Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/components/Home/RunSection/RunRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { runAnnotationsQueryOptions } from "@/services/runAnnotations";
import {
getAnnotationValue,
getPipelineTagsFromAnnotations,
RUN_REQUESTED_BY_ANNOTATION,
RUN_SOURCE_ANNOTATION,
} from "@/utils/annotations";
import { formatDate } from "@/utils/date";
Expand Down Expand Up @@ -65,6 +66,10 @@ const RunRow = ({
const name = run.pipeline_name ?? "Unknown pipeline";
const tags = getPipelineTagsFromAnnotations(annotations);
const source = getAnnotationValue(annotations, RUN_SOURCE_ANNOTATION);
const requestedBy = getAnnotationValue(
annotations,
RUN_REQUESTED_BY_ANNOTATION,
);

const createdBy = run.created_by ?? "Unknown user";
const truncatedCreatedBy = truncateMiddle(createdBy);
Expand Down Expand Up @@ -185,7 +190,11 @@ const RunRow = ({
</TableCell>
<TableCell className="w-0">
<InlineStack gap="2" blockAlign="center" wrap="nowrap">
<RunSourceIcon source={source} className="opacity-50" />
<RunSourceIcon
source={source}
requestedBy={requestedBy}
className="opacity-50"
/>
<TooltipButton
tooltip="Share Run"
onClick={handleShare}
Expand Down
9 changes: 8 additions & 1 deletion src/components/PipelineRun/RunDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
getAnnotationValue,
getPipelineTagsFromSpec,
PIPELINE_NOTES_ANNOTATION,
RUN_REQUESTED_BY_ANNOTATION,
RUN_SOURCE_ANNOTATION,
SYSTEM_ANNOTATIONS,
} from "@/utils/annotations";
Expand Down Expand Up @@ -53,6 +54,10 @@ export const RunDetails = () => {
...runAnnotationsQueryOptions(runId, backendUrl),
});
const runSource = getAnnotationValue(runAnnotations, RUN_SOURCE_ANNOTATION);
const requestedBy = getAnnotationValue(
runAnnotations,
RUN_REQUESTED_BY_ANNOTATION,
);

const handleCopyUrl = () => {
copyToClipboard(window.location.href);
Expand Down Expand Up @@ -127,7 +132,9 @@ export const RunDetails = () => {
{metadata && (
<KeyValueList
title="Run Info"
titleAction={<RunSourceIcon source={runSource} />}
titleAction={
<RunSourceIcon source={runSource} requestedBy={requestedBy} />
}
items={[
{ label: "Run Id", value: metadata.id },
{ label: "Execution Id", value: metadata.root_execution_id },
Expand Down
12 changes: 12 additions & 0 deletions src/components/shared/RunSource.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@ describe("getRunSourceMessage", () => {
expect(getRunSourceMessage("tangent")).toBe("Submitted by a Tangent agent");
});

it.each(["tangent", "tangent-ui"])(
"names the person who requested a %s run",
(source) => {
expect(getRunSourceMessage(source, "person@example.com")).toBe(
"Submitted by person@example.com via Tangent",
);
expect(getRunSourceMessage("web-app", "person@example.com")).toBe(
"Submitted via the Tangle web app",
);
},
);

/** Anything may submit a run, so the map is a reader's vocabulary. */
it("falls back for a submitter it has never heard of", () => {
expect(getRunSourceMessage("some-future-tool")).toBe(
Expand Down
21 changes: 17 additions & 4 deletions src/components/shared/RunSource.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,26 +61,39 @@ export const hasRunSource = (source?: string | null): boolean =>
Boolean(source);

/** Human-readable message describing how a run was submitted. */
export const getRunSourceMessage = (source?: string | null): string =>
getRunSourceConfig(source).message;
export const getRunSourceMessage = (
source?: string | null,
requestedBy?: string,
): string => {
if (
requestedBy &&
(source === TANGENT_AGENT_RUN_SOURCE || source === TANGENT_UI_RUN_SOURCE)
) {
return `Submitted by ${requestedBy} via Tangent`;
}
return getRunSourceConfig(source).message;
};

interface RunSourceIconProps {
requestedBy?: string;
source?: string | null;
size?: "xs" | "sm" | "md";
className?: string;
}

export const RunSourceIcon = ({
source,
requestedBy,
size = "sm",
className,
}: RunSourceIconProps) => {
const { icon, message } = getRunSourceConfig(source);
const { icon } = getRunSourceConfig(source);
const message = getRunSourceMessage(source, requestedBy);

return (
<Tooltip>
<TooltipTrigger asChild>
<span className={className}>
<span role="img" aria-label={message} className={className}>
<Icon name={icon} size={size} className="text-muted-foreground" />
</span>
</TooltipTrigger>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,26 @@ afterEach(() => {
});

describe("<RunDetailsContent/>", () => {
it.each<[string, string | undefined, string]>([
[
"tangent",
"matt@example.test",
"Submitted by matt@example.test via Tangent",
],
["tangent", undefined, "Submitted by a Tangent agent"],
])(
"shows the Run Info byline for a %s run requested by %s",
async (source, requester, expected) => {
fetchRunAnnotations.mockResolvedValue({
source,
requested_by: requester,
});
renderPanel(<RunDetailsContent offersTangentHandoff />);
expect(await screen.findByText(expected)).toBeVisible();
expect(screen.getByRole("img", { name: expected })).toBeInTheDocument();
},
);

it("shows run annotations", async () => {
fetchRunAnnotations.mockResolvedValue({
experiment: "baseline",
Expand Down
13 changes: 11 additions & 2 deletions src/routes/v2/pages/RunView/components/RunDetailsContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
isSystemRunAnnotation,
PIPELINE_NOTES_ANNOTATION,
PIPELINE_TAGS_ANNOTATION,
RUN_REQUESTED_BY_ANNOTATION,
RUN_SOURCE_ANNOTATION,
SYSTEM_ANNOTATIONS,
} from "@/utils/annotations";
Expand Down Expand Up @@ -297,6 +298,10 @@ function RunInfoSection({ metadata }: { metadata: PipelineRunResponse }) {
const { data: runAnnotations } = useRunAnnotations(metadata.id);

const runSource = getAnnotationValue(runAnnotations, RUN_SOURCE_ANNOTATION);
const requestedBy = getAnnotationValue(
runAnnotations,
RUN_REQUESTED_BY_ANNOTATION,
);
const hasKnownSource = hasRunSource(runSource);

return (
Expand All @@ -317,9 +322,13 @@ function RunInfoSection({ metadata }: { metadata: PipelineRunResponse }) {

{hasKnownSource && (
<InlineStack gap="1" blockAlign="center" wrap="nowrap">
<RunSourceIcon source={runSource} size="xs" />
<RunSourceIcon
source={runSource}
requestedBy={requestedBy}
size="xs"
/>
<Text size="xs" tone="subdued">
{getRunSourceMessage(runSource)}
{getRunSourceMessage(runSource, requestedBy)}
</Text>
</InlineStack>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const ProjectChatArea = observer(function ProjectChatArea() {
const references = useChatReferences(store.projectId);
const { createdBy } = useProjectAuthor();
const recordContribution = useRecordProjectContribution();
const commands = useChatCommands(store.projectId);
const commands = useChatCommands(store.projectId, createdBy);
const refreshSessionResources = useRefreshSessionResources();
const activeSessionId = store.activeSessionId;

Expand Down
59 changes: 51 additions & 8 deletions src/routes/v2/pages/Tangent/hooks/useChatCommands.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { EmbedCommand } from "@tangent/embed-react";
import { renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";

Expand All @@ -11,7 +10,12 @@ const fakes = vi.hoisted(() => ({
listEntries: vi.fn(),
listFiles: vi.fn(),
resolvePipeline: vi.fn(),
submit: vi.fn(),
submit:
vi.fn<
(
deps: BridgeDeps,
) => Promise<{ success: boolean; runId?: string; error?: string }>
>(),
recordSessionRun: vi.fn(),
}));

Expand Down Expand Up @@ -67,8 +71,10 @@ const TRAIN = {
archived: false,
};

function commandNamed(name: string): EmbedCommand {
const { result } = renderHook(() => useChatCommands("project-1"));
function commandNamed(name: string, currentUserId = "first@example.com") {
const { result } = renderHook(() =>
useChatCommands("project-1", currentUserId),
);
const command = result.current.find((candidate) => candidate.name === name);
if (!command) throw new Error(`No /${name} command`);
return command;
Expand Down Expand Up @@ -121,16 +127,22 @@ describe("useChatCommands", () => {
it("starts each pipeline it's given, puts it in the chat, and reports the rest", async () => {
fakes.submit.mockResolvedValue({ success: true, runId: "r-9" });

const text = await commandNamed("run").run("[p-1, nope]");
const text = await commandNamed("run").run(
"[p-1, nope]",
"first@example.com",
);

expect(fakes.resolvePipeline).toHaveBeenCalledWith({
source: "remote",
backendUrl: "https://backend.example",
pipelineId: "p-1",
});
const [deps] = fakes.submit.mock.calls[0] as [BridgeDeps];
const [deps] = fakes.submit.mock.calls[0];
expect(deps.getSpec()?.name).toBe("Train");
expect(Object.values(deps.getRunAnnotations?.() ?? {})).toEqual(["true"]);
expect(deps.getRunAnnotations?.()).toEqual({
"tangleml.com/project/id/project-1": "true",
requested_by: "first@example.com",
});
expect(fakes.recordSessionRun).toHaveBeenCalledWith(
"chat-1",
"r-9",
Expand All @@ -141,13 +153,44 @@ describe("useChatCommands", () => {
expect(text).toContain("- `nope`: not one of this project's pipelines");
});

it.each([undefined, "guest@example.com"])(
"leaves the requester unset when the sender is %s",
async (authorId) => {
fakes.submit.mockResolvedValue({ success: true, runId: "r-1" });
await commandNamed("run").run("p-1", authorId);
const [deps] = fakes.submit.mock.calls[0];
expect(deps.getRunAnnotations?.()).not.toHaveProperty("requested_by");
expect(recordContribution).not.toHaveBeenCalled();
},
);

it("keeps overlapping requests with the people who sent them", async () => {
const first = Promise.withResolvers<{ success: boolean; runId: string }>();
fakes.submit
.mockReturnValueOnce(first.promise)
.mockResolvedValueOnce({ success: true, runId: "second" });
const a = commandNamed("run").run("p-1", "first@example.com");
await vi.waitFor(() => expect(fakes.submit).toHaveBeenCalledOnce());
await commandNamed("run", "second@example.com").run(
"p-1",
"second@example.com",
);
first.resolve({ success: true, runId: "first" });
await a;
expect(
fakes.submit.mock.calls.map(
([deps]) => deps.getRunAnnotations?.()?.requested_by,
),
).toEqual(["first@example.com", "second@example.com"]);
});

it("reports why the backend didn't start a pipeline", async () => {
fakes.submit.mockResolvedValue({
success: false,
error: "A required input has no value.",
});

const text = await commandNamed("run").run("p-1");
const text = await commandNamed("run").run("p-1", "first@example.com");

expect(text).toContain("`p-1` (Train): A required input has no value.");
expect(fakes.recordSessionRun).not.toHaveBeenCalled();
Expand Down
15 changes: 10 additions & 5 deletions src/routes/v2/pages/Tangent/hooks/useChatCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
import { useRecordProjectContribution } from "@/services/projects/useProjectContributors";
import { runExecutionStatsQuery } from "@/services/projects/useProjectRuns";
import { useTeamForSubmission } from "@/services/teams/useTeamForSubmission";
import { RUN_REQUESTED_BY_ANNOTATION } from "@/utils/annotationKeys";
import { buildProjectRunAnnotationKey } from "@/utils/annotations";
import {
getExecutionStatusLabel,
Expand All @@ -56,7 +57,7 @@ import { PIPELINE_YAML_LOAD_OPTIONS } from "@/utils/yaml";
* project card does, and `/run` starts pipelines by id. None of them starts
* the agent; it's sent their results with the next message.
*/
export function useChatCommands(projectId: string): EmbedCommand[] {
export function useChatCommands(projectId: string, currentUserId?: string) {
const store = useTangentProject();
const handlers = useProjectCardHandlers();
const storage = usePipelineStorage();
Expand Down Expand Up @@ -139,6 +140,7 @@ export function useChatCommands(projectId: string): EmbedCommand[] {
id: string,
pipelines: ProjectCardEntry[],
sessionId: string | undefined,
requestedBy: string | undefined,
): Promise<RunStart> {
const pipeline = pipelines.find(({ target }) => targetId(target) === id);
if (!pipeline) return { id, error: "not one of this project's pipelines" };
Expand All @@ -153,13 +155,14 @@ export function useChatCommands(projectId: string): EmbedCommand[] {
queryClient,
getRunAnnotations: () => ({
[buildProjectRunAnnotationKey(projectId)]: "true",
...(requestedBy && { [RUN_REQUESTED_BY_ANNOTATION]: requestedBy }),
}),
getRunTeam: () => runTeamRef.current,
}).submitPipelineRun();
if (!result.success || !result.runId) {
return { id, name: pipeline.name, error: result.error };
}
recordContribution(projectId);
if (requestedBy) recordContribution(projectId);
if (sessionId) {
// Best effort: the run has started whether or not the chat noted it.
await recordSessionRun(sessionId, result.runId, pipeline.name).catch(
Expand Down Expand Up @@ -212,25 +215,27 @@ export function useChatCommands(projectId: string): EmbedCommand[] {
name: "run",
description: "Start pipelines by id",
argumentHint: "<ids>",
run: async (args) => {
run: async (args: string, authorId?: string) => {
if (parsePipelineIds(args).length === 0) {
throw new Error(
"add pipeline ids separated by commas. /pipelines lists them.",
);
}
// The person may open another chat while these start.
const sessionId = store.activeSessionId;
const requestedBy =
authorId === currentUserId ? currentUserId : undefined;
const { pipelines } = await handlers.listEntries();
const ids = parsePipelineIds(
args,
pipelines.map(({ target }) => targetId(target)),
);
const starts: RunStart[] = [];
for (const id of ids) {
starts.push(await start(id, pipelines, sessionId));
starts.push(await start(id, pipelines, sessionId, requestedBy));
}
return runStartsResult(starts);
},
},
];
] satisfies EmbedCommand[];
}
1 change: 1 addition & 0 deletions src/utils/annotationKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const PIPELINE_TAGS_ANNOTATION = "tags";
export const PIPELINE_CANONICAL_NAME_ANNOTATION = "canonical-pipeline-name";
export const RUN_NAME_TEMPLATE_ANNOTATION = "run-name-template";
export const RUN_SOURCE_ANNOTATION = "source";
export const RUN_REQUESTED_BY_ANNOTATION = "requested_by";
export const EDITOR_POSITION_ANNOTATION = "editor.position";
export const EDITOR_COLLAPSED_ANNOTATION = "editor.collapsed";
export const EDITOR_FLOW_DIRECTION_ANNOTATION = "editor.flow-direction";
Expand Down
Loading