feat: session/projection push frame; tail block reads the watermark snapshot

This commit is contained in:
imccyu
2026-07-27 21:34:14 +08:00
parent 708d3132cf
commit 6f47df0913
7 changed files with 138 additions and 75 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ Wire messages form a four-quadrant discriminated union — who initiates × requ
The layering/protocol decisions are recorded in the [GUI layering and RPC protocol RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md); the browser-side consumption architecture in the [web client architecture RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md). The layering/protocol decisions are recorded in the [GUI layering and RPC protocol RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md); the browser-side consumption architecture in the [web client architecture RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md).
`session.history`'s tail page (`beforeSeq` absent) additionally carries an optional `projections` block — one synchronous cut over every provider registered on `ctx.sessionProjections` (`@deepseek-ai/dsh-session-projection`), with `asOfSeq` equal to the window tail seq. The handler holds zero domain knowledge (each value passes its provider's own schema; the wire schema keeps `values` wide); loadOlder pages never carry the block, and a composition without the registry serves histories without it. `session.history`'s tail page (`beforeSeq` absent) additionally carries an optional `projections` block — the watermark snapshot of every unit registered on `ctx.sessionProjections` (`@deepseek-ai/dsh-session-projection`), with `asOfSeq` = the last event seq the values reflect (`-1` on an empty log). The gateway also subscribes to the registry's change feed and mints a `session/projection` mux frame per changed unit (`{sessionId, key, value, seq}` — live push state, never logged; clients hold one generic per-session value store under higher-seq-wins). The carrier holds zero domain knowledge (each value passed its unit's own schema inside the registry; the wire schemas keep `values`/`value` wide); loadOlder pages never carry the block, and a composition without the registry serves histories without either surface.
The mux stream projects the latest log-backed title as a validated `session/title` control frame after each attached-session subscription baseline and immediately after the corresponding live raw title event. This projection does not add titles to `session.list`; cold sessions remain metadata-only there until opening or resuming attaches their logs. The mux stream projects the latest log-backed title as a validated `session/title` control frame after each attached-session subscription baseline and immediately after the corresponding live raw title event. This projection does not add titles to `session.list`; cold sessions remain metadata-only there until opening or resuming attaches their logs.
+18 -15
View File
@@ -299,25 +299,18 @@ function backscanTodos(events: readonly SessionEvent[]): TodoItem[] | undefined
} }
/** /**
* Compute the projection baseline for one history tail page: read the * The projection baseline for one history tail page: the registry's
* session's next-event seq, then walk every registered provider — one fully * watermark-cache snapshot — one fully synchronous read (no await between the
* synchronous pass (no await anywhere), so all values and `asOfSeq` form a * page slice and this), so all values and `asOfSeq` form a single consistent
* single consistent cut and `asOfSeq` equals the window tail seq. Each value * cut and `asOfSeq` equals the window tail event seq. The carrier holds zero
* passes through its provider's own schema before leaving the host (the * domain knowledge (each value passed its unit's own schema inside the
* carrier holds zero domain knowledge; a provider returning an invalid value — * registry). An absent registry means the deployment has no projection seam:
* including an accidental Promise from a non-synchronous `get` — fails loud * the whole block is absent and clients treat every key as capability-absent.
* here). An absent registry means the deployment has no projection seam: the
* whole block is absent and clients treat every key as capability-absent.
*/ */
function projectionsFor(ctx: Context, agent: Agent): SessionProjectionsBlock | undefined { function projectionsFor(ctx: Context, agent: Agent): SessionProjectionsBlock | undefined {
const registry = ctx.get('sessionProjections') const registry = ctx.get('sessionProjections')
if (registry === undefined) return undefined if (registry === undefined) return undefined
const asOfSeq = agent.session.seq return registry.snapshot(agent.session)
const values: Record<string, unknown> = {}
for (const provider of registry.entries()) {
values[provider.key] = provider.schema.parse(provider.get(agent))
}
return { asOfSeq, values: values as SessionProjectionsBlock['values'] }
} }
/** /**
@@ -400,6 +393,16 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
for (const queue of muxQueues) queue.push(envelope) for (const queue of muxQueues) queue.push(envelope)
} }
// Projection change feed → session/projection push frames. The carrier
// mints the wire frame (the seam package holds no wire vocabulary); the
// child activates only when a projection registry is composed, and the
// subscription unwinds with this gateway's fiber.
ctx.inject(['sessionProjections'], (projectionCtx) => {
projectionCtx.sessionProjections.onChanged((session, key, value, seq) => {
broadcast({ type: 'session/projection', sessionId: session.id, key, value, seq })
})
})
/** /**
* Per-session inbox mirror serving the mux-open queue snapshot (the same * Per-session inbox mirror serving the mux-open queue snapshot (the same
* refresh-recovery baseline as pending questions). Keyed by the stable * refresh-recovery baseline as pending questions). Keyed by the stable
@@ -37,6 +37,9 @@ export const muxFrameSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('question/resolved'), sessionId: sessionIdSchema, questionRpcId: rpcIdSchema, outcome: z.union([z.literal('answered'), z.literal('cancelled')]) }), z.object({ type: z.literal('question/resolved'), sessionId: sessionIdSchema, questionRpcId: rpcIdSchema, outcome: z.union([z.literal('answered'), z.literal('cancelled')]) }),
// content/source reuse the wide passthroughs (both are merge-extensible in core). // content/source reuse the wide passthroughs (both are merge-extensible in core).
z.object({ type: z.literal('session/queued'), sessionId: sessionIdSchema, content: z.array(contentBlockSchema), source: z.looseObject({ kind: z.string() }), steering: z.boolean() }), z.object({ type: z.literal('session/queued'), sessionId: sessionIdSchema, content: z.array(contentBlockSchema), source: z.looseObject({ kind: z.string() }), steering: z.boolean() }),
// value stays wide: it already passed its unit's own schema on the host,
// and deep-validating here would import every domain's schema into the carrier.
z.object({ type: z.literal('session/projection'), sessionId: sessionIdSchema, key: z.string().min(1), value: z.unknown(), seq: z.number().int().nonnegative() }),
z.object({ type: z.literal('stream/error'), error: rpcErrorSchema }), z.object({ type: z.literal('stream/error'), error: rpcErrorSchema }),
]) as unknown as z.ZodType<MuxFrame> ]) as unknown as z.ZodType<MuxFrame>
+9
View File
@@ -75,6 +75,15 @@ export type MuxFrame =
* reconciliation key). * reconciliation key).
*/ */
| { type: 'session/queued'; sessionId: SessionId; content: ContentBlock[]; source: MessageSource; steering: boolean } | { type: 'session/queued'; sessionId: SessionId; content: ContentBlock[]; source: MessageSource; steering: boolean }
/**
* One projection unit's finished value changed (session-projection RFC).
* Live push state, never logged — replay recomputes on the host (the
* tool-view posture). `value` is the unit's schema-validated view output;
* `seq` is the unit's watermark at emission. Clients keep one generic
* per-session value store under higher-seq-wins, seeded by the history
* tail page's projections block.
*/
| { type: 'session/projection'; sessionId: SessionId; key: string; value: unknown; seq: number }
| { type: 'stream/error'; error: RpcError } | { type: 'stream/error'; error: RpcError }
/** /**
@@ -105,7 +105,8 @@ export const todoItemSchema = z.object({
* deep-validating here would import every domain's schema into the carrier. * deep-validating here would import every domain's schema into the carrier.
*/ */
export const sessionProjectionsBlockSchema = z.object({ export const sessionProjectionsBlockSchema = z.object({
asOfSeq: z.number().int().nonnegative(), // -1 = empty log (the lastSeq convention of session/subscribed).
asOfSeq: z.number().int().min(-1),
values: z.record(z.string(), z.unknown()), values: z.record(z.string(), z.unknown()),
}) as unknown as z.ZodType<SessionProjectionsBlock> }) as unknown as z.ZodType<SessionProjectionsBlock>
+8 -5
View File
@@ -37,13 +37,16 @@ export interface HistoryEntry {
/** /**
* The projection baseline riding the history tail page: one synchronous cut * The projection baseline riding the history tail page: one synchronous cut
* over every registered projection provider. `asOfSeq` equals the window tail * over every registered projection unit, read from the registry's watermark
* seq (the session's next-event seq at slice time) because the handler reads * cache. `asOfSeq` is the seq of the last committed event every value
* it and every value with no await in between. A key absent from `values` * reflects — the window tail event seq (`-1` for an empty log, mirroring
* means the capability is absent (its domain plugin is unmounted). * `session/subscribed.lastSeq`), directly comparable with
* `session/projection` frame seqs under the client's higher-seq-wins rule. A
* key absent from `values` means the capability is absent (its domain plugin
* is unmounted).
*/ */
export interface SessionProjectionsBlock { export interface SessionProjectionsBlock {
/** The session seq the values are consistent with (window tail seq). */ /** Seq of the last event the values reflect; -1 for an empty log. */
asOfSeq: number asOfSeq: number
/** Whole current value per registered projection key. */ /** Whole current value per registered projection key. */
values: Partial<SessionProjectionMap> values: Partial<SessionProjectionMap>
@@ -1,10 +1,10 @@
/** /**
* Projections block on the session.history tail page: a registered fake * Projection carrier paths of the host ApiProxy: the history tail page's
* provider's whole value rides the tail page with asOfSeq equal to the window * projections block reads the registry's watermark snapshot (asOfSeq = last
* tail seq; loadOlder pages (beforeSeq present) never carry the block; a * event seq, one consistent cut); loadOlder pages never carry the block; a
* composition without the registry serves histories without the block; a * composition without the registry serves histories without it; a disposed
* disposed registration's key leaves subsequent responses; and a provider * registration's key leaves subsequent responses; and every unit change is
* value rejected by its own schema fails the handler loud. * pushed to mux consumers as a session/projection frame minted here.
*/ */
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
@@ -15,15 +15,15 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import SessionStore from '@deepseek-ai/dsh-session' import SessionStore from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import type { ProjectionProvider } from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy' import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
declare module '@deepseek-ai/dsh-session-projection' { declare module '@deepseek-ai/dsh-session-projection/types' {
interface SessionProjectionMap { interface SessionProjectionMap {
'test/echo-seq': { seenSeq: number } 'test/last-user': { text: string } | null
} }
} }
@@ -32,12 +32,18 @@ function request<P>(payload: P): RpcRequest<P> {
return { rpcId: RpcId(`proj-${String(nextRpc++)}`), payload } return { rpcId: RpcId(`proj-${String(nextRpc++)}`), payload }
} }
/** Provider whose value records the session seq it observed at get() time. */ /** Whole-value unit folding the latest user/message text; null before the first. */
const echoSeqProvider: ProjectionProvider<'test/echo-seq'> = { type LastUserState = { text: string } | null
key: 'test/echo-seq', const lastUserUnit = (): ProjectionDefinition<'test/last-user', LastUserState> => ({
schema: z.object({ seenSeq: z.number().int().nonnegative() }), key: 'test/last-user',
get: agent => ({ seenSeq: agent.session.seq }), schema: z.union([z.object({ text: z.string() }), z.null()]),
} init: () => null,
apply: (state, event) => (event.type === 'user/message'
? { text: (event.data.content[0] as { text?: string }).text ?? '' }
: state),
view: state => state,
stateVersion: 1,
})
async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> { async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
const ctx = new Context() const ctx = new Context()
@@ -59,32 +65,29 @@ function seedMessages(session: Session, count: number): void {
} }
} }
describe('session.history projections block', () => { const api = (ctx: Context) => createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
it('serves the registered value on the tail page with asOfSeq = window tail seq', async () => {
const { ctx, session } = await harness(true)
ctx.sessionProjections.register(echoSeqProvider)
seedMessages(session, 3)
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
const response = await api.sessions.history(request({ sessionId: session.id })) describe('session.history projections block', () => {
it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
const { ctx, session } = await harness(true)
ctx.sessionProjections.register(lastUserUnit())
seedMessages(session, 3)
const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
expect(response.result.ok).toBe(true) expect(response.result.ok).toBe(true)
if (!response.result.ok) throw new Error('unreachable') if (!response.result.ok) throw new Error('unreachable')
const { events, projections } = response.result.value const { events, projections } = response.result.value
expect(projections).toBeDefined() expect(projections).toBeDefined()
expect(projections?.asOfSeq).toBe(session.seq) expect(projections?.asOfSeq).toBe(session.seq - 1)
// The cut is consistent: the value observed the same seq the block stamps. expect(projections?.values['test/last-user']).toEqual({ text: 'm2' })
expect(projections?.values['test/echo-seq']).toEqual({ seenSeq: session.seq }) // asOfSeq IS the window tail: the last served event carries it.
// asOfSeq is the window tail: the last served event sits right below it. expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq)
expect(events.at(-1)?.event.seq).toBe(session.seq - 1)
}) })
it('never carries the block on loadOlder pages (beforeSeq present)', async () => { it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
const { ctx, session } = await harness(true) const { ctx, session } = await harness(true)
ctx.sessionProjections.register(echoSeqProvider) ctx.sessionProjections.register(lastUserUnit())
seedMessages(session, 5) seedMessages(session, 5)
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const older = await api(ctx).sessions.history(request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
const older = await api.sessions.history(request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
expect(older.result.ok).toBe(true) expect(older.result.ok).toBe(true)
if (!older.result.ok) throw new Error('unreachable') if (!older.result.ok) throw new Error('unreachable')
expect('projections' in older.result.value).toBe(false) expect('projections' in older.result.value).toBe(false)
@@ -93,9 +96,7 @@ describe('session.history projections block', () => {
it('serves no block when the composition has no projection registry', async () => { it('serves no block when the composition has no projection registry', async () => {
const { ctx, session } = await harness(false) const { ctx, session } = await harness(false)
seedMessages(session, 2) seedMessages(session, 2)
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
const response = await api.sessions.history(request({ sessionId: session.id }))
expect(response.result.ok).toBe(true) expect(response.result.ok).toBe(true)
if (!response.result.ok) throw new Error('unreachable') if (!response.result.ok) throw new Error('unreachable')
expect('projections' in response.result.value).toBe(false) expect('projections' in response.result.value).toBe(false)
@@ -103,35 +104,78 @@ describe('session.history projections block', () => {
it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => { it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
const { ctx, session } = await harness(true) const { ctx, session } = await harness(true)
const dispose = ctx.sessionProjections.register(echoSeqProvider) const dispose = ctx.sessionProjections.register(lastUserUnit())
seedMessages(session, 1) seedMessages(session, 1)
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const proxy = api(ctx)
const before = await proxy.sessions.history(request({ sessionId: session.id }))
const before = await api.sessions.history(request({ sessionId: session.id }))
if (!before.result.ok) throw new Error('unreachable') if (!before.result.ok) throw new Error('unreachable')
expect(before.result.value.projections?.values['test/echo-seq']).toBeDefined() expect(before.result.value.projections?.values['test/last-user']).toEqual({ text: 'm0' })
dispose() dispose()
const after = await api.sessions.history(request({ sessionId: session.id })) const after = await proxy.sessions.history(request({ sessionId: session.id }))
if (!after.result.ok) throw new Error('unreachable') if (!after.result.ok) throw new Error('unreachable')
// The registry is still mounted, so the block itself stays (asOfSeq cut // The registry is still mounted, so the block itself stays (asOfSeq cut
// with zero keys); the disposed key reads as capability absence. // with zero keys); the disposed key reads as capability absence.
expect(after.result.value.projections?.asOfSeq).toBe(session.seq) expect(after.result.value.projections?.asOfSeq).toBe(session.seq - 1)
expect(after.result.value.projections?.values).toEqual({}) expect(after.result.value.projections?.values).toEqual({})
}) })
})
it('fails loud when a provider value violates its own schema (async get is unrepresentable)', async () => { describe('session/projection push frame', () => {
/** Drain frames until `count` session/projection frames arrived. */
async function collect(iterable: AsyncIterable<RpcRequest<MuxFrame>>, count: number, abort: AbortController): Promise<MuxFrame[]> {
const frames: MuxFrame[] = []
for await (const envelope of iterable) {
frames.push(envelope.payload)
if (frames.filter(f => f.type === 'session/projection').length >= count) abort.abort()
}
return frames
}
it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
const { ctx, session } = await harness(true) const { ctx, session } = await harness(true)
ctx.sessionProjections.register({ ctx.sessionProjections.register(lastUserUnit())
key: 'test/echo-seq', const proxy = api(ctx)
schema: z.object({ seenSeq: z.number().int().nonnegative() }), // The gateway's onChanged subscription lives in an inject child whose
// A Promise (what an accidentally-async get would return) is not the // fiber activates asynchronously; yield until it lands before appending.
// declared shape: the boundary parse rejects it before it hits the wire. await new Promise(resolve => setTimeout(resolve, 0))
get: () => Promise.resolve({ seenSeq: 0 }) as never, const abort = new AbortController()
}) const stream = proxy.events.mux({ rpcId: RpcId('t-proj-mux'), payload: {} }, abort.signal)
seedMessages(session, 1) const collected = collect(stream, 2, abort)
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
await expect(api.sessions.history(request({ sessionId: session.id }))).rejects.toThrow() seedMessages(session, 1)
// Same-reference apply: turn/start does not concern the unit — no frame.
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
seedMessages(session, 1)
const frames = await collected
const pushes = frames.filter(
(f): f is Extract<MuxFrame, { type: 'session/projection' }> => f.type === 'session/projection',
)
expect(pushes).toEqual([
{ type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
{ type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
])
// Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
const tail = await proxy.sessions.history(request({ sessionId: session.id }))
if (!tail.result.ok) throw new Error('unreachable')
expect(tail.result.value.projections?.asOfSeq).toBe(pushes.at(-1)?.seq)
})
it('emits no projection frames when the composition has no registry', async () => {
const { ctx, session } = await harness(false)
const proxy = api(ctx)
const abort = new AbortController()
const stream = proxy.events.mux({ rpcId: RpcId('t-noproj-mux'), payload: {} }, abort.signal)
const frames: MuxFrame[] = []
const drained = (async () => {
for await (const envelope of stream) {
frames.push(envelope.payload)
if (frames.filter(f => f.type === 'session/event').length >= 2) abort.abort()
}
})()
seedMessages(session, 2)
await drained
expect(frames.some(f => f.type === 'session/projection')).toBe(false)
}) })
}) })