Skip to content

Commit aa94b0e

Browse files
authored
fix(mothership): skip the 30s workflow pickup wait when no chat view is reading (#10148)
* 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. * fix(mothership): clear a reader's mark when it leaves and count it before its first event Each reconnect attachment now holds its own entry in a per-stream sorted set, removed on release, so leaving stops counting at once instead of lingering until the TTL. The route awaits the first mark before reading, and the Redis suite skips when no test Redis is configured locally.
1 parent 00d21c3 commit aa94b0e

10 files changed

Lines changed: 255 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: async () => () => {},
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 = await 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: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
mothershipClientToolWaiterMockFns,
1010
} from '@sim/testing/mocks/mothership-client-tool-waiter.mock'
1111
import { sleep } from '@sim/utils/helpers'
12+
import { toRecord } from '@sim/utils/object'
1213
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
1314
import { AsyncToolCallOwnershipError } from '@/lib/mothership/async-runs/errors'
1415
import { restoreStreamingContext } from '@/lib/mothership/request/context/restore'
@@ -1363,6 +1364,79 @@ describe('sse-handlers tool lifecycle', () => {
13631364
expect(workflowResults[0].payload.executor).toBe(MothershipStreamV1ToolExecutor.sim)
13641365
})
13651366

1367+
describe('workflow tool pickup grace', () => {
1368+
/** Dispatches a workflow call whose browser wait only ends when the server takes it over. */
1369+
async function dispatchUnpickedWorkflowCall(toolCallId: string, hasClientViewer: boolean) {
1370+
waitForWorkflowToolCompletion.mockImplementationOnce((params: unknown) => {
1371+
const abortSignal = toRecord(params).abortSignal
1372+
return new Promise((resolve) => {
1373+
if (abortSignal instanceof AbortSignal) {
1374+
abortSignal.addEventListener('abort', () => resolve(null))
1375+
}
1376+
})
1377+
})
1378+
claimWorkflowToolExecution.mockResolvedValueOnce({ toolCallId })
1379+
executeTool.mockResolvedValueOnce({ success: true, output: {} })
1380+
await sseHandlers.tool(
1381+
{
1382+
type: MothershipStreamV1EventType.tool,
1383+
payload: {
1384+
toolCallId,
1385+
toolName: 'run_workflow',
1386+
arguments: { workflowId: 'workflow-1' },
1387+
executor: MothershipStreamV1ToolExecutor.client,
1388+
mode: MothershipStreamV1ToolMode.async,
1389+
phase: MothershipStreamV1ToolPhase.call,
1390+
},
1391+
} satisfies StreamEvent,
1392+
context,
1393+
execContext,
1394+
{ interactive: true, hasClientViewer: async () => hasClientViewer }
1395+
)
1396+
}
1397+
1398+
it('runs a call no chat view is reading on the server after the short grace', async () => {
1399+
vi.useFakeTimers()
1400+
try {
1401+
await dispatchUnpickedWorkflowCall('tool-no-viewer', false)
1402+
await vi.advanceTimersByTimeAsync(5_000)
1403+
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
1404+
'tool-no-viewer',
1405+
expect.any(String),
1406+
'sim'
1407+
)
1408+
1409+
await Promise.allSettled(context.pendingToolPromises.values())
1410+
expect(executeTool.mock.calls.at(-1)?.[0]).toBe('run_workflow')
1411+
} finally {
1412+
vi.useRealTimers()
1413+
}
1414+
})
1415+
1416+
it('keeps waiting the full grace for a call a chat view is reading', async () => {
1417+
vi.useFakeTimers()
1418+
try {
1419+
await dispatchUnpickedWorkflowCall('tool-viewer', true)
1420+
await vi.advanceTimersByTimeAsync(29_000)
1421+
expect(claimWorkflowToolExecution).not.toHaveBeenCalledWith(
1422+
'tool-viewer',
1423+
expect.any(String),
1424+
'sim'
1425+
)
1426+
1427+
await vi.advanceTimersByTimeAsync(1_000)
1428+
await Promise.allSettled(context.pendingToolPromises.values())
1429+
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
1430+
'tool-viewer',
1431+
expect.any(String),
1432+
'sim'
1433+
)
1434+
} finally {
1435+
vi.useRealTimers()
1436+
}
1437+
})
1438+
})
1439+
13661440
it('claims and runs the same workflow when the call omits an explicit workflowId', async () => {
13671441
// The waiter resolves the target via resolveWorkflowToolTargetId(args, ctx)
13681442
// 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: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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 the
4+
* moment it 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+
const { redisUrl } = await vi.hoisted(async () => {
9+
const { readTestRedisUrl } = await import('@sim/db/testing/test-infrastructure')
10+
const url = readTestRedisUrl()
11+
if (url) process.env.REDIS_URL = url
12+
return { redisUrl: url }
13+
})
14+
15+
import { sleep } from '@sim/utils/helpers'
16+
import { generateId } from '@sim/utils/id'
17+
import { closeRedisConnection } from '@/lib/core/config/redis'
18+
import { hasStreamViewer, holdStreamViewer } from '@/lib/mothership/request/session/viewer'
19+
20+
describe.runIf(Boolean(redisUrl))('chat stream reader presence', () => {
21+
afterAll(async () => {
22+
await closeRedisConnection()
23+
})
24+
25+
it('counts a reader as attached once its hold resolves', async () => {
26+
const streamId = generateId()
27+
const release = await holdStreamViewer(streamId)
28+
try {
29+
expect(await hasStreamViewer(streamId)).toBe(true)
30+
} finally {
31+
release()
32+
}
33+
})
34+
35+
it('sees no reader on a stream nobody attached to', async () => {
36+
expect(await hasStreamViewer(generateId())).toBe(false)
37+
})
38+
39+
it('keeps counting a stream while another reader stays attached', async () => {
40+
const streamId = generateId()
41+
const leaving = await holdStreamViewer(streamId)
42+
const staying = await holdStreamViewer(streamId)
43+
try {
44+
leaving()
45+
await expect.poll(() => hasStreamViewer(streamId)).toBe(true)
46+
} finally {
47+
staying()
48+
}
49+
})
50+
51+
it('stops counting a reader as soon as it leaves, and never re-marks it', async () => {
52+
const streamId = generateId()
53+
const release = await holdStreamViewer(streamId)
54+
release()
55+
await expect.poll(() => hasStreamViewer(streamId)).toBe(false)
56+
// Longer than one refresh: a reader still refreshing would have re-marked itself by now.
57+
await sleep(3_500)
58+
59+
expect(await hasStreamViewer(streamId)).toBe(false)
60+
})
61+
})
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { createLogger } from '@sim/logger'
2+
import { toError } from '@sim/utils/errors'
3+
import { generateId } from '@sim/utils/id'
4+
import { getRedisClient } from '@/lib/core/config/redis'
5+
6+
/**
7+
* Which chat streams have a reconnected reader attached right now, on any instance.
8+
*
9+
* A chat view starts client-routed workflow tools from the stream it reads. The original send
10+
* knows in-process whether its own response is still attached; a view that re-attached through
11+
* the reconnect route (a reload, a chat switch back, another tab) may sit on another instance,
12+
* so each attachment holds its own entry here, scored by when it lapses, for as long as it
13+
* stays attached. Leaving removes the entry at once; a reader that dies without leaving lapses.
14+
*/
15+
16+
const logger = createLogger('SessionStreamViewer')
17+
18+
/** Long enough that one late refresh never makes an attached reader look gone. */
19+
const STREAM_VIEWER_TTL_MS = 10_000
20+
const STREAM_VIEWER_REFRESH_MS = 3_000
21+
22+
function getViewersKey(streamId: string) {
23+
return `mothership_stream:${streamId}:viewers`
24+
}
25+
26+
async function markStreamViewer(streamId: string, attachmentId: string): Promise<void> {
27+
const redis = getRedisClient()
28+
if (!redis) return
29+
const key = getViewersKey(streamId)
30+
await redis
31+
.multi()
32+
.zadd(key, Date.now() + STREAM_VIEWER_TTL_MS, attachmentId)
33+
.pexpire(key, STREAM_VIEWER_TTL_MS)
34+
.exec()
35+
}
36+
37+
async function unmarkStreamViewer(streamId: string, attachmentId: string): Promise<void> {
38+
const redis = getRedisClient()
39+
if (!redis) return
40+
await redis.zrem(getViewersKey(streamId), attachmentId)
41+
}
42+
43+
function warnMarkFailed(streamId: string, error: unknown) {
44+
logger.warn('Could not record a chat stream reader', {
45+
streamId,
46+
error: toError(error).message,
47+
})
48+
}
49+
50+
/**
51+
* Records a reader attached to the stream until the returned release runs. Resolves once the
52+
* first mark is written, so the reader counts before it reads its first event.
53+
*/
54+
export async function holdStreamViewer(streamId: string): Promise<() => void> {
55+
const attachmentId = generateId()
56+
const refresh = () =>
57+
markStreamViewer(streamId, attachmentId).catch((error) => warnMarkFailed(streamId, error))
58+
await refresh()
59+
const interval = setInterval(refresh, STREAM_VIEWER_REFRESH_MS)
60+
return () => {
61+
clearInterval(interval)
62+
unmarkStreamViewer(streamId, attachmentId).catch((error) => warnMarkFailed(streamId, error))
63+
}
64+
}
65+
66+
/**
67+
* Whether a reconnected reader is attached to the stream. Answers true whenever it cannot
68+
* tell (no Redis, a failed read), so an unknown never cuts a present view's pickup window.
69+
*/
70+
export async function hasStreamViewer(streamId: string): Promise<boolean> {
71+
const redis = getRedisClient()
72+
if (!redis) return true
73+
try {
74+
return (await redis.zcount(getViewersKey(streamId), Date.now(), '+inf')) > 0
75+
} catch (error) {
76+
logger.warn('Could not read whether a chat stream reader is attached', {
77+
streamId,
78+
error: toError(error).message,
79+
})
80+
return true
81+
}
82+
}

‎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)