Skip to content

Commit 2fbf76e

Browse files
committed
fix(mothership): extend the workflow pickup grace for a view that re-attaches during it
A reload drops the send's response, so a call dispatched right then got the 5s grace even though the view re-attaches about two seconds later. Presence is now read again when the short grace ends, and a view attached by then gets the rest of the full grace. A reader's refresh also drops lapsed entries, and the send's in-process attachment signal is covered by a test.
1 parent aa94b0e commit 2fbf76e

5 files changed

Lines changed: 116 additions & 17 deletions

File tree

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

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1366,7 +1366,10 @@ describe('sse-handlers tool lifecycle', () => {
13661366

13671367
describe('workflow tool pickup grace', () => {
13681368
/** Dispatches a workflow call whose browser wait only ends when the server takes it over. */
1369-
async function dispatchUnpickedWorkflowCall(toolCallId: string, hasClientViewer: boolean) {
1369+
async function dispatchUnpickedWorkflowCall(
1370+
toolCallId: string,
1371+
hasClientViewer: () => Promise<boolean>
1372+
) {
13701373
waitForWorkflowToolCompletion.mockImplementationOnce((params: unknown) => {
13711374
const abortSignal = toRecord(params).abortSignal
13721375
return new Promise((resolve) => {
@@ -1391,14 +1394,14 @@ describe('sse-handlers tool lifecycle', () => {
13911394
} satisfies StreamEvent,
13921395
context,
13931396
execContext,
1394-
{ interactive: true, hasClientViewer: async () => hasClientViewer }
1397+
{ interactive: true, hasClientViewer }
13951398
)
13961399
}
13971400

13981401
it('runs a call no chat view is reading on the server after the short grace', async () => {
13991402
vi.useFakeTimers()
14001403
try {
1401-
await dispatchUnpickedWorkflowCall('tool-no-viewer', false)
1404+
await dispatchUnpickedWorkflowCall('tool-no-viewer', async () => false)
14021405
await vi.advanceTimersByTimeAsync(5_000)
14031406
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
14041407
'tool-no-viewer',
@@ -1413,10 +1416,37 @@ describe('sse-handlers tool lifecycle', () => {
14131416
}
14141417
})
14151418

1419+
it('gives a view that re-attached during the short grace the rest of the full grace', async () => {
1420+
vi.useFakeTimers()
1421+
try {
1422+
let attached = false
1423+
await dispatchUnpickedWorkflowCall('tool-reattached', async () => attached)
1424+
// A reload: the send's response dropped, and the view re-attaches two seconds later.
1425+
await vi.advanceTimersByTimeAsync(2_000)
1426+
attached = true
1427+
await vi.advanceTimersByTimeAsync(27_000)
1428+
expect(claimWorkflowToolExecution).not.toHaveBeenCalledWith(
1429+
'tool-reattached',
1430+
expect.any(String),
1431+
'sim'
1432+
)
1433+
1434+
await vi.advanceTimersByTimeAsync(1_000)
1435+
await Promise.allSettled(context.pendingToolPromises.values())
1436+
expect(claimWorkflowToolExecution).toHaveBeenCalledWith(
1437+
'tool-reattached',
1438+
expect.any(String),
1439+
'sim'
1440+
)
1441+
} finally {
1442+
vi.useRealTimers()
1443+
}
1444+
})
1445+
14161446
it('keeps waiting the full grace for a call a chat view is reading', async () => {
14171447
vi.useFakeTimers()
14181448
try {
1419-
await dispatchUnpickedWorkflowCall('tool-viewer', true)
1449+
await dispatchUnpickedWorkflowCall('tool-viewer', async () => true)
14201450
await vi.advanceTimersByTimeAsync(29_000)
14211451
expect(claimWorkflowToolExecution).not.toHaveBeenCalledWith(
14221452
'tool-viewer',

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

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -243,14 +243,25 @@ function desktopClaimsLocalReads(
243243
/**
244244
* How long a workflow tool waits for a chat view to pick it up before the server runs it. The
245245
* 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.
246+
* capability means no wait. With the capability, a turn no view is reading waits only for one
247+
* that is re-attaching, and a view that attached by the end of that short wait (a reload) gets
248+
* the rest of the full grace. The claim arbitration is the same either way.
248249
*/
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
250+
async function workflowToolPickupGrace(
251+
options: OrchestratorOptions
252+
): Promise<{ graceMs: number; extendGrace?: () => Promise<number> }> {
253+
if (options.clientToolPickupExpected === false) return { graceMs: 0 }
254+
const hasClientViewer = options.hasClientViewer
255+
if (!hasClientViewer) return { graceMs: COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS }
256+
const viewing = () => hasClientViewer().catch(() => true)
257+
if (await viewing()) return { graceMs: COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS }
258+
return {
259+
graceMs: COPILOT_WORKFLOW_TOOL_NO_VIEWER_GRACE_MS,
260+
extendGrace: async () =>
261+
(await viewing())
262+
? COPILOT_WORKFLOW_TOOL_CLIENT_GRACE_MS - COPILOT_WORKFLOW_TOOL_NO_VIEWER_GRACE_MS
263+
: 0,
264+
}
254265
}
255266

256267
/**
@@ -1127,7 +1138,7 @@ async function dispatchToolExecution(
11271138
workflowId: resolveWorkflowToolTargetId(args, execContext.workflowId),
11281139
timeoutMs,
11291140
deadlineAt: toolCall.deadlineAt,
1130-
graceMs: await workflowToolPickupGraceMs(options),
1141+
...(await workflowToolPickupGrace(options)),
11311142
...(toolCall.waitTimeoutMs !== undefined
11321143
? { waitTimeoutMs: toolCall.waitTimeoutMs }
11331144
: {}),

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { propagation, trace } from '@opentelemetry/api'
22
import { W3CTraceContextPropagator } from '@opentelemetry/core'
33
import { TracerProvider } from '@opentelemetry/sdk-trace'
44
import { dbChainMockFns, resetDbChainMock, resetEnvFlagsMock, setEnvFlags } from '@sim/testing'
5+
import { createDeferred } from '@sim/testing/helpers/deferred'
56
import {
67
billingAttributionMock,
78
billingAttributionMockFns,
@@ -42,6 +43,7 @@ const {
4243
releasePendingChatStream,
4344
unregisterActiveStream,
4445
buildChatTitleContext,
46+
hasStreamViewer,
4547
} = vi.hoisted(() => ({
4648
runCopilotLifecycle: vi.fn(),
4749
resetBuffer: vi.fn(),
@@ -56,6 +58,7 @@ const {
5658
releasePendingChatStream: vi.fn(),
5759
unregisterActiveStream: vi.fn(),
5860
buildChatTitleContext: vi.fn().mockResolvedValue(undefined),
61+
hasStreamViewer: vi.fn(),
5962
}))
6063

6164
const BILLING_ATTRIBUTION = {
@@ -108,6 +111,7 @@ vi.mock('@/lib/mothership/request/session', () => ({
108111
releasePendingChatStream,
109112
registerActiveStream,
110113
unregisterActiveStream,
114+
hasStreamViewer,
111115
startAbortPoller: vi.fn().mockReturnValue(setInterval(() => {}, 999999)),
112116
isExplicitStopReason: (reason: unknown) => reason === 'user_stop:abortActiveStream',
113117
SSE_RESPONSE_HEADERS: {},
@@ -405,6 +409,42 @@ describe('createSSEStream terminal error handling', () => {
405409
}
406410
)
407411

412+
it('counts the send as viewed while its response is attached, and asks for a reader once it is not', async () => {
413+
const lifecycleDone = createDeferred<void>()
414+
let hasClientViewer: (() => Promise<boolean>) | undefined
415+
runCopilotLifecycle.mockImplementationOnce(
416+
async (_payload: unknown, options: { hasClientViewer?: () => Promise<boolean> }) => {
417+
hasClientViewer = options.hasClientViewer
418+
await lifecycleDone.promise
419+
return { success: true, content: '', contentBlocks: [], toolCalls: [] }
420+
}
421+
)
422+
hasStreamViewer.mockResolvedValue(false)
423+
const stream = createSSEStream({
424+
requestPayload: { message: 'hello' },
425+
userId: 'user-1',
426+
streamId: 'stream-viewer',
427+
executionId: 'exec-viewer',
428+
runId: 'run-viewer',
429+
currentChat: null,
430+
message: 'hello',
431+
titleModel: 'gpt-5.4',
432+
requestId: 'req-viewer',
433+
orchestrateOptions: { userId: 'user-1' },
434+
})
435+
await vi.waitFor(() => expect(hasClientViewer).toBeDefined())
436+
437+
expect(await hasClientViewer?.()).toBe(true)
438+
439+
await stream.cancel()
440+
expect(await hasClientViewer?.()).toBe(false)
441+
hasStreamViewer.mockResolvedValueOnce(true)
442+
expect(await hasClientViewer?.()).toBe(true)
443+
expect(hasStreamViewer).toHaveBeenCalledWith('stream-viewer')
444+
445+
lifecycleDone.resolve()
446+
})
447+
408448
it('starts the agent while title metadata is pending and forwards recovered inventory', async () => {
409449
let resolveContext!: (value: string) => void
410450
buildChatTitleContext.mockImplementationOnce(

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,12 @@ async function markStreamViewer(streamId: string, attachmentId: string): Promise
2727
const redis = getRedisClient()
2828
if (!redis) return
2929
const key = getViewersKey(streamId)
30+
const now = Date.now()
31+
// Drops readers that died without leaving, which a live reader's refresh keeps the key past.
3032
await redis
3133
.multi()
32-
.zadd(key, Date.now() + STREAM_VIEWER_TTL_MS, attachmentId)
34+
.zremrangebyscore(key, '-inf', now)
35+
.zadd(key, now + STREAM_VIEWER_TTL_MS, attachmentId)
3336
.pexpire(key, STREAM_VIEWER_TTL_MS)
3437
.exec()
3538
}

‎apps/sim/lib/mothership/request/tools/workflow-client-fallback.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ interface RaceWorkflowToolClientPickupParams {
5151
/** When the call's deadline passes: past it the server does not take the call over. */
5252
deadlineAt?: number
5353
graceMs: number
54+
/**
55+
* Asked once when the grace ends with no result: how much longer a view that attached during
56+
* the grace should get (0 for none). Bounded by `timeoutMs` like the grace itself.
57+
*/
58+
extendGrace?: () => Promise<number>
5459
/**
5560
* How long to wait for a browser's run before settling the call still running (the frame's
5661
* `waitTimeoutMs`); the browser's run goes on. Undefined waits until it settles.
@@ -191,10 +196,20 @@ export async function raceWorkflowToolClientPickup(
191196
// would outlive the wait it is supposed to bound.
192197
const effectiveGraceMs = Math.min(graceMs, timeoutMs)
193198

194-
const first = await Promise.race([
195-
clientWait.then((completion) => ({ kind: 'client' as const, completion })),
196-
sleep(effectiveGraceMs).then(() => ({ kind: 'grace' as const })),
197-
])
199+
const raceGrace = (ms: number) =>
200+
Promise.race([
201+
clientWait.then((completion) => ({ kind: 'client' as const, completion })),
202+
sleep(ms).then(() => ({ kind: 'grace' as const })),
203+
])
204+
205+
let first = await raceGrace(effectiveGraceMs)
206+
if (first.kind === 'grace' && params.extendGrace) {
207+
const extraMs = Math.min(
208+
await params.extendGrace().catch(() => 0),
209+
timeoutMs - effectiveGraceMs
210+
)
211+
if (extraMs > 0) first = await raceGrace(extraMs)
212+
}
198213

199214
// A non-null client result inside the grace window is the normal path.
200215
// A null one means the wait itself already expired (timeoutMs <= graceMs), so

0 commit comments

Comments
 (0)