Skip to content

Commit 234b10d

Browse files
committed
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 7c5ef5f commit 234b10d

5 files changed

Lines changed: 74 additions & 39 deletions

File tree

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

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

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ async function handleResumeRequestBody({
399399
}
400400
request.signal.addEventListener('abort', abortListener, { once: true })
401401
// An attached reader is a chat view that starts this turn's workflow tools.
402-
const releaseViewer = holdStreamViewer(streamId)
402+
const releaseViewer = await holdStreamViewer(streamId)
403403

404404
/** Delivers the ring's events after the cursor, or returns null if it trimmed the next one. */
405405
const flushEvents = async (): Promise<number | null> => {

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

Lines changed: 9 additions & 4 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'
@@ -1366,10 +1367,14 @@ describe('sse-handlers tool lifecycle', () => {
13661367
describe('workflow tool pickup grace', () => {
13671368
/** Dispatches a workflow call whose browser wait only ends when the server takes it over. */
13681369
async function dispatchUnpickedWorkflowCall(toolCallId: string, hasClientViewer: boolean) {
1369-
waitForWorkflowToolCompletion.mockImplementationOnce(
1370-
({ abortSignal }: { abortSignal?: AbortSignal }) =>
1371-
new Promise((resolve) => abortSignal?.addEventListener('abort', () => resolve(null)))
1372-
)
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+
})
13731378
claimWorkflowToolExecution.mockResolvedValueOnce({ toolCallId })
13741379
executeTool.mockResolvedValueOnce({ success: true, output: {} })
13751380
await sseHandlers.tool(

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

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,32 @@
11
/**
22
* 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.
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.
55
*/
66
import { afterAll, describe, expect, it, vi } from 'vitest'
77

8-
await vi.hoisted(async () => {
8+
const { redisUrl } = await vi.hoisted(async () => {
99
const { readTestRedisUrl } = await import('@sim/db/testing/test-infrastructure')
10-
process.env.REDIS_URL = readTestRedisUrl()
10+
const url = readTestRedisUrl()
11+
if (url) process.env.REDIS_URL = url
12+
return { redisUrl: url }
1113
})
1214

1315
import { sleep } from '@sim/utils/helpers'
1416
import { generateId } from '@sim/utils/id'
15-
import { closeRedisConnection, getRedisClient } from '@/lib/core/config/redis'
17+
import { closeRedisConnection } from '@/lib/core/config/redis'
1618
import { hasStreamViewer, holdStreamViewer } from '@/lib/mothership/request/session/viewer'
1719

18-
describe('chat stream reader presence', () => {
20+
describe.runIf(Boolean(redisUrl))('chat stream reader presence', () => {
1921
afterAll(async () => {
2022
await closeRedisConnection()
2123
})
2224

23-
it('sees a reader attached to the stream', async () => {
25+
it('counts a reader as attached once its hold resolves', async () => {
2426
const streamId = generateId()
25-
const release = holdStreamViewer(streamId)
27+
const release = await holdStreamViewer(streamId)
2628
try {
27-
await expect.poll(() => hasStreamViewer(streamId)).toBe(true)
29+
expect(await hasStreamViewer(streamId)).toBe(true)
2830
} finally {
2931
release()
3032
}
@@ -34,13 +36,23 @@ describe('chat stream reader presence', () => {
3436
expect(await hasStreamViewer(generateId())).toBe(false)
3537
})
3638

37-
it('never re-marks a reader after it leaves', async () => {
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 () => {
3852
const streamId = generateId()
39-
const release = holdStreamViewer(streamId)
40-
await expect.poll(() => hasStreamViewer(streamId)).toBe(true)
53+
const release = await holdStreamViewer(streamId)
4154
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`)
55+
await expect.poll(() => hasStreamViewer(streamId)).toBe(false)
4456
// Longer than one refresh: a reader still refreshing would have re-marked itself by now.
4557
await sleep(3_500)
4658

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

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createLogger } from '@sim/logger'
22
import { toError } from '@sim/utils/errors'
3+
import { generateId } from '@sim/utils/id'
34
import { getRedisClient } from '@/lib/core/config/redis'
45

56
/**
@@ -8,7 +9,8 @@ import { getRedisClient } from '@/lib/core/config/redis'
89
* A chat view starts client-routed workflow tools from the stream it reads. The original send
910
* knows in-process whether its own response is still attached; a view that re-attached through
1011
* 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+
* 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.
1214
*/
1315

1416
const logger = createLogger('SessionStreamViewer')
@@ -17,32 +19,48 @@ const logger = createLogger('SessionStreamViewer')
1719
const STREAM_VIEWER_TTL_MS = 10_000
1820
const STREAM_VIEWER_REFRESH_MS = 3_000
1921

20-
function getViewerKey(streamId: string) {
21-
return `mothership_stream:${streamId}:viewer`
22+
function getViewersKey(streamId: string) {
23+
return `mothership_stream:${streamId}:viewers`
2224
}
2325

24-
async function markStreamViewer(streamId: string): Promise<void> {
26+
async function markStreamViewer(streamId: string, attachmentId: string): Promise<void> {
2527
const redis = getRedisClient()
2628
if (!redis) return
27-
await redis.set(getViewerKey(streamId), '1', 'PX', STREAM_VIEWER_TTL_MS)
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+
})
2848
}
2949

3050
/**
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.
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.
3353
*/
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()
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()
4459
const interval = setInterval(refresh, STREAM_VIEWER_REFRESH_MS)
45-
return () => clearInterval(interval)
60+
return () => {
61+
clearInterval(interval)
62+
unmarkStreamViewer(streamId, attachmentId).catch((error) => warnMarkFailed(streamId, error))
63+
}
4664
}
4765

4866
/**
@@ -53,7 +71,7 @@ export async function hasStreamViewer(streamId: string): Promise<boolean> {
5371
const redis = getRedisClient()
5472
if (!redis) return true
5573
try {
56-
return (await redis.exists(getViewerKey(streamId))) > 0
74+
return (await redis.zcount(getViewersKey(streamId), Date.now(), '+inf')) > 0
5775
} catch (error) {
5876
logger.warn('Could not read whether a chat stream reader is attached', {
5977
streamId,

0 commit comments

Comments
 (0)