Skip to content

Commit 7c5ef5f

Browse files
committed
fix(mothership): skip the 30s workflow pickup wait when no chat view is reading
A client-routed workflow tool waited 30s for a chat view to pick it up before the server ran it, even when no view was reading the turn's stream at all (tab closed, user on another chat or page). Dispatch now checks whether the send's own response is still attached or a reconnected reader holds a short-lived Redis mark; with neither, it waits only 5s for a view that is re-attaching. A present view keeps the full grace, and an unknown (no Redis, failed read) counts as present.
1 parent 10b0baa commit 7c5ef5f

10 files changed

Lines changed: 220 additions & 8 deletions

File tree

‎apps/sim/app/api/copilot/chat/stream/route.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ vi.mock('@/lib/mothership/request/session', () => ({
3131
readEvents,
3232
readFilePreviewSessions,
3333
findReplayGap,
34+
holdStreamViewer: () => () => {},
3435
readRingPosition: async () => ({ requestedAfterSeq: 0, oldestSeq: 0, latestSeq: 0 }),
3536
ringCanServe: () => true,
3637
replayGapTerminal: async () => ({ gapDetected: true, envelopes: [] }),

‎apps/sim/app/api/copilot/chat/stream/route.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
encodeSSEEnvelope,
3636
findReplayGap,
3737
forwardRunReplay,
38+
holdStreamViewer,
3839
isTerminalStreamStatus,
3940
openRunReplay,
4041
RunReplayUnavailableError,
@@ -397,6 +398,8 @@ async function handleResumeRequestBody({
397398
controllerClosed = true
398399
}
399400
request.signal.addEventListener('abort', abortListener, { once: true })
401+
// An attached reader is a chat view that starts this turn's workflow tools.
402+
const releaseViewer = holdStreamViewer(streamId)
400403

401404
/** Delivers the ring's events after the cursor, or returns null if it trimmed the next one. */
402405
const flushEvents = async (): Promise<number | null> => {
@@ -591,6 +594,7 @@ async function handleResumeRequestBody({
591594
}
592595
markSpanForError(rootSpan, error)
593596
} finally {
597+
releaseViewer()
594598
request.signal.removeEventListener('abort', abortListener)
595599
// Read before closing: closing the controller here is this route ending, not the client.
596600
const clientDisconnected = controllerClosed

‎apps/sim/lib/mothership/constants.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,13 @@ export const CHAT_RUN_DEADLINE_MS = 3_600_000
6666
*/
6767
export const COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS = 30_000
6868

69+
/**
70+
* The workflow grace when no chat view is reading the turn's stream at dispatch: a tab closed,
71+
* a switch to another chat or page. It only bridges a view that is re-attaching right then (a
72+
* reload, a reconnect after a network drop), which reads the call within a reconnect poll.
73+
*/
74+
export const COPILOT_WORKFLOW_TOOL_NO_VIEWER_GRACE_MS = 5_000
75+
6976
/**
7077
* How long a desktop tool call (browser, terminal, local import) waits for the desktop app to
7178
* claim it before it fails as never started.

‎apps/sim/lib/mothership/request/handlers/handlers.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,6 +1363,75 @@ describe('sse-handlers tool lifecycle', () => {
13631363
expect(workflowResults[0].payload.executor).toBe(MothershipStreamV1ToolExecutor.sim)
13641364
})
13651365

1366+
describe('workflow tool pickup grace', () => {
1367+
/** Dispatches a workflow call whose browser wait only ends when the server takes it over. */
1368+
async function dispatchUnpickedWorkflowCall(toolCallId: string, hasClientViewer: boolean) {
1369+
waitForWorkflowToolCompletion.mockImplementationOnce(
1370+
({ abortSignal }: { abortSignal?: AbortSignal }) =>
1371+
new Promise((resolve) => abortSignal?.addEventListener('abort', () => resolve(null)))
1372+
)
1373+
claimWorkflowToolExecution.mockResolvedValueOnce({ toolCallId })
1374+
executeTool.mockResolvedValueOnce({ success: true, output: {} })
1375+
await sseHandlers.tool(
1376+
{
1377+
type: MothershipStreamV1EventType.tool,
1378+
payload: {
1379+
toolCallId,
1380+
toolName: 'run_workflow',
1381+
arguments: { workflowId: 'workflow-1' },
1382+
executor: MothershipStreamV1ToolExecutor.client,
1383+
mode: MothershipStreamV1ToolMode.async,
1384+
phase: MothershipStreamV1ToolPhase.call,
1385+
},
1386+
} satisfies StreamEvent,
1387+
context,
1388+
execContext,
1389+
{ interactive: true, hasClientViewer: async () => hasClientViewer }
1390+
)
1391+
}
1392+
1393+
it('runs a call no chat view is reading on the server after the short grace', async () => {
1394+
vi.useFakeTimers()
1395+
try {
1396+
await dispatchUnpickedWorkflowCall('tool-no-viewer', false)
1397+
await vi.advanceTimersByTimeAsync(5_000)
1398+
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
1399+
'tool-no-viewer',
1400+
expect.any(String),
1401+
'sim'
1402+
)
1403+
1404+
await Promise.allSettled(context.pendingToolPromises.values())
1405+
expect(executeTool.mock.calls.at(-1)?.[0]).toBe('run_workflow')
1406+
} finally {
1407+
vi.useRealTimers()
1408+
}
1409+
})
1410+
1411+
it('keeps waiting the full grace for a call a chat view is reading', async () => {
1412+
vi.useFakeTimers()
1413+
try {
1414+
await dispatchUnpickedWorkflowCall('tool-viewer', true)
1415+
await vi.advanceTimersByTimeAsync(29_000)
1416+
expect(claimWorkflowToolExecution).not.toHaveBeenCalledWith(
1417+
'tool-viewer',
1418+
expect.any(String),
1419+
'sim'
1420+
)
1421+
1422+
await vi.advanceTimersByTimeAsync(1_000)
1423+
await Promise.allSettled(context.pendingToolPromises.values())
1424+
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
1425+
'tool-viewer',
1426+
expect.any(String),
1427+
'sim'
1428+
)
1429+
} finally {
1430+
vi.useRealTimers()
1431+
}
1432+
})
1433+
})
1434+
13661435
it('claims and runs the same workflow when the call omits an explicit workflowId', async () => {
13671436
// The waiter resolves the target via resolveWorkflowToolTargetId(args, ctx)
13681437
// while the handler resolves it as params.workflowId || context.workflowId.

‎apps/sim/lib/mothership/request/handlers/tool.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { getAsyncToolCall, upsertAsyncToolCall } from '@/lib/mothership/async-ru
1818
import {
1919
CLIENT_TOOL_RESULT_TIMEOUT_MS,
2020
COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS,
21+
COPILOT_WORKFLOW_TOOL_NO_VIEWER_GRACE_MS,
2122
DESKTOP_TOOL_PICKUP_GRACE_MS,
2223
} from '@/lib/mothership/constants'
2324
import {
@@ -239,6 +240,19 @@ function desktopClaimsLocalReads(
239240
return options?.desktopClaimsLocalReads === true || desktopDeviceId !== null
240241
}
241242

243+
/**
244+
* How long a workflow tool waits for a chat view to pick it up before the server runs it. The
245+
* caller declared its executors at turn setup (ChatRequest.clientCapabilities): no pickup
246+
* capability means no wait. With the capability, a turn no view is reading only waits for one
247+
* that is re-attaching. The claim arbitration is the same either way.
248+
*/
249+
async function workflowToolPickupGraceMs(options: OrchestratorOptions): Promise<number> {
250+
if (options.clientToolPickupExpected === false) return 0
251+
if (!options.hasClientViewer) return COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS
252+
const viewer = await options.hasClientViewer().catch(() => true)
253+
return viewer ? COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS : COPILOT_WORKFLOW_TOOL_NO_VIEWER_GRACE_MS
254+
}
255+
242256
/**
243257
* Upsert the durable `async_tool_calls` row before the authoritative tool-call
244258
* SSE frame is forwarded to the client, so `/api/copilot/confirm` and
@@ -1113,14 +1127,7 @@ async function dispatchToolExecution(
11131127
workflowId: resolveWorkflowToolTargetId(args, execContext.workflowId),
11141128
timeoutMs,
11151129
deadlineAt: toolCall.deadlineAt,
1116-
// The caller declared its executors at turn setup (ChatRequest.clientCapabilities):
1117-
// no pickup capability → zero grace, the race resolves straight to the server
1118-
// claim. Same claim arbitration either way — the grace only encodes how long a
1119-
// client might plausibly appear.
1120-
graceMs:
1121-
options.clientToolPickupExpected === false
1122-
? 0
1123-
: COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS,
1130+
graceMs: await workflowToolPickupGraceMs(options),
11241131
...(toolCall.waitTimeoutMs !== undefined
11251132
? { waitTimeoutMs: toolCall.waitTimeoutMs }
11261133
: {}),

‎apps/sim/lib/mothership/request/lifecycle/start.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { type CopilotLifecycleOutcome, startCopilotOtelRoot } from '@/lib/mother
4646
import {
4747
cleanupAbortMarker,
4848
clearFilePreviewSessions,
49+
hasStreamViewer,
4950
isExplicitStopReason,
5051
registerActiveStream,
5152
releasePendingChatStream,
@@ -427,6 +428,8 @@ export function createSSEStream(params: StreamingOrchestrationParams): ReadableS
427428

428429
const result = await runCopilotLifecycle(requestPayload, {
429430
...orchestrateOptions,
431+
hasClientViewer: async () =>
432+
!publisher.clientDisconnected || (await hasStreamViewer(streamId)),
430433
executionId,
431434
runId,
432435
trace: collector,

‎apps/sim/lib/mothership/request/session/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,5 @@ export {
8383
} from './run-replay'
8484
export { encodeSSEEnvelope, SSE_RESPONSE_HEADERS } from './sse'
8585
export type { StreamBatchEvent } from './types'
86+
export { hasStreamViewer, holdStreamViewer } from './viewer'
8687
export { StreamWriter, type StreamWriterOptions } from './writer'
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Chat stream reader presence against real Redis: a reader attached on one instance must be
3+
* visible to the instance dispatching that turn's workflow tools, and must stop counting once it
4+
* leaves, so a turn nobody reads no longer waits out the full pickup grace.
5+
*/
6+
import { afterAll, describe, expect, it, vi } from 'vitest'
7+
8+
await vi.hoisted(async () => {
9+
const { readTestRedisUrl } = await import('@sim/db/testing/test-infrastructure')
10+
process.env.REDIS_URL = readTestRedisUrl()
11+
})
12+
13+
import { sleep } from '@sim/utils/helpers'
14+
import { generateId } from '@sim/utils/id'
15+
import { closeRedisConnection, getRedisClient } from '@/lib/core/config/redis'
16+
import { hasStreamViewer, holdStreamViewer } from '@/lib/mothership/request/session/viewer'
17+
18+
describe('chat stream reader presence', () => {
19+
afterAll(async () => {
20+
await closeRedisConnection()
21+
})
22+
23+
it('sees a reader attached to the stream', async () => {
24+
const streamId = generateId()
25+
const release = holdStreamViewer(streamId)
26+
try {
27+
await expect.poll(() => hasStreamViewer(streamId)).toBe(true)
28+
} finally {
29+
release()
30+
}
31+
})
32+
33+
it('sees no reader on a stream nobody attached to', async () => {
34+
expect(await hasStreamViewer(generateId())).toBe(false)
35+
})
36+
37+
it('never re-marks a reader after it leaves', async () => {
38+
const streamId = generateId()
39+
const release = holdStreamViewer(streamId)
40+
await expect.poll(() => hasStreamViewer(streamId)).toBe(true)
41+
release()
42+
// Stands in for the TTL running out, so the test does not wait it out.
43+
await getRedisClient()?.del(`mothership_stream:${streamId}:viewer`)
44+
// Longer than one refresh: a reader still refreshing would have re-marked itself by now.
45+
await sleep(3_500)
46+
47+
expect(await hasStreamViewer(streamId)).toBe(false)
48+
})
49+
})
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { createLogger } from '@sim/logger'
2+
import { toError } from '@sim/utils/errors'
3+
import { getRedisClient } from '@/lib/core/config/redis'
4+
5+
/**
6+
* Which chat streams have a reconnected reader attached right now, on any instance.
7+
*
8+
* A chat view starts client-routed workflow tools from the stream it reads. The original send
9+
* knows in-process whether its own response is still attached; a view that re-attached through
10+
* the reconnect route (a reload, a chat switch back, another tab) may sit on another instance,
11+
* so it marks itself here for as long as it stays attached.
12+
*/
13+
14+
const logger = createLogger('SessionStreamViewer')
15+
16+
/** Long enough that one late refresh never makes an attached reader look gone. */
17+
const STREAM_VIEWER_TTL_MS = 10_000
18+
const STREAM_VIEWER_REFRESH_MS = 3_000
19+
20+
function getViewerKey(streamId: string) {
21+
return `mothership_stream:${streamId}:viewer`
22+
}
23+
24+
async function markStreamViewer(streamId: string): Promise<void> {
25+
const redis = getRedisClient()
26+
if (!redis) return
27+
await redis.set(getViewerKey(streamId), '1', 'PX', STREAM_VIEWER_TTL_MS)
28+
}
29+
30+
/**
31+
* Marks a reader attached to the stream until the returned release runs. The mark lapses on
32+
* its own a few seconds after release, so a crashed reader never holds it.
33+
*/
34+
export function holdStreamViewer(streamId: string): () => void {
35+
const refresh = () => {
36+
markStreamViewer(streamId).catch((error) => {
37+
logger.warn('Could not mark a chat stream reader attached', {
38+
streamId,
39+
error: toError(error).message,
40+
})
41+
})
42+
}
43+
refresh()
44+
const interval = setInterval(refresh, STREAM_VIEWER_REFRESH_MS)
45+
return () => clearInterval(interval)
46+
}
47+
48+
/**
49+
* Whether a reconnected reader is attached to the stream. Answers true whenever it cannot
50+
* tell (no Redis, a failed read), so an unknown never cuts a present view's pickup window.
51+
*/
52+
export async function hasStreamViewer(streamId: string): Promise<boolean> {
53+
const redis = getRedisClient()
54+
if (!redis) return true
55+
try {
56+
return (await redis.exists(getViewerKey(streamId))) > 0
57+
} catch (error) {
58+
logger.warn('Could not read whether a chat stream reader is attached', {
59+
streamId,
60+
error: toError(error).message,
61+
})
62+
return true
63+
}
64+
}

‎apps/sim/lib/mothership/request/types.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,13 @@ export interface OrchestratorOptions {
290290
* `interactive`, which is a trust classification, not executor routing.
291291
*/
292292
clientToolPickupExpected?: boolean
293+
/**
294+
* Whether a chat view is reading this turn's stream right now: the send's own response, or a
295+
* reader re-attached through the reconnect route. Answers true when it cannot tell. With no
296+
* view, a workflow tool waits only a short grace for one to attach before running server-side.
297+
* Absent on legs that cannot tell, which keep the full grace.
298+
*/
299+
hasClientViewer?: () => Promise<boolean>
293300
/**
294301
* The turn's desktop claims local reads (`read_local_file`, user-local VFS reads) through
295302
* authorize before reading, so they are persisted pending and fail fast when nothing picks them

0 commit comments

Comments
 (0)