feat(client): retain recent sessions and skip conversation folding while unrendered (#8502)

* feat(client): retain recent sessions and skip conversation folding while unrendered

* docs(notes): state that attention-protected recent views are unbounded

* refactor(ui-workspace): derive recent views from visit order and make the limit configurable

Recent views now hold exactly the Sessions one idempotent sync() selects from
the visit order and current snapshots, so navigation reports the shown Session
once and the main-view Session never counts. A failed Conversation resumption
leaves the binding stale so the next window change rebuilds the whole window.

* refactor(session-controller): report facet counts through retainInfo instead of SessionBinding

SessionBinding stays unchanged; SessionRetainInfo gains optional retainedFacets
counts beside retainedBy, and owners derive their facet from retainInfo and the
current binding. Adds the upgrade guide for Client plugins that render a Session
they retain, and updates two web e2e expectations: a recently viewed Session now
keeps its right Sidebar view state when the main view returns to it.

* feat(client): keep drafts with a connectionless Session hold and fold only the last page on return

Session references gain connection (true by default). When no reference keeps
it, the Session disconnects and empties its window while keeping its scope.
When the last facet is released, the Session keeps only its last Turn-aligned
page visible and its event stream buffers the older records, answering page
reads from that buffer before the Host. BoundConversation folds only while the
conversation facet is retained and drops its fold on release. The input hub
holds a Session with { source: 'draft', connection: false } while its draft has
attachments, replacing the root-level draft-attachment ownership; reload marks
remain.

* refactor(session-controller): share retain-info counting with the test fixture

* fix(client): keep gap repair, disconnect, and recent-view counting correct while Sessions are buffered

- Only page reads before the window take buffered records; a live gap repair
  reads the Host.
- A resync whose teardown a disconnect interrupted stays cold.
- A Session the main view already retains takes no recent-view slot before
  show(), so losing its unread protection during retention evicts nothing.
- Buffering marks the window partial, so the start-of-history marker survives
  after the buffer runs out.

* fix(session-controller): consume an arrived older page before buffering the window

* feat(ui-workspace): sync the recent-view limit from the Host Config

recentViewLimit becomes a volatile field of the ui-workspace Host Config
(z.natural().default(10)). The browser receives it through synced plugin
configuration, and RecentSessionViews reconciles whenever it changes, so a
cordis.yml edit takes effect without a page reload. Until a value arrives,
every counted recent view is kept.

The package gains a Host compiler face: src/types.ts holds the shared
Config type, tsconfig.host.json and tsconfig.client.json replace the single
Client config, and every reference names the face it compiles against.
This commit is contained in:
imccyu authored and GitHub committed 2026-11-17 20:51:42 +08:00
commit 7e7b604620
99 files changed
+2456 -518

No files matched your search

@@ -14,7 +14,7 @@ import type { SessionSearchResultItem } from '../sessions/manager.ts'
import type { SessionBinding, SessionListState } from '../sessions/service.ts'
import type { SessionFace } from './session.ts'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { SessionReferenceSource } from '../index.ts'
import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts'
export type { AgentContext } from '../scope.ts'
@@ -32,9 +32,20 @@ export interface SessionReference extends Disposable {
release(): void
}
/** Consumer identity and optional cancellation of one acquisition waiter. */
/** Consumer identity, retained facets, and optional cancellation of one acquisition waiter. */
export interface SessionRetainOptions {
readonly source: SessionReferenceSource
/**
* Whether this reference keeps the Session's own event connection and the event window it keeps current, so a
* return shows the data at once. Defaults to `true`; `false` keeps only the Session object and its local state,
* such as the composer draft. This is not the page's transport connection.
*/
readonly connection?: boolean | undefined
/**
* Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed.
* The set is fixed for the reference's lifetime.
*/
readonly facets?: Readonly<Partial<Record<SessionRetainFacet, true>>> | undefined
readonly signal?: AbortSignal | undefined
}
@@ -43,6 +54,13 @@ export interface SessionRetainInfo {
readonly referenceCount: number
/** Positive source counts only; a source without references is absent. */
readonly retainedBy: Readonly<Partial<Record<SessionReferenceSource, number>>>
/**
* Positive counts of references retaining each facet; absent while no reference retains any facet.
* Owners read their facet here, for example `(info.retainedFacets?.conversation ?? 0) > 0`.
*/
readonly retainedFacets?: Readonly<Partial<Record<SessionRetainFacet, number>>>
/** Positive count of references keeping the event connection; absent while none does. */
readonly connectionCount?: number
}
/** The sessions-service face injected as `ctx.sessions`. */
@@ -87,6 +87,15 @@ export interface SessionReferenceSourceMap {
/** Declaration-merge-extensible labels carried by independent Client references. */
export type SessionReferenceSource = Extract<keyof SessionReferenceSourceMap, string>
/**
* Owner-declared parts of a retained Session beyond its history stream, each counted independently.
* Owners extend it by augmenting this package's canonical `/client` module specifier; the Controller assigns no meaning to a key.
*/
export interface SessionRetainFacetMap {}
/** Declaration-merge-extensible facet names a reference may retain. */
export type SessionRetainFacet = Extract<keyof SessionRetainFacetMap, string>
declare module '@deepseek-ai/cordis' {
interface Context {
/** Client Session object layer and Agent scope owner. */
@@ -0,0 +1,41 @@
/** Turn-aligned page cuts over buffered Session entries. */
import type { SessionEventLikeEntry, SessionLiveEventEntry } from '../contract/events.ts'
/** Minimum messages and Turn starts one page covers, as the Host pages history. */
export interface PageRule {
readonly minMessages: number
readonly minTurns: number
}
/**
* Find where the last page of `entries` starts: the latest `turn/start` at or before which the page holds at least
* `minMessages` user or assistant messages and crosses at least `minTurns` Turn starts.
* @param entries - contiguous entries or wire records in seq order.
* @param rule - page minima; absent minima make the whole range one page.
* @returns index of the page's first entry; 0 when the whole range is one page.
*/
export function tailPageStart(
entries: readonly { readonly event: { readonly type: string } }[],
rule: PageRule | undefined,
): number {
if (rule === undefined) return 0
let messages = 0
let turns = 0
for (let index = entries.length - 1; index > 0; index--) {
const type = entries[index]?.event.type
if (type === 'user/message' || type === 'assistant/message') messages++
if (type !== 'turn/start') continue
turns++
if (messages >= rule.minMessages && turns >= rule.minTurns) return index
}
return 0
}
/**
* Whether a window entry is a durable event rather than a transient Assistant chunk.
* @param entry - window entry.
* @returns true for a durable event.
*/
export function isDurableEntry(entry: SessionEventLikeEntry): entry is SessionLiveEventEntry {
return entry.type === 'event'
}
@@ -0,0 +1,77 @@
/** Per-generation reference counts: sources, owner-declared facets, and the event connection. */
import type { SessionRetainInfo, SessionRetainOptions } from '../contract/sessions.ts'
import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts'
type FacetCounts = NonNullable<SessionRetainInfo['retainedFacets']>
/**
* The facet keys a retain request sets to `true`.
* @param facets - the request's facet record.
* @returns the facets one reference retains for its lifetime.
*/
export function heldFacets(facets: SessionRetainOptions['facets']): readonly SessionRetainFacet[] {
if (facets === undefined) return []
return (Object.keys(facets) as SessionRetainFacet[]).filter(facet => facets[facet] === true)
}
/** What one reference counts while it lives. */
export interface RetainedUse {
readonly source: SessionReferenceSource
readonly facets: readonly SessionRetainFacet[]
readonly connected: boolean
}
/** Source labels are dictionary keys, including names also present on Object.prototype. */
function freezeRetainedBy(counts: Partial<Record<SessionReferenceSource, number>>): SessionRetainInfo['retainedBy'] {
Object.setPrototypeOf(counts, null)
return Object.freeze(counts)
}
/** Retain info of a generation that no reference holds. */
export const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) })
/**
* Count one reference in or out of a generation's retain info.
* @param info - the generation's current retain info.
* @param use - what the retained or released reference counts.
* @param delta - `1` when the reference is retained, `-1` when it is released.
* @returns the frozen next retain info; {@link EMPTY_RETAIN_INFO} once no reference remains.
*/
export function shiftRetention(info: SessionRetainInfo, use: RetainedUse, delta: 1 | -1): SessionRetainInfo {
const referenceCount = info.referenceCount + delta
if (referenceCount === 0) return EMPTY_RETAIN_INFO
const { [use.source]: sourceCount = 0, ...otherSources } = info.retainedBy
const nextSource = sourceCount + delta
const retainedBy = freezeRetainedBy(nextSource > 0 ? { ...otherSources, [use.source]: nextSource } : otherSources)
const retainedFacets = shiftFacetCounts(info.retainedFacets, use.facets, delta)
const connectionCount = (info.connectionCount ?? 0) + (use.connected ? delta : 0)
return Object.freeze({
referenceCount,
retainedBy,
...(retainedFacets === undefined ? {} : { retainedFacets }),
...(connectionCount === 0 ? {} : { connectionCount }),
})
}
/**
* Count one reference's facets in or out of a retain-info snapshot.
* @param counts - the previous positive facet counts, absent when none.
* @param facets - the facets of the retained or released reference.
* @param delta - `1` when the reference is retained, `-1` when it is released.
* @returns the frozen positive counts, or undefined when no facet remains retained.
*/
function shiftFacetCounts(
counts: FacetCounts | undefined,
facets: readonly SessionRetainFacet[],
delta: 1 | -1,
): FacetCounts | undefined {
if (facets.length === 0) return counts
// The facet key type is empty in programs where no owner has declared a facet, so counts are built over strings.
const next = new Map<string, number>(Object.entries(counts ?? {}))
for (const facet of facets) next.set(facet, (next.get(facet) ?? 0) + delta)
const positive = [...next].filter(([, count]) => count > 0)
if (positive.length === 0) return undefined
// Facet names are dictionary keys, including names also present on Object.prototype.
const record: FacetCounts = Object.assign(Object.create(null) as object, Object.fromEntries(positive))
return Object.freeze(record)
}
@@ -3,7 +3,7 @@
import type {
SessionHistoryRecord,
} from '../../types.ts'
import type { SessionEventLikeEntry } from '../contract/events.ts'
import type { SessionEventLikeEntry, SessionLiveEventEntry } from '../contract/events.ts'
/**
* Narrow aligned wire records to their Client event types without allocation.
@@ -13,7 +13,21 @@ import type { SessionEventLikeEntry } from '../contract/events.ts'
export function historyEntries(
records: readonly SessionHistoryRecord[],
): readonly SessionEventLikeEntry[] {
return records as unknown as readonly SessionEventLikeEntry[]
// Both views share the same validated objects.
const aligned: readonly unknown[] = records
return aligned as readonly SessionEventLikeEntry[]
}
/**
* View durable window entries, which the Client received as validated wire records, as those records again.
* @param entries - durable entries taken from the event window.
* @returns the same array typed as history transport records.
*/
export function historyRecords(
entries: readonly SessionLiveEventEntry[],
): readonly SessionHistoryRecord[] {
const aligned: readonly unknown[] = entries
return aligned as readonly SessionHistoryRecord[]
}
/**
@@ -15,8 +15,9 @@ import type { SessionFace } from '../contract/session.ts'
import type {
AgentContext, ISessions, SessionReference, SessionRetainInfo, SessionRetainOptions, SessionTarget,
} from '../contract/sessions.ts'
import type { SessionReferenceSource } from '../index.ts'
import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts'
import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from '../scope.ts'
import { EMPTY_RETAIN_INFO, heldFacets, shiftRetention } from './facets.ts'
import { SessionManager } from './manager.ts'
import type { SessionRemotes } from './remotes.ts'
import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts'
@@ -159,14 +160,18 @@ function incrementedTitle(title: string): string {
return `${title} (1)`
}
/** Source labels are dictionary keys, including names also present on Object.prototype. */
function freezeRetainedBy(counts: Partial<Record<SessionReferenceSource, number>>): SessionRetainInfo['retainedBy'] {
Object.setPrototypeOf(counts, null)
return Object.freeze(counts)
/**
* Drop what no remaining reference keeps: the connection when none keeps it, otherwise the older window pages
* when no facet computes over them any longer.
*/
function releaseConnectionWork(session: Session, before: SessionRetainInfo, after: SessionRetainInfo): void {
if ((before.connectionCount ?? 0) > 0 && after.connectionCount === undefined) {
void session.disconnect()
return
}
if (before.retainedFacets !== undefined && after.retainedFacets === undefined) session.bufferOlder()
}
const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) })
interface ScopeRecord {
fiber: Fiber
ctx: AgentContext
@@ -299,13 +304,14 @@ export class ClientSessions implements ISessions {
}
retain(target: SessionTarget, options: SessionRetainOptions): SessionReference {
const { source, signal } = options
const { source, signal, facets } = options
const connected = options.connection !== false
signal?.throwIfAborted()
if (this.closed) throw new Error('Session Controller is disposed')
const id = this.manager.resolveTarget(target)
const reference = this.retainScope(id, source)
const reference = this.retainScope(id, source, heldFacets(facets), connected)
try {
reference.attachOpening(this.manager.get(id).open(), signal)
reference.attachOpening(connected ? this.manager.get(id).open() : Promise.resolve(), signal)
return reference
} catch (error) {
reference.release()
@@ -517,7 +523,7 @@ export class ClientSessions implements ISessions {
*/
retainAgentScope(id: SessionId): SessionReference {
if (this.closed) throw new Error('Session Controller is disposed')
return this.retainScope(id, 'gateway')
return this.retainScope(id, 'gateway', [], false)
}
/**
@@ -559,23 +565,25 @@ export class ClientSessions implements ISessions {
return this.scopes.get(id)?.binding
}
private retainScope(id: SessionId, source: SessionReferenceSource): ClientSessionReference {
private retainScope(
id: SessionId,
source: SessionReferenceSource,
facets: readonly SessionRetainFacet[],
connected: boolean,
): ClientSessionReference {
const record = this.scopes.get(id) ?? this.materializeScope(id)
const previous = record.retention
record.retention = Object.freeze({
referenceCount: previous.referenceCount + 1,
retainedBy: freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }),
})
const use = { source, facets, connected }
record.retention = shiftRetention(record.retention, use, 1)
const reference = new ClientSessionReference(id, record, () => {
if (!record.live) return
const count = record.retention.referenceCount - 1
const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy
const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources
record.retention = count === 0
? EMPTY_RETAIN_INFO
: Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) })
if (count === 0) this.retireScope(id, record)
else this.publishRetention(id)
const before = record.retention
record.retention = shiftRetention(before, use, -1)
if (record.retention.referenceCount === 0) {
this.retireScope(id, record)
return
}
this.publishRetention(id)
releaseConnectionWork(record.session, before, record.retention)
})
if (this.list.getSnapshot().byId[id] === undefined && this.manager.subagentAddress(id) !== undefined) {
this.projectList()
@@ -8,6 +8,7 @@ import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
import type { MessageId } from '@deepseek-ai/dsh-llm/types'
import type { UserMessage } from '@deepseek-ai/dsh-llm/types'
import { SessionLogOffset, SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types'
import { isDurableEntry, tailPageStart } from './buffered-pages.ts'
import { SessionEventStream } from '../transport.ts'
import type { SessionJournalChange } from '../transport.ts'
import type {
@@ -584,11 +585,13 @@ export class Session implements SessionFace {
* 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)
this.openGeneration++
const generation = ++this.openGeneration
this.clearOlderHistory()
const events = this.events
this.events = undefined
await events?.dispose()
// A disconnect during teardown ends this rebuild; the Session stays cold.
if (generation !== this.openGeneration) return
this.openPromise = null
this.openState = 'cold'
this.openError = null
@@ -680,6 +683,49 @@ export class Session implements SessionFace {
this.notifier.markDirty()
}
/**
* Keep only the last page visible and buffer the older entries in the event stream, so paging back returns them
* without a request. Applies only to an open window longer than one page with no paging in progress.
*/
bufferOlder(): void {
// A page that arrived but was not consumed joins the window first, so no remounted view finds it waiting.
this.consumeOlder()
const events = this.events
if (this.openState !== 'open' || events === undefined || this.olderRequest !== null || this.pendingHistory !== null) return
const { entries } = this.eventSource.getSnapshot()
const start = tailPageStart(entries, HISTORY_PAGE_OPTIONS.turnWindow)
const first = entries[start]
const older = entries.slice(0, start)
if (first === undefined || older.length === 0 || !older.every(isDurableEntry)) return
events.bufferOlder(older, first.event.seq, this.hasMore)
this.baseSeq = SessionLogOffset(first.event.seq)
this.hasMore = true
this.historyWasPartial = true
this.eventSource.replace(entries.slice(start), true)
this.notifier.markDirty()
}
/**
* Close the event connection and drop the window while keeping the Session object, including pending
* submission echoes; the next `open()` connects as the first open did.
* @returns when the Remote iterator has completed teardown.
*/
async disconnect(): Promise<void> {
if (this.openState === 'cold') return
this.openGeneration++
this.clearOlderHistory()
const events = this.events
this.events = undefined
this.openPromise = null
this.openState = 'cold'
this.openError = null
this.baseSeq = SessionLogOffset(0)
this.hasMore = false
this.eventSource.replace([], false)
this.notifier.markDirty()
await events?.dispose()
}
/**
* Stop the Session's live Remote source.
* @returns when the Remote iterator has completed teardown.
@@ -21,10 +21,12 @@ import type {
SessionPageRequest,
SessionProjectionBaseline,
} from '../types.ts'
import { tailPageStart } from './sessions/buffered-pages.ts'
import {
historyEntries,
historyRecordFirstSeq,
historyRecordLastSeq,
historyRecords,
} from './sessions/history-records.ts'
import type { SessionEventLikeEntry, SessionLiveEventEntry } from './contract/events.ts'
import type { SessionRemotes } from './sessions/remotes.ts'
@@ -134,7 +136,18 @@ export function createSessionControlStream(
})
}
/** Gateway-owned event journal bound to one ordinary or direct-subagent Session address. */
/** Older records the published window released into memory, served to page reads before the Host. */
interface BufferedRecords {
/** Contiguous records before the published window, oldest first. */
records: readonly SessionHistoryRecord[]
/** Whether the Host has history before `records`. */
hostHasMore: boolean
}
/**
* Gateway-owned event journal bound to one ordinary or direct-subagent Session address. Pages before the published
* window come from buffered records first and from the Host after they run out; a replaced window drops the buffer.
*/
export class SessionEventStream extends RemoteJournalStream<
SessionJournalPage,
SessionHistoryRecord,
@@ -152,6 +165,7 @@ export class SessionEventStream extends RemoteJournalStream<
private readonly address: SessionAddress,
options: SessionEventStreamOptions,
) {
const buffered: BufferedRecords = { records: [], hostHasMore: false }
super(remote, {
name: 'session event stream',
emptyCursor: -1,
@@ -161,12 +175,31 @@ export class SessionEventStream extends RemoteJournalStream<
last: historyRecordLastSeq,
compare: (left, right) => left - right,
follows: (left, right) => right === left + 1,
publish: (change) => { options.publish(toSessionJournalChange(change)) },
publish: (change) => {
if (change.type === 'replace') buffered.records = []
options.publish(toSessionJournalChange(change))
},
...(options.carrierFailed === undefined
? {}
: { carrierFailed: options.carrierFailed }),
failed: options.failed,
})
this.buffered = buffered
}
private readonly buffered: BufferedRecords
/**
* Release the start of the published window into memory; later pages before the window return it without a
* request.
* @param entries - durable entries at the window's start, oldest first, that the window no longer shows.
* @param firstSeq - seq of the first entry the window still shows.
* @param hostHasMore - whether the Host has history before `entries`; ignored while older entries are buffered.
*/
bufferOlder(entries: readonly SessionLiveEventEntry[], firstSeq: number, hostHasMore: boolean): void {
if (this.buffered.records.length === 0) this.buffered.hostHasMore = hostHasMore
this.buffered.records = [...this.buffered.records, ...historyRecords(entries)]
this.releaseBefore(firstSeq)
}
/** @inheritdoc */
@@ -227,6 +260,13 @@ export class SessionEventStream extends RemoteJournalStream<
throughSeq: number,
signal: AbortSignal,
): Promise<SessionJournalPage> {
const buffered = this.buffered.records
// Only a page before the window reads the buffer; a gap repair without beforeSeq reads the Host.
if (request.beforeSeq !== undefined && buffered.length > 0) {
const start = tailPageStart(buffered, request.turnWindow)
this.buffered.records = buffered.slice(0, start)
return { records: buffered.slice(start), hasMore: start > 0 || this.buffered.hostHasMore }
}
const result = await this.remote.session.page(
{ address: this.address, throughSeq, ...request },
signal,