Skip to content
Open
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
8 changes: 4 additions & 4 deletions frontend-v2/README.md

Large diffs are not rendered by default.

241 changes: 240 additions & 1 deletion frontend-v2/e2e/workflow-runs.spec.ts

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions frontend-v2/src/features/chat/workflow-run/node-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import type { Conversation } from '@/components/agent-thread/model/types'
/**
* Follows one node attempt's session over v2-server's node events stream and folds it as the chat
* page folds a conversation's, so the run page shows the Agent's whole turn: its thinking, tool
* calls and answer, live while it runs. `conversation` is null until the first event arrives, and
* stays null when the stream is refused (an attempt not dispatched yet, or a session that belongs
* to whoever else started the run), so the page keeps showing what the attempt recorded; `refused`
* says the server turned the stream away, which the browser only shows as a stream that closed for
* good before sending anything.
* calls and answer, live while it runs for any member of the workspace. `conversation` is null
* until the first event arrives, and stays null when the stream is unavailable (e.g. an attempt not
* dispatched yet), so the page keeps showing what the attempt recorded; `refused` says the server
* turned the stream away, which the browser only shows as a stream that closed for good before
* sending anything.
*/
export function useNodeSession(
tenantId: string,
Expand Down
41 changes: 38 additions & 3 deletions frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ describe('workflow runs in chat', () => {
await user.click(within(start).getByRole('button', { name: '启动' }))
expect(within(pane).getByRole('button', { name: '舞台' })).toHaveAttribute('aria-pressed', 'true')
await waitFor(() => expect(within(project()).getByRole('button', { name: '工作流运行 审查 cloud#210(成功)' })).toBeInTheDocument(), { timeout: 25_000 })
expect(within(pane).getByText('由 演示用户 发起')).toBeInTheDocument()
expect(within(within(project()).getByRole('button', { name: '工作流运行 审查 cloud#210(成功)' })).getByText('由 演示用户 发起')).toBeInTheDocument()
// The run went pending → running → succeeded under polling; its frozen graph was analyzed once.
expect(workflows.seen.filter((request) => request.endsWith('/workflows/analyze'))).toHaveLength(1)
expect(await within(pane).findByText('运行完成')).toBeInTheDocument()
Expand Down Expand Up @@ -418,24 +420,57 @@ describe('workflow runs in chat', () => {
expect(stream.closed).toBe(true)
}, 30_000)

it("tells a member that a running node's live session belongs to whoever started the run", async () => {
it('lets another workspace member see the starter and follow the full live node session', async () => {
runs.hold = true
const user = userEvent.setup()
await renderPage()
await createRun(user, '别人的运行')
const pane = await screen.findByRole('region', { name: '工作流运行' })
await within(pane).findByRole('heading', { level: 2, name: '别人的运行' }, { timeout: 10_000 })
const [entry] = [...runs.runs.values()]
entry!.detail.startedBy = 'user-alice'
entry!.detail.run.startedByName = '爱丽丝'
await user.click(within(pane).getByRole('button', { name: '启动' }))
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: '启动' }))

expect(await within(pane).findByText('由 爱丽丝 发起')).toBeInTheDocument()
const row = within(project()).getByRole('button', { name: '工作流运行 别人的运行(运行中)' })
expect(within(row).getByText('由 爱丽丝 发起')).toBeInTheDocument()

await user.click(await within(pane).findByRole('button', { name: '查看节点会话' }))
expect(within(pane).getByText('正在准备…')).toBeInTheDocument()

const attempt = entry!.detail.nodes.find((n) => n.nodeType === 'agent')!
const stream = FakeEventSource.all.find((s) => s.url.endsWith(`/nodes/${attempt.id}/events`))!
act(() => {
stream.emit({
kind: 'history_snapshot',
history: { records: [line.user(1, '请审查变更'), line.say(2, '正在检查差异…')], incomplete: true },
})
})
expect(await within(pane).findByText('请审查变更')).toBeInTheDocument()
expect(within(pane).getByText('正在检查差异…')).toBeInTheDocument()
expect(within(pane).queryByText(/只有启动这次运行的人能查看实时会话/)).not.toBeInTheDocument()
}, 30_000)

it('shows an unavailable notice when a node session stream closes before any event arrives', async () => {
runs.hold = true
const user = userEvent.setup()
await renderPage()
await createRun(user, '失效会话的运行')
const pane = await screen.findByRole('region', { name: '工作流运行' })
await within(pane).findByRole('heading', { level: 2, name: '失效会话的运行' }, { timeout: 10_000 })
await user.click(within(pane).getByRole('button', { name: '启动' }))
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: '启动' }))
await user.click(await within(pane).findByRole('button', { name: '查看节点会话' }))
expect(within(pane).getByText('正在准备…')).toBeInTheDocument()

// v2-server answers 404 to anyone but the run's starter; the browser closes the stream for good.
const [entry] = [...runs.runs.values()]
const attempt = entry!.detail.nodes.find((n) => n.nodeType === 'agent')!
const stream = FakeEventSource.all.find((s) => s.url.endsWith(`/nodes/${attempt.id}/events`))!
act(() => stream.refuse())
expect(within(pane).getByText('只有启动这次运行的人能查看实时会话;节点完成后会显示任务和回答。')).toBeInTheDocument()
expect(within(pane).getByText('无法读取这个节点的实时会话;节点完成后会显示任务和回答。')).toBeInTheDocument()
expect(within(pane).queryByText(/只有启动这次运行的人能查看实时会话/)).not.toBeInTheDocument()
}, 30_000)

