fix(web): reconcile durable inbox recovery with master

This commit is contained in:
_Kerman committed 2026-09-09 15:14:08 +08:00
1 parent cb999713d1
commit 72f2e71070
72 files changed
+485 -857

No files matched your search

@@ -1,24 +1,10 @@
/** Session-owned observable state excluding Conversation target data. */
import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
import type { RemoteFailure } from '@deepseek-ai/dsh-typert-protocol'
import type { SessionRequestId } from '../../types.ts'
/** One transient inbox occurrence from the authoritative queue snapshot. */
export interface QueuedMessage {
readonly id: MessageId
readonly messageId: MessageId
readonly placement: 'queued' | 'steering' | 'context'
/** Prompt-RPC identity of a browser-submitted occurrence; correlates the local submission echo. */
readonly rpcId?: SessionRequestId
readonly content: readonly ContentBlock[]
readonly preview: string
readonly text: string | null
}
/** One image displayed by a local submission echo before durable admission. */
export interface PendingSubmissionImage {
/** Browser-owned preview URL; its lifecycle belongs to the submitter, never this snapshot. */
@@ -82,7 +68,6 @@ export interface PromptError {
/** Immutable Session lifecycle and control snapshot. */
export interface SessionSnapshot {
readonly sessionId: SessionId
readonly queue: readonly QueuedMessage[]
/** Local prompt-submission echoes not yet observed as durable events or queue occurrences. */
readonly pendingSubmissions: readonly PendingSubmission[]
readonly running: boolean
@@ -8,7 +8,6 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
import type {
SessionControlBaseline,
SessionControlFrame,
SessionQueuedItem,
SessionSummary,
SessionJob as JobView,
} from '../../types.ts'
@@ -96,8 +95,6 @@ export class SessionManager {
private readonly sessions = new Map<SessionId, Session>()
/** In-flight Session disposals remain here after instances leave `sessions`, so manager disposal can await quiescence. */
private readonly sessionDisposals = new Set<Promise<void>>()
/** Latest transient queues, retained independently of Session object materialization. */
private readonly queues = new Map<SessionId, readonly SessionQueuedItem[]>()
/**
* Sessions that finished running while not selected — the sidebar's green
* "done" reminder (manager-owned, survives connection generations; cleared
@@ -290,11 +287,6 @@ export class SessionManager {
if (session === undefined) {
session = this.createSession(sessionId)
this.sessions.set(sessionId, session)
// Install the latest control baseline before the running-bit sync: a
// not-running summary must sweep replayed queue
// rows the same way a live status flip would (their retirement events dropped
// while the session was uninstantiated).
session.replaceControl(this.queues.get(sessionId) ?? [])
// Sync the running and blank bits from the list snapshot into the new
// instance (consistency when the list precedes open).
const summary = this.summaries.find(s => s.sessionId === sessionId)
@@ -669,22 +661,12 @@ export class SessionManager {
this.notifier.markDirty()
return
}
if (frame.type === 'jobs') {
if (frame.jobs.length === 0) this.jobsBySession.delete(frame.sessionId)
else this.jobsBySession.set(frame.sessionId, frame.jobs)
this.notifier.markDirty()
return
}
this.queues.set(frame.sessionId, frame.items)
this.sessions.get(frame.sessionId)?.handleControlFrame(frame)
if (frame.jobs.length === 0) this.jobsBySession.delete(frame.sessionId)
else this.jobsBySession.set(frame.sessionId, frame.jobs)
this.notifier.markDirty()
}
private replaceControlBaseline(baseline: SessionControlBaseline): void {
this.queues.clear()
for (const [sessionId, items] of Object.entries(baseline.queues)) {
this.queues.set(sessionId as SessionId, items)
}
this.jobsBySession.clear()
for (const [sessionId, jobs] of Object.entries(baseline.jobs)) {
if (jobs.length > 0) this.jobsBySession.set(sessionId as SessionId, jobs)
@@ -696,9 +678,6 @@ export class SessionManager {
store.truncate(asOfSeq)
store.seed({ ...block, asOfSeq })
}
for (const [sessionId, session] of this.sessions) {
session.replaceControl(this.queues.get(sessionId) ?? [])
}
this.notifier.markDirty()
}
@@ -738,7 +717,6 @@ export class SessionManager {
this.updateCatalogActivity(sessionId, false)
if (durableSubagent) this.sessions.get(sessionId)?.handleRunning(false)
else this.sessions.get(sessionId)?.handleRemoved()
this.queues.delete(sessionId)
this.jobsBySession.delete(sessionId)
if (!durableSubagent) this.projectionStores.delete(sessionId)
const inflightCatalog = this.catalogInflight.get(sessionId)
@@ -1,71 +0,0 @@
import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
import type { SessionQueuedItem } from '../../types.ts'
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import type { QueuedMessage } from '../contract/snapshot.ts'
const QUEUE_PREVIEW_CHARS = 200
// Attachment blocks are excluded: queue presentation renders them from
// `content`, so the text preview covers only what has no visual form.
function previewOf(content: readonly ContentBlock[]): string {
const flat = content
.filter(block => block.type !== 'image' && block.type !== 'file')
.map(block => (block.type === 'text' ? block.text : `[${block.type}]`))
.join(' ').replace(/\s+/g, ' ').trim()
const chars = Array.from(flat)
return chars.length > QUEUE_PREVIEW_CHARS ? `${chars.slice(0, QUEUE_PREVIEW_CHARS).join('')}…` : flat
}
function textOf(content: readonly ContentBlock[]): string | null {
if (!content.every(block => block.type === 'text')) return null
return content.map(block => block.text).join('')
}
type QueueItems = readonly SessionQueuedItem[]
/** Authoritative transient queue projection and durable steering handoff. */
export class SessionQueueMirror {
private current: readonly QueuedMessage[] = []
/**
* Return the current immutable queue projection.
* @returns current queue rows.
*/
snapshot(): readonly QueuedMessage[] {
return this.current
}
/**
* Replace from one authoritative stream queue frame.
* @param items - complete host queue snapshot.
*/
replace(items: QueueItems): void {
this.current = items.map((item) => {
const content = item.message.content as unknown as readonly ContentBlock[]
return {
id: item.id,
messageId: item.message.id,
placement: item.placement,
...(item.rpcId === undefined ? {} : { rpcId: item.rpcId }),
content,
preview: previewOf(content),
text: textOf(content),
}
})
}
/**
* Retire a transient steering row once its durable message enters the log.
* @param event - newly contiguous durable Session event.
* @returns whether the projection changed.
*/
acceptDurable(event: SessionEvent): boolean {
if (event.type !== 'user/message') return false
const messageId = event.data.id
const index = this.current.findIndex(item =>
item.placement === 'steering' && item.messageId === messageId)
if (index < 0) return false
this.current = this.current.filter((_item, candidate) => candidate !== index)
return true
}
}
@@ -1,6 +1,7 @@
// Sessions remain resident after creation so their open Remote sources keep running off-screen.
import type { Context } from '@deepseek-ai/cordis'
import type { InboxState } from '@deepseek-ai/dsh-agent/types'
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
import type { AttachmentIdType, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
@@ -13,9 +14,7 @@ import type {
QueueAction,
SessionAddress,
SessionAssistantStreamBaseline,
SessionControlFrame,
SessionProjectionBaseline,
SessionQueuedItem,
SessionRequestId,
} from '../../types.ts'
import type {
@@ -36,7 +35,6 @@ import type { SessionRemotes } from './remotes.ts'
import { ProjectionValueStore } from './projection-store.ts'
import type { ProjectionsBaseline } from './projection-store.ts'
import { resolvedClientTimeZone } from '../time-zone.ts'
import { SessionQueueMirror } from './queue-mirror.ts'
import {
ClientAssistantStream,
type ClientAssistantStreamResult,
@@ -99,8 +97,7 @@ export class Session implements SessionFace {
private jumpTargetSeq: SessionSeq | null = null
/** The running jump loop's completion, shared by retargeting callers. */
private jumpPromise: Promise<void> | null = null
/** Authoritative stream-only inbox snapshot; pending work never hits history. */
private readonly queueMirror = new SessionQueueMirror()
private readonly stopObservingInbox: () => void
private readonly assistantStream = new ClientAssistantStream()
private running = false
private address: SubagentAddress | undefined
@@ -121,7 +118,7 @@ export class Session implements SessionFace {
/** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */
private pendingSubmissions: readonly PendingSubmission[] = []
/** Per-echo settlement state; `retiring` latches the first observation so a
* queue frame and its durable event cannot both retire one echo. */
* Inbox projection and its durable event cannot both retire one echo. */
private readonly submissionSettlements = new Map<SessionRequestId, {
readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined
retiring: boolean
@@ -173,6 +170,9 @@ export class Session implements SessionFace {
this.snapshotCache = this.buildSnapshot()
})
this.snapshotCache = this.buildSnapshot()
this.stopObservingInbox = this.projections.faceOf('inbox').subscribe(() => {
this.observeSubmissionInbox()
})
}
/**
@@ -453,7 +453,7 @@ export class Session implements SessionFace {
}
/** Rebuild an opened history source after address replacement.
* Invalidates any in-flight open first; queue state belongs to the independently
* Invalidates any in-flight open first; projection state belongs to the independently
* reconnecting control stream and remains untouched. */
async resync(): Promise<void> {
if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open)
@@ -491,26 +491,6 @@ export class Session implements SessionFace {
// ---- Manager-only entry points (@internal; never called by the UI) ----
/**
* Replace every transient control value for this Session from one stream baseline.
* @param queue - complete pending queue for this Session.
*/
replaceControl(queue: readonly SessionQueuedItem[]): void {
this.queueMirror.replace(queue)
this.observeSubmissionQueue(queue)
this.notifier.markDirty()
}
/**
* Apply one Session-addressed live control update.
* @param frame - queue replacement addressed to this Session.
*/
handleControlFrame(frame: Extract<SessionControlFrame, { type: 'queue' }>): void {
this.queueMirror.replace(frame.items)
this.observeSubmissionQueue(frame.items)
this.notifier.markDirty()
}
/**
* Running-bit relay from the host stream (list entry and snapshot stay consistent).
* @param running - the new running state.
@@ -588,6 +568,7 @@ export class Session implements SessionFace {
* @returns when the Remote iterator has completed teardown.
*/
async dispose(): Promise<void> {
this.stopObservingInbox()
// Unsettled echoes retire as failed so their owners can restore or
// release browser resources; echoes already scheduled as observed keep
// that settlement.
@@ -713,18 +694,25 @@ export class Session implements SessionFace {
const event = entry.event
const awaitingFirstTurn = this.firstPromptPendingTurn
if (event.type === 'turn/start') this.firstPromptPendingTurn = false
const queueChanged = this.queueMirror.acceptDurable(event)
this.eventSource.append(entry)
// After the feed append: the conversation assembly's animation frame is
// registered by the feed subscribers above, so the echo-retirement frame
// scheduled here always runs after the durable node became renderable.
this.observeSubmissionEvent(event)
return queueChanged || awaitingFirstTurn !== this.firstPromptPendingTurn
return awaitingFirstTurn !== this.firstPromptPendingTurn
}
/** Retire the matching echo when a durable browser-prompt `user/message` becomes visible. */
/** Observe durable acceptance even when insertion and claim share one projection notification. */
private observeSubmissionEvent(event: { readonly type: string; readonly data?: unknown }): void {
if (this.submissionSettlements.size === 0 || event.type !== 'user/message') return
if (this.submissionSettlements.size === 0) return
if (event.type === 'agent/inbox/spliced') {
const splice = event.data as { readonly inserted?: unknown } | undefined
if (Array.isArray(splice?.inserted)) {
for (const message of splice.inserted) this.observeSubmissionEvent({ type: 'user/message', data: message })
}
return
}
if (event.type !== 'user/message') return
// Structural read: window entries may be compact history records, so the
// fields are narrowed rather than trusted (same posture as Conversation
// assembly matchers).
@@ -734,12 +722,15 @@ export class Session implements SessionFace {
this.scheduleObservedRetirement(source.rpcId as SessionRequestId, attachmentRefsIn(data?.content))
}
/** Retire echoes whose prompts landed in the host inbox instead of the log (running-turn submissions). */
private observeSubmissionQueue(items: readonly SessionQueuedItem[]): void {
/** Retire local echoes when their accepted messages appear in the durable Inbox projection. */
private observeSubmissionInbox(): void {
if (this.submissionSettlements.size === 0) return
for (const item of items) {
if (item.rpcId !== undefined) {
this.scheduleObservedRetirement(item.rpcId, attachmentRefsIn(item.message.content))
const inbox = this.projections.get('inbox') as InboxState | undefined
if (inbox === undefined) return
for (const message of [...inbox['next-turn'], ...inbox['next-step']]) {
const source = message.source
if (source.kind === 'user' && 'rpcId' in source) {
this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content))
}
}
}
@@ -795,7 +786,6 @@ export class Session implements SessionFace {
private buildSnapshot(): SessionSnapshot {
return {
sessionId: this.sessionId,
queue: this.queueMirror.snapshot(),
pendingSubmissions: this.pendingSubmissions,
running: this.running,
subagent: this.address === undefined