Files
deepseek-harness/packages/api/session-controller/src/client/transport.ts
T
a39d44b5dc feat(session): add host reading status to SessionStatus (#6858)
* ✨ feat(session): persist and synchronize read state

* 🌐 fix(client): complete Japanese labels after base update

* 📝 docs: refresh session read-state dependency graph

* 🧪 test(web): align session menu and read-state snapshots

* 🌐 fix(session): complete Japanese plugin metadata

* 🧪 test(web): distinguish unread from pending user input

* 🐛 修复会话阅读状态的故障隔离与生命周期

* 🐛 修复阅读状态依赖检查并补齐自动已读覆盖

* 🐛 恢复会话绿点并移除未读标题加粗

* ♻️ Keep shared session reading state in Host memory

* 🌐 Complete reading-state metadata for supported locales

* 📝 Refresh module graph after removing storage dependency

* 🧹 Move storage dependency policy out of memory-only reading

* 🐛 Wait for sidebar catalog before replay navigation

* 🔧 Give Host TypeScript checks 8 GiB of heap

* ✅ Align Host heap checks and Windows diagnostics

* ♻️ Keep CI repairs outside the session reading PR

* 🐛 Show failed unread turns with an error indicator

* 🔧 Adjust npm layout budget for the reading package

* 🧪 Scope projection stream assertions to observed units

* 🧪 Scope permission and title assertions to their projections

* ♻️ Simplify session reading updates to explicit positions

* 🐛 Align session reading package with release version

* 🧪 Load reading state in LiveShare viewer fixtures

* 🧹 Remove persistence-only type link from memory PR

* 🧪 Align context menu expectations with reading actions

* 🐛 Sync reading package with the release version

* 🧪 Include turn boundaries in session summary expectations

* ♻️ Derive reading failure facts from Host events instead of a projection

The reading service took each completion from the Agent turn-boundary
projection, which forced a stateVersion bump and put that projection's whole
internal state on the wire for every Session list row. The service now records
`turn/end` itself, so `core/agent` and the persisted projection schema are
untouched.

History that ended before the service started raises no reminder, which keeps
"existing history reads as read" without a startup scan. The failure flag
therefore describes only turns this Host observed: marking a Session whose last
turn failed before a restart shows the ordinary unread reminder.

* 🐛 Preserve manual unread until explicit Session interaction

* 🧪 Align cold Session reading snapshot with unloaded title

* 🔖 chore(session): align session-read-state with 0.2.2-rc.2

Master moved the root and every released manifest to 0.2.2-rc.2, but the
new dsh-session-read-state package still declared 0.2.2-rc.1, failing
constraints, verify-version-sync, verify-npm-install-layout, and
release:verify after the master merge.

* ♻️ refactor(gateway): recognize Remote stream carrier loss by error code

RemoteStream now decides whether a generation end or failure is a
retryable carrier loss by the stable code 'gateway/carrier-lost' instead
of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps
working and carries that code, so existing callers are unchanged, while a
Client feature package can return a coded Error from `ended` without
importing the class. The new RemoteStreamCarrierFailure type describes
such errors; terminal-controller classifies disconnects the same way.

* ♻️ refactor(session): move Session reading into ui-session-status

Fold the reading feature into the single package
packages/client/ui-session-status and delete session-read-state.

- Host face: SessionStatusService keeps in-memory reading records and
  serves the sessionStatus Remote namespace (mark, follow) with
  session-status/* error codes; its service key is registered only for
  Gateway discovery and is not declared on Context.
- Client face: a package-internal reading model follows the Host stream
  through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the
  records into completionUnread and completionFailed and exposes mark and
  readingReady; main-view acknowledgement and the
  session-status/read-intent event live here. No reading service or type
  is exported.
- verify-client-packages lets a packages/client feature package request
  packages/api rows through dsh.client.external; feature-to-feature
  requests stay rejected.
- ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client
  test runtime, docs, Agent Notes, and the upgrade guide follow.

* ♻️ refactor(session): clear manual unread only when the main view switches to the Session

Remove the session-status/read-intent event. ui-session-status now clears an
existing manual unread mark when the main view switches to a different
Session, including the first selection after a page load, once the reading
baseline is ready and the body arrives. Window focus, visibility changes,
a replaced binding for the same Session, and activity in the open Session
preserve manual unread.

ui-conversation returns to master (only the ui-session-status client
tsconfig reference remains), and ui-workspace navigation no longer emits
the event. Tests, the session-reading Web e2e case, READMEs, and the
reading Agent Note follow the new rule.

* 🐛 fix(session): address the Session status review findings

- Open the reading stream only while ctx.remoteAccess allows
  sessionStatus/follow, so a LiveShare viewer opens no owner-only stream,
  keeps readingReady false, and logs no synchronization failure; access
  changes start or stop the stream.
- Hide the unacknowledged completion of the Session the visible, focused
  main view retains; manual marks stay visible, completionFailed follows
  completionUnread, and the reminder returns on blur, hiding, or a switch.
- Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and
  SERVICE_ROLES entries; the service and SessionRead* types document on
  docs/subsystems/web-client.md, which now owns the reading section with
  the failed field.
- Document that a Host plugin reload can leave the Client with a terminal
  error until a page reload; drop the redundant types import and the
  unused publish() result.
- Archived Sessions read as read and offer no reading mark in the row
  menu or the toggle-read shortcut.
- session.toggleRead names the open dialog, open panel, or archived
  Session that blocks it instead of asking to select a Session.
- isRemoteStreamCarrierFailure rejects a RemoteError from the Host even
  when it carries gateway/carrier-lost; the code is Client-local.
- ./types is types-only like ui-trajectory, and files no longer ship
  lib/types JavaScript.

* 🐛 fix(session): close the remaining Session status review gaps

- The Gateway Client exports isRemoteStreamCarrierFailure, and the
  terminal view uses it, so a Host RemoteError carrying the carrier code
  shows as failed rather than disconnected.
- Each access grant's reading stream carries a token: frames a revoked
  or superseded stream still delivers are discarded, and cleanup waits
  for disposal before leaving reading unavailable unless a newer grant
  is active.
- The status table hides the viewed Session's natural reminder only
  while that Session is open; the panel case is a documented limitation.
- The README limitation and the upgrade guide state that only the
  main-view switch rule, including a reload restore, clears manual
  unread automatically.
- Add the missing blank line before the next heading in the web-client
  reading section.

* ♻️ refactor(session): install reading under the Session status table

- apply returns to master's form plus one line: UiSessionStatus is the
  root, published as the useSessionStatus source, and installReading()
  from the new src/client/read.ts follows Host reading records into it.
  UiSessionStatus takes master's three constructor parameters and
  creates its own SessionReadModel as the package-internal `reading`
  member; installSessionStatus is removed and acknowledge.ts stays a
  separate file.
- The viewed Session's snapshot subscription republishes the table only
  when its openState changes, so streamed events do not rebuild it.
- Remove the obsolete Dev Note sentence about failure outcomes.
- session.toggleRead passes when the Peer may not mark reading, matching
  the row menu, and reports readingUnavailable only while unsynchronized.

---------

Co-authored-by: imccyu <[email protected]>
Co-authored-by: imccyu <[email protected]>
2026-11-12 05:35:57 +00:00

249 lines
8.6 KiB
TypeScript

/** Session-specific adapters for Gateway-owned Remote stream lifecycles. */
import type {} from '@deepseek-ai/dsh-api-session-controller/remote'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import {
RemoteJournalStream,
RemoteSnapshotStream,
RemoteStreamCarrierError,
type ClientRemote,
type RemoteStreamCarrierFailure,
type RemoteJournalChange,
type RemoteJournalFrame,
} from '@deepseek-ai/dsh-api-gateway/client'
import type {
SessionAddress,
SessionAssistantStreamBaseline,
SessionAssistantStreamFrame,
SessionControlFrame,
SessionHistoryRecord,
SessionPage,
SessionPageRequest,
SessionProjectionBaseline,
} from '../types.ts'
import {
historyEntries,
historyRecordFirstSeq,
historyRecordLastSeq,
} from './sessions/history-records.ts'
import type { SessionEventLikeEntry, SessionLiveEventEntry } from './contract/events.ts'
import type { SessionRemotes } from './sessions/remotes.ts'
import { assertSessionWireEvent } from './session-wire-event.ts'
export {
SESSION_SEARCH_RESULT_LIMIT,
SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
} from '../types.ts'
/** Pagination fields bound to an already-addressed Session journal. */
export type ClientSessionPageRequest = Omit<SessionPageRequest, 'address' | 'throughSeq'>
/** Complete generated `ctx.remote.session` namespace. */
export type SessionRemote = ClientRemote['session']
/** Opening metadata carried only by a follow snapshot, never by loadOlder pages. */
interface SessionJournalPage extends SessionPage {
readonly projections?: SessionProjectionBaseline
readonly assistantStream?: SessionAssistantStreamBaseline
}
/** One complete publication from the Session journal stream. */
export type SessionJournalChange =
| {
readonly type: 'replace' | 'prepend'
readonly page: SessionJournalPage
readonly entries: readonly SessionEventLikeEntry[]
readonly hasMore: boolean
}
| { readonly type: 'append'; readonly entry: SessionLiveEventEntry }
| { readonly type: 'assistant-stream'; readonly frame: SessionAssistantStreamFrame }
function toSessionJournalChange(
change: RemoteJournalChange<
SessionJournalPage, SessionHistoryRecord, SessionAssistantStreamFrame
>,
): SessionJournalChange {
switch (change.type) {
case 'replace':
case 'prepend':
return { ...change, entries: historyEntries(change.entries) }
case 'append': {
return {
type: 'append',
entry: change.entry as unknown as SessionLiveEventEntry,
}
}
case 'notification':
return { type: 'assistant-stream', frame: change.notification }
}
}
type SessionControlBaselineFrame = Extract<SessionControlFrame, { type: 'baseline' }>
type SessionControlDeltaFrame = Exclude<SessionControlFrame, SessionControlBaselineFrame>
/** Gateway-owned control snapshot stream configured for Session frames. */
export type SessionControlStream = RemoteSnapshotStream<
SessionControlBaselineFrame,
SessionControlDeltaFrame
>
/** Domain sinks used by the Host-wide Session control stream. */
export interface SessionControlStreamOptions {
/** Apply a complete baseline or one later update. */
readonly accept: (frame: SessionControlFrame) => void
/** Observe a retryable carrier loss before reconnection. */
readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void
/** Publish a terminal business or protocol failure. */
readonly failed: (error: unknown) => void
}
/** Domain sinks used by one addressed Session event journal. */
export interface SessionEventStreamOptions {
/** Apply one complete event-window change. */
readonly publish: (change: SessionJournalChange) => void
/** Observe a retryable carrier loss before reconnection. */
readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void
/** Publish a terminal stream, page, or protocol failure after opening. */
readonly failed: (error: unknown) => void
}
/**
* Create the Host-wide Session control snapshot stream.
* @param remote - generated Session namespace and Gateway stream factory.
* @param options - Session state destinations.
* @returns an unstarted stream owned by the Client Session runtime.
*/
export function createSessionControlStream(
remote: SessionRemotes,
options: SessionControlStreamOptions,
): SessionControlStream {
const stream = remote.$stream<SessionControlFrame>({
name: 'session control stream',
open: signal => remote.session.control(signal),
ended: accepted => accepted
? new RemoteStreamCarrierError('session control stream ended without a terminal result')
: new Error('session control stream ended before its opening snapshot'),
...(options.carrierFailed === undefined ? {} : { carrierFailed: options.carrierFailed }),
})
return new RemoteSnapshotStream(stream, {
name: 'session control stream',
isSnapshot: (frame): frame is SessionControlBaselineFrame => frame.type === 'baseline',
replace: options.accept,
update: options.accept,
failed: options.failed,
})
}
/** Gateway-owned event journal bound to one ordinary or direct-subagent Session address. */
export class SessionEventStream extends RemoteJournalStream<
SessionJournalPage,
SessionHistoryRecord,
number,
ClientSessionPageRequest,
SessionAssistantStreamFrame
> {
/**
* @param remote - generated Session namespace and Gateway stream factory.
* @param address - durable ordinary-Session or direct-subagent address.
* @param options - Session event-window destinations.
*/
constructor(
private readonly remote: SessionRemotes,
private readonly address: SessionAddress,
options: SessionEventStreamOptions,
) {
super(remote, {
name: 'session event stream',
emptyCursor: -1,
entries: page => page.records,
hasMore: page => page.hasMore,
first: historyRecordFirstSeq,
last: historyRecordLastSeq,
compare: (left, right) => left - right,
follows: (left, right) => right === left + 1,
publish: (change) => { options.publish(toSessionJournalChange(change)) },
...(options.carrierFailed === undefined
? {}
: { carrierFailed: options.carrierFailed }),
failed: options.failed,
})
}
/** @inheritdoc */
protected override async * follow(
request: ClientSessionPageRequest,
signal: AbortSignal,
): AsyncIterable<RemoteJournalFrame<
SessionHistoryRecord, number, SessionJournalPage, SessionAssistantStreamFrame
>> {
let assistantRevision: number | undefined
for await (const frame of this.remote.session.follow({
address: this.address,
activate: true,
assistantStream: true,
...this.repairRequest(request),
}, signal)) {
if (frame.type === 'snapshot') {
for (const record of frame.records) assertSessionWireEvent(record.event)
if (frame.assistantStream === undefined) {
throw new RemoteError(
'gateway/internal',
'session assistant stream omitted its opted-in opening baseline',
{},
)
}
assistantRevision = frame.assistantStream.revision
yield {
type: 'opened',
cursor: frame.cursor,
page: {
records: frame.records,
hasMore: frame.hasMore,
projections: frame.projections,
assistantStream: frame.assistantStream,
},
}
continue
}
if (frame.type === 'assistant-stream') {
const expected = (assistantRevision ?? 0) + 1
if (frame.frame.revision !== expected) {
throw new RemoteStreamCarrierError(
`session assistant stream skipped revision ${String(expected)}`,
)
}
assistantRevision = frame.frame.revision
yield { type: 'notification', notification: frame.frame }
continue
}
assertSessionWireEvent(frame.event)
yield { type: 'entry', entry: frame }
}
}
/** @inheritdoc */
protected override async readPage(
request: ClientSessionPageRequest,
throughSeq: number,
signal: AbortSignal,
): Promise<SessionJournalPage> {
const result = await this.remote.session.page(
{ address: this.address, throughSeq, ...request },
signal,
)
if (!result.ok) throw result.error
for (const record of result.value.records) assertSessionWireEvent(record.event)
return result.value
}
/** @inheritdoc */
protected override repairRequest(
request: ClientSessionPageRequest,
): ClientSessionPageRequest {
return {
...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
...(request.turnWindow === undefined ? {} : { turnWindow: request.turnWindow }),
}
}
}