it('stops a run that is still executing', async () => {
Expand Down
3 changes: 3 additions & 0 deletions frontend-v2/src/features/chat/workflow-run/run-pane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,9 @@ function RunWorkspace({ tenantId, run, readOnly, hostedWorkspace, leading, refre
<FadeText text={run.name} />
{run.taskId && <Link className="text-xs underline shrink-0" to={`/collaboration/tasks/${run.taskId}?tab=workflows&workflow=${run.id}`}>返回任务</Link>}
</h2>
{run.startedByName && (
<span className="shrink-0 text-xs text-muted-foreground">由 {run.startedByName} 发起</span>
)}
<Badge variant="outline" className={cn('gap-1.5', tone.badge)}>
<span className={cn('size-1.5 rounded-full', tone.dot)} />
{runStatusLabel(run.status)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const definition = normalizeWorkflowDefinition({
})

const emptyDetail = (id: string): WorkflowRunDetail => ({
run: { id, workflowId: 'wf', snapshotId: 's', projectId: 'p', name: '运行', status: 'failed', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 },
run: { id, workflowId: 'wf', snapshotId: 's', projectId: 'p', name: '运行', status: 'failed', startedByName: '', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 },
nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null,
})

Expand Down Expand Up @@ -143,3 +143,4 @@ describe('resume eligibility', () => {
expect(runKeys.resumePreview('t', 'r').slice(0, runKeys.run('t', 'r').length)).toEqual([...runKeys.run('t', 'r')])
})
})

11 changes: 8 additions & 3 deletions frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,16 +200,21 @@ function RunRow({ tenantId, projectId, run }: { tenantId: string; projectId: str
const tone = runStatusTone(run.status)
const label = runStatusLabel(run.status)
return (
<div className={cn('group/run flex h-8 items-center rounded-md pr-1 text-sm', selected ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/60')}>
<div className={cn('group/run flex min-h-8 items-center rounded-md pr-1 text-sm', selected ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/60')}>
<button
type="button"
className="flex h-full min-w-0 flex-1 items-center gap-2 px-2 text-left"
className="flex h-full min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left"
aria-current={selected ? 'page' : undefined}
aria-label={`工作流运行 ${run.name}(${label})`}
onClick={() => selectRun(run.id)}
>
<WorkflowIcon className="size-3.5 shrink-0 text-muted-foreground" />
<FadeText text={run.name} className="flex-1" />
<span className="flex min-w-0 flex-1 flex-col">
<FadeText text={run.name} />
{run.startedByName && (
<span className="truncate text-xs text-muted-foreground">由 {run.startedByName} 发起</span>
)}
</span>
<span title={label} className={cn('size-2 shrink-0 rounded-full', tone.dot, isNodeWorking(run.status) && 'animate-pulse')} />
</button>
<DropdownMenu>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ function nodeRun(over: Partial<WorkflowNodeRun>): WorkflowNodeRun {
function rail(a: Partial<WorkflowNodeRun>) {
const detail: WorkflowRunDetail = {
run: {
id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'awaitingInput', state: '{"current_nodes":["a"]}',
id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'awaitingInput', startedByName: 'Alice', state: '{"current_nodes":["a"]}',
input: '需求', output: null, error: null, startedAt: 1_000, finishedAt: null, createdAt: 500, updatedAt: 2_000,
},
nodes: [nodeRun({ id: 'start-run' }), nodeRun({ id: 'a-run', nodeId: 'a', nodeType: 'agent', sessionId: 'session-1', finishedAt: null, ...a })],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function graphNode(id: string, kind: (typeof definition.nodes)[number]['data']['
function detail(over: Partial<WorkflowRunDetail['run']>, nodes: WorkflowNodeRun[], conditionDecisions: Record<string, string> = {}): WorkflowRunDetail {
return {
run: {
id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'running', state: '{"current_nodes":["a"]}',
id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'running', startedByName: '', state: '{"current_nodes":["a"]}',
input: '需求', output: null, error: null, startedAt: 1_000, finishedAt: null, createdAt: 500, updatedAt: 2_000,
...over,
},
Expand Down Expand Up @@ -517,4 +517,11 @@ describe('attempts a resume from failure replaced', () => {
const adjacent = nodeRun({ id: 'a4', nodeId: 'a', nodeType: 'agent', status: 'failed', payload: JSON.stringify({ error_detail: { kind: 'session', attempt: 4 } }) })
expect(labels([adjacent], [3])).toEqual([[3, 'manual_resume']])
})

it('preserves the starter identity and display name on the adapted run', () => {
const graph = normalizeWorkflowDefinition({ ...definition, nodes: [graphNode('start', 'start'), graphNode('a', 'agent')], edges: [{ id: 'e1', source: 'start', target: 'a' }] })
const adapted = toGraphWorkflowRun({ ...detail({ startedByName: 'Alice' }, []), startedBy: 'user-alice' }, graph)
expect(adapted.startedBy).toBe('user-alice')
expect(adapted.startedByName).toBe('Alice')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ export function toGraphWorkflowRun(detail: WorkflowRunDetail, definition: Workfl
definitionSnapshot: withRunStartValues(definition, detail),
name: run.name,
status,
startedByName: run.startedByName,
nodeStates,
rounds,
roundStates,
Expand Down
15 changes: 13 additions & 2 deletions frontend-v2/src/features/chat/workflow-run/server-runs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it } from 'vitest'
import { sampleWorkflowBackend, serveWorkflows, type WorkflowServer } from '@/lib/workflows/test/workflow-server'
import { chatBackend, tenantId } from '../test-backend'
import { runSnapshotQuery, useRunStartPreflight, useRunUnappliedSettings } from './server-runs'
import { projectRunsQuery, runSnapshotQuery, useRunStartPreflight, useRunUnappliedSettings } from './server-runs'
import { serveRuns, type RunServer } from './test-run-server'

const wrapper = ({ children }: { children: ReactNode }) => (
Expand Down Expand Up @@ -47,7 +47,7 @@ describe('the run analysis', () => {
const { published } = workflows.backend.get({ workflowId })
runs.runs.set(runId, {
detail: {
run: { id: runId, workflowId, snapshotId: published!.id, projectId: 'p', name: '冻结', status: 'failed', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 },
run: { id: runId, workflowId, snapshotId: published!.id, projectId: 'p', name: '冻结', status: 'failed', startedByName: '', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 },
nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null,
},
graph: published!.graph,
Expand Down Expand Up @@ -79,4 +79,15 @@ describe('the run analysis', () => {
await expect(waitFor(() => expect(analyses()).toBeGreaterThan(1), { timeout: 300 })).rejects.toThrow()
expect(snapshotReads()).toBe(1)
})

it('keeps the starter display name on project run list items', async () => {
const entry = runs.runs.get(runId)!
entry.detail.run.startedByName = '爱丽丝'
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const own = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
const { result } = renderHook(() => useQuery(projectRunsQuery(tenantId, 'p')), { wrapper: own })
await waitFor(() => expect(result.current.data).toHaveLength(1))
expect(result.current.data![0]).toMatchObject({ id: runId, startedByName: '爱丽丝' })
})
})

17 changes: 15 additions & 2 deletions frontend-v2/src/features/chat/workflow-run/server-runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,18 @@ export interface RunListItem {
id: string
name: string
status: GraphWorkflowRunStatus
startedByName?: string
createdAt: string
}

function listItem(summary: WorkflowRunSummary): RunListItem {
return { id: summary.id, name: summary.name, status: toDisplayRunStatus(summary.status), createdAt: new Date(summary.createdAt).toISOString() }
return {
id: summary.id,
name: summary.name,
status: toDisplayRunStatus(summary.status),
startedByName: summary.startedByName,
createdAt: new Date(summary.createdAt).toISOString(),
}
}

/** A project's runs, newest first; read again while any of them still executes. */
Expand All @@ -239,7 +246,13 @@ export function projectRunsQuery(tenantId: string, projectId: string) {
staleTime: 0,
queryFn: async ({ signal }) => {
const { runs } = await call(() => listWorkflowRuns(tenantId, { projectId }, undefined, signal))
const local = cdaseProjectRuns(tenantId, projectId).map(({ id, name, status, createdAt }) => ({ id, name, status, createdAt }))
const local = cdaseProjectRuns(tenantId, projectId).map(({ id, name, status, startedByName, createdAt }) => ({
id,
name,
status,
startedByName,
createdAt,
}))
return [...local, ...runs.map(listItem)].sort((a, b) => b.createdAt.localeCompare(a.createdAt))
},
refetchInterval: (query) => (query.state.data?.some((run) => !isTerminalRunStatus(run.status)) ? runRefreshMs.interval : false),
Expand Down
10 changes: 8 additions & 2 deletions frontend-v2/src/features/chat/workflow-run/test-run-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS
const at = now()
const run: WorkflowRun = {
id: `run-${++ids}`, workflowId: created[1]!, snapshotId: published.id, projectId: body.projectId as string,
name: (body.name as string | undefined) ?? '', status: 'pending', state: JSON.stringify({ current_nodes: [] }),
name: (body.name as string | undefined) ?? '', status: 'pending', startedByName: '',
state: JSON.stringify({ current_nodes: [] }),
input: null, output: null, error: null, startedAt: null, finishedAt: null, createdAt: at, updatedAt: at,
}
server.runs.set(run.id, { detail: { run, nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null }, graph: published.graph, version: published.version })
Expand All @@ -157,7 +158,10 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS
const projectId = (config.params as { projectId?: string } | undefined)?.projectId
const runs = [...server.runs.values()]
.filter(({ detail }) => projectId === undefined || detail.run.projectId === projectId)
.map(({ detail: { run }, version }) => ({ id: run.id, name: run.name, projectId: run.projectId, workflowId: run.workflowId, version, status: run.status, startedAt: run.startedAt, finishedAt: run.finishedAt, createdAt: run.createdAt }))
.map(({ detail: { run }, version }) => ({
id: run.id, name: run.name, projectId: run.projectId, workflowId: run.workflowId, version, status: run.status,
startedByName: run.startedByName, startedAt: run.startedAt, finishedAt: run.finishedAt, createdAt: run.createdAt,
}))
return respond(config, 200, { runs })
}
const [, runId, action = ''] = url.slice(runsBase.length).match(/^\/([^/]+)(\/[a-z-]+)?$/) ?? []
Expand All @@ -182,6 +186,8 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS
if (action === '/start') {
if (run.status !== 'pending') return refuse(config, 400, 'workflow_run_start_failed')
run.status = 'running'
entry.detail.startedBy = entry.detail.startedBy || 'user-me'
run.startedByName = run.startedByName || '演示用户'
run.startedAt = now()
execute(entry)
return respond(config, 200, { run })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { animateOverlayWidth } from "./theater-overlay-motion";

describe("animateOverlayWidth", () => {
afterEach(() => {
vi.restoreAllMocks();
});

it("anchors progress to the first animation frame clock rather than performance.now()", () => {
const frames: Array<(time: number) => void> = [];
vi.spyOn(window, "matchMedia").mockReturnValue({
matches: false,
} as MediaQueryList);
vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
frames.push(cb);
return frames.length;
});
vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined);
// Simulate a large offset between performance.now() and rAF frame timestamps.
vi.spyOn(performance, "now").mockReturnValue(10_000);

const widths: number[] = [];
const onCollapsed = vi.fn();
const onComplete = vi.fn();
const animationRef = { current: null as number | null };

animateOverlayWidth({
animationRef,
duration: 200,
fromWidth: 0,
targetWidth: 320,
onFrame: (width) => widths.push(width),
onCollapsed,
onComplete,
});

expect(frames).toHaveLength(1);
frames[0]!(50);
frames[1]!(150);
frames[2]!(250);

expect(widths[0]).toBe(0);
expect(widths[1]).toBe(280);
expect(widths[2]).toBe(320);
expect(onCollapsed).not.toHaveBeenCalled();
expect(onComplete).toHaveBeenCalledTimes(1);
expect(animationRef.current).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,14 @@ export function animateOverlayWidth({
return;
}

const startedAt = window.performance.now();
// Anchor to the first rAF timestamp so progress uses the same clock as frames even when rAF and
// performance.now() have different origins (e.g. after module-load offset in jsdom).
let startedAt: number | null = null;
const animate = (now: number): void => {
const progress = Math.min(1, (now - startedAt) / duration);
if (startedAt === null) {
startedAt = now;
}
const progress = duration <= 0 ? 1 : Math.max(0, Math.min(1, (now - startedAt) / duration));
const easedProgress = 1 - (1 - progress) ** 3;
onFrame(fromWidth + (targetWidth - fromWidth) * easedProgress);
if (progress < 1) {
Expand Down
Loading
Loading