Skip to content
Merged
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
36 changes: 36 additions & 0 deletions apps/web/src/routes/api/chat/__tests__/stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,42 @@ describe('GET /api/chat/stream - assistant activity snapshot replay', () => {
})
})

describe('GET /api/chat/stream - teardown keeps the workspace scope', () => {
it('clears presence inside the request workspace scope when the client disconnects', async () => {
const { createWorkspaceScope, getWorkspaceScope, runWithWorkspaceScope } =
await import('@/lib/server/workspaces/workspace-context')
const scope = createWorkspaceScope({
workspace: { workspaceKey: 'inst_stream' },
db: {},
sql: {},
origin: 'request',
secrets: { secretKey: 'd'.repeat(64), storage: null, storageProblem: 'not read here' },
} as never)
tokenPrincipal('member')
let scopeSeenByClear: string | null | undefined
mockClearPresence.mockImplementation(async () => {
scopeSeenByClear = getWorkspaceScope()?.workspace.workspaceKey ?? null
return false
})

// Opened inside a workspace scope, exactly as the middleware would run it…
const controller = new AbortController()
const request = new Request('http://test/api/chat/stream?scope=inbox', {
signal: controller.signal,
})
const res = await runWithWorkspaceScope(scope, () => GET({ request }))
expect(res.status).toBe(200)
await vi.waitFor(() => expect(mockMarkPresent).toHaveBeenCalled())

// …and aborted from outside it, which is where the runtime fires the
// signal. Teardown must not see an empty scope.
expect(getWorkspaceScope()).toBeNull()
controller.abort()
await vi.waitFor(() => expect(mockClearPresence).toHaveBeenCalled())
expect(scopeSeenByClear).toBe('inst_stream')
})
})

describe('GET /api/chat/stream - abandoned heartbeat timeout', () => {
it('stops polling presence and unsubscribes when pings go unconsumed', async () => {
vi.useFakeTimers()
Expand Down
11 changes: 10 additions & 1 deletion apps/web/src/routes/api/chat/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { createSseStream, SSE_RESPONSE_HEADERS } from '@/lib/server/utils/sse'
import { streamLimiter } from '@/lib/server/realtime/stream-connection-limit'
import { startStreamHeartbeat } from '@/lib/server/realtime/stream-heartbeat'
import { getClientIp } from '@/lib/server/domains/api/rate-limit'
import { getWorkspaceScope, runWithWorkspaceScope } from '@/lib/server/workspaces/workspace-context'
import { logger } from '@/lib/server/logger'

const log = logger.child({ component: 'chat-stream' })
Expand Down Expand Up @@ -224,7 +225,13 @@ export const Route = createFileRoute('/api/chat/stream')({
let heartbeat: { stop: () => void } | null = null
let unsubscribe: (() => Promise<void>) | null = null

cleanup = async () => {
// The abort listener and the stream's cancel hook are invoked by the
// runtime, outside the request's AsyncLocalStorage context, so under
// pooled tenancy `clearPresence` (and the requeue behind it) would run
// with no workspace scope and throw. Capture the scope now and re-enter
// it for teardown — the same pattern the auth stash sweeps use.
const workspaceScope = getWorkspaceScope()
const teardown = async () => {
if (cleanedUp) return
cleanedUp = true
heartbeat?.stop()
Expand All @@ -251,6 +258,8 @@ export const Route = createFileRoute('/api/chat/stream')({
}
slot.release()
}
cleanup = () =>
workspaceScope ? runWithWorkspaceScope(workspaceScope, teardown) : teardown()

const run = async () => {
try {
Expand Down
Loading