perf(tui): open the /resume selector from one batch projection
The selector called readSession per listed session under an unbounded Promise.all: each call re-listed the whole persistence store (O(N^2) listings), decompressed and parsed the complete log, replay-validated every event, and deep-cloned it up to three times, only to derive one row's title, activity time, turn label, route, and goal phase. On a real 185-session / 87 MB store the selector took tens of seconds. Candidate rows now come from one projectSessions batch over borrowed logs; a rejected projection degrades to the same disabled unreadable row. Preflight still replay-validates the single chosen session through readSession, which is already live-preferred, so its redundant live shortcut is gone.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Session-resume sub-controller for the interactive chat channel: the
|
||||
* `/resume` selector, per-candidate summary reads that tolerate a corrupt
|
||||
* `/resume` selector, one batch summary projection that tolerates a corrupt
|
||||
* neighbor, the pre-handoff preflight, and the terminal handoff itself.
|
||||
* @module @deepseek-ai/dsh-tui/chat/resume
|
||||
*/
|
||||
@@ -10,7 +10,7 @@ import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
|
||||
import { errorChain } from '@deepseek-ai/dsh-llm'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {
|
||||
SessionLogSnapshot,
|
||||
LogicalSessionSource,
|
||||
SessionQueryService,
|
||||
SessionRecord,
|
||||
} from '@deepseek-ai/dsh-session-query'
|
||||
@@ -66,44 +66,45 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
|
||||
const workspaceLabel = (cwd: string | undefined): string =>
|
||||
runtime.formatCwd?.(cwd) ?? formatCwd(cwd)
|
||||
|
||||
/** Build one display candidate without letting a corrupt neighbor abort the selector. */
|
||||
/** Summarize one record from a borrowed source, retaining only the record and derived scalars. */
|
||||
const summarize = (
|
||||
record: SessionRecord,
|
||||
source: LogicalSessionSource,
|
||||
providers: ReadonlySet<string>,
|
||||
): ResumeCandidate => summarizeResumeCandidate(
|
||||
record,
|
||||
source,
|
||||
agent.session.id,
|
||||
agent.session.header.cwd,
|
||||
providers,
|
||||
workspaceLabel,
|
||||
)
|
||||
|
||||
/** The disabled fallback row for a session whose log cannot be summarized. */
|
||||
const unreadableCandidate = (record: SessionRecord, error: unknown): ResumeCandidate => ({
|
||||
record,
|
||||
title: 'Unreadable session',
|
||||
lastActivityAt: record.header.createdAt,
|
||||
lastTurn: 'log unavailable',
|
||||
currentWorkspace: record.header.cwd === agent.session.header.cwd,
|
||||
workspaceLabel: workspaceLabel(record.header.cwd),
|
||||
disabledReason: `session cannot be loaded: ${errorChain(error)}`,
|
||||
})
|
||||
|
||||
/** Build one exact candidate from a live-preferred read that replay-validates a persisted log. */
|
||||
const readResumeCandidate = async (
|
||||
record: SessionRecord,
|
||||
providers: ReadonlySet<string>,
|
||||
): Promise<ResumeCandidate> => {
|
||||
try {
|
||||
let snapshot: SessionLogSnapshot
|
||||
const live = ctx.sessions.get(record.header.id)
|
||||
if (live !== undefined) {
|
||||
snapshot = {
|
||||
session: structuredClone(live.header),
|
||||
events: live.events.map(event => structuredClone(event)),
|
||||
}
|
||||
} else {
|
||||
const readQuery = sessionQuery()
|
||||
/* v8 ignore start -- caller proves the optional service before mapping records */
|
||||
if (readQuery === undefined) throw new Error('session query is unavailable')
|
||||
/* v8 ignore stop */
|
||||
snapshot = await readQuery.readSession(record.header.id)
|
||||
}
|
||||
return summarizeResumeCandidate(
|
||||
record,
|
||||
snapshot,
|
||||
agent.session.id,
|
||||
agent.session.header.cwd,
|
||||
providers,
|
||||
workspaceLabel,
|
||||
)
|
||||
const readQuery = sessionQuery()
|
||||
/* v8 ignore start -- caller proves the optional service before mapping records */
|
||||
if (readQuery === undefined) throw new Error('session query is unavailable')
|
||||
/* v8 ignore stop */
|
||||
const snapshot = await readQuery.readSession(record.header.id)
|
||||
return summarize(record, { header: snapshot.session, events: snapshot.events }, providers)
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
record,
|
||||
title: 'Unreadable session',
|
||||
lastActivityAt: record.header.createdAt,
|
||||
lastTurn: 'log unavailable',
|
||||
currentWorkspace: record.header.cwd === agent.session.header.cwd,
|
||||
workspaceLabel: workspaceLabel(record.header.cwd),
|
||||
disabledReason: `session cannot be loaded: ${errorChain(error)}`,
|
||||
}
|
||||
return unreadableCandidate(record, error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +200,25 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
|
||||
// Every workspace in the store is summarized; the picker owns the
|
||||
// current-workspace/all-workspaces scope split over the whole set.
|
||||
const providers = new Set(ctx.llm.listProviders().map(provider => provider.id))
|
||||
const candidates = await Promise.all(records.map(record => readResumeCandidate(record, providers)))
|
||||
// One bounded batch projection over borrowed logs: unlike a
|
||||
// per-candidate readSession, it lists persistence once and skips
|
||||
// replay validation and log cloning, so opening the selector scales
|
||||
// with session count instead of total log size. A corrupt neighbor
|
||||
// degrades to one disabled row.
|
||||
const recordById = new Map(records.map(record => [record.header.id, record]))
|
||||
const listedRecord = (id: SessionId): SessionRecord => {
|
||||
const record = recordById.get(id)
|
||||
/* v8 ignore next 2 -- projection ids come from this map; the corpus verifies each loaded header id */
|
||||
if (record === undefined) throw new Error(`resume scan returned unlisted session "${id}"`)
|
||||
return record
|
||||
}
|
||||
const results = await listQuery.projectSessions(
|
||||
records.map(record => record.header.id),
|
||||
source => summarize(listedRecord(source.header.id), source, providers),
|
||||
)
|
||||
const candidates = results.map(result => result.status === 'fulfilled'
|
||||
? result.value
|
||||
: unreadableCandidate(listedRecord(result.sessionId), result.reason))
|
||||
candidates.sort((a, b) => b.lastActivityAt - a.lastActivityAt
|
||||
|| a.record.header.id.localeCompare(b.record.header.id))
|
||||
if (deps.isDisposed() || scan !== resumeScan) return
|
||||
|
||||
@@ -28,7 +28,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { foldGoal, type GoalPhase } from '@deepseek-ai/dsh-goal'
|
||||
import { foldSessionTitle } from '@deepseek-ai/dsh-session-title'
|
||||
import type {
|
||||
SessionLogSnapshot,
|
||||
LogicalSessionSource,
|
||||
SessionRecord,
|
||||
} from '@deepseek-ai/dsh-session-query'
|
||||
import type { AskUserQuestionItem } from '@deepseek-ai/dsh-user-interaction'
|
||||
@@ -453,8 +453,8 @@ export interface ResumeCandidate {
|
||||
disabledReason?: string
|
||||
}
|
||||
|
||||
function resumeTurnLabel(snapshot: SessionLogSnapshot): string {
|
||||
const event = snapshot.events.findLast(item => item.type === 'turn/end')
|
||||
function resumeTurnLabel(source: LogicalSessionSource): string {
|
||||
const event = source.events.findLast(item => item.type === 'turn/end')
|
||||
if (event === undefined) return 'no completed turn'
|
||||
const reason = event.data.reason
|
||||
switch (reason.kind) {
|
||||
@@ -468,24 +468,26 @@ function resumeTurnLabel(snapshot: SessionLogSnapshot): string {
|
||||
}
|
||||
}
|
||||
|
||||
function resumeRoute(snapshot: SessionLogSnapshot): ResumeRoute | undefined {
|
||||
const header = snapshot.events.findLast(item => item.type === 'request/header')
|
||||
function resumeRoute(source: LogicalSessionSource): ResumeRoute | undefined {
|
||||
const header = source.events.findLast(item => item.type === 'request/header')
|
||||
if (header?.type === 'request/header') {
|
||||
return { provider: header.data.header.config.provider, model: header.data.header.config.model }
|
||||
}
|
||||
const assistant = snapshot.events.findLast(item => item.type === 'assistant/message')
|
||||
const assistant = source.events.findLast(item => item.type === 'assistant/message')
|
||||
return assistant?.type === 'assistant/message'
|
||||
? { provider: assistant.data.message.source.provider, model: assistant.data.message.source.model }
|
||||
: undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one resume selector row from a record and its log snapshot, deriving the
|
||||
* title, route, goal phase, workspace scope, and any reason the session cannot
|
||||
* be resumed here. A workspace other than the current one is a scope, not a
|
||||
* disabled reason: resuming it hands the process off into that directory.
|
||||
* Build one resume selector row from a record and its borrowed log source,
|
||||
* deriving the title, route, goal phase, workspace scope, and any reason the
|
||||
* session cannot be resumed here. A workspace other than the current one is a
|
||||
* scope, not a disabled reason: resuming it hands the process off into that
|
||||
* directory. The result retains only the record and derived scalars, so a
|
||||
* borrowed source stays valid for exactly this call.
|
||||
* @param record - The session record.
|
||||
* @param snapshot - The session's log snapshot.
|
||||
* @param source - The session's borrowed header and raw event log.
|
||||
* @param currentId - The current session id.
|
||||
* @param cwd - The CURRENT session's workspace, which decides the picker scope this row falls in.
|
||||
* @param availableProviders - Providers registered in this runtime.
|
||||
@@ -494,15 +496,15 @@ function resumeRoute(snapshot: SessionLogSnapshot): ResumeRoute | undefined {
|
||||
*/
|
||||
export function summarizeResumeCandidate(
|
||||
record: SessionRecord,
|
||||
snapshot: SessionLogSnapshot,
|
||||
source: LogicalSessionSource,
|
||||
currentId: SessionId,
|
||||
cwd: string | undefined,
|
||||
availableProviders: ReadonlySet<string>,
|
||||
formatWorkspace: (cwd: string | undefined) => string,
|
||||
): ResumeCandidate {
|
||||
const title = foldSessionTitle(snapshot.events)?.title ?? 'Untitled session'
|
||||
const route = resumeRoute(snapshot)
|
||||
const foldedGoal = foldGoal(snapshot.events).goal
|
||||
const title = foldSessionTitle(source.events)?.title ?? 'Untitled session'
|
||||
const route = resumeRoute(source)
|
||||
const foldedGoal = foldGoal(source.events).goal
|
||||
let disabledReason: string | undefined
|
||||
if (record.header.id === currentId) disabledReason = 'current session'
|
||||
else if (record.live) disabledReason = 'session is already live in this runtime'
|
||||
@@ -514,8 +516,8 @@ export function summarizeResumeCandidate(
|
||||
record,
|
||||
title,
|
||||
// Excludes a prior pickup's boundary, or every browsed session floats up.
|
||||
lastActivityAt: lastActivityTime(snapshot.events) ?? snapshot.session.createdAt,
|
||||
lastTurn: resumeTurnLabel(snapshot),
|
||||
lastActivityAt: lastActivityTime(source.events) ?? source.header.createdAt,
|
||||
lastTurn: resumeTurnLabel(source),
|
||||
currentWorkspace: record.header.cwd === cwd,
|
||||
workspaceLabel: formatWorkspace(record.header.cwd),
|
||||
...route === undefined ? {} : { route },
|
||||
|
||||
@@ -273,6 +273,20 @@ describe('goodbye message and /resume', () => {
|
||||
{ type: 'turn/end', seq: 6, time: time + 6, data: { turn: 1, reason } },
|
||||
{ type: 'session/title', seq: 7, time: time + 7, data: { title, messageSeqs: [1], source: { kind: 'fallback' } } },
|
||||
]
|
||||
/** Derive the selector's batch projection from a fake per-session readSession. */
|
||||
const projectViaReadSession = (
|
||||
readSession: (id: SessionId) => Promise<{ session: SessionHeader; events: SessionEvent[] }>,
|
||||
) => (
|
||||
ids: readonly SessionId[],
|
||||
project: (source: { header: SessionHeader; events: readonly SessionEvent[] }) => unknown,
|
||||
) => Promise.all(ids.map(async (sessionId) => {
|
||||
try {
|
||||
const snapshot = await readSession(sessionId)
|
||||
return { sessionId, status: 'fulfilled', value: project({ header: snapshot.session, events: snapshot.events }) }
|
||||
} catch (reason) {
|
||||
return { sessionId, status: 'rejected', reason }
|
||||
}
|
||||
}))
|
||||
|
||||
it('prints the host goodbye message on exit', async () => {
|
||||
const result = await setup({
|
||||
@@ -516,6 +530,7 @@ describe('goodbye message and /resume', () => {
|
||||
queryCtx = child
|
||||
child.provide('sessionQuery', {
|
||||
listSessions: async () => { listCalls++; return [] },
|
||||
projectSessions: async () => [],
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
@@ -546,16 +561,18 @@ describe('goodbye message and /resume', () => {
|
||||
cwd: '/workspace',
|
||||
async configureContext(ctx) {
|
||||
ctx.provide('tools', { get: () => undefined } as never)
|
||||
const readSession = () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Query-only persisted session'),
|
||||
})
|
||||
ctx.provide('sessionQuery', {
|
||||
listSessions: () => Promise.resolve([{
|
||||
header: target,
|
||||
live: false,
|
||||
persisted: true,
|
||||
}]),
|
||||
readSession: () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Query-only persisted session'),
|
||||
}),
|
||||
readSession,
|
||||
projectSessions: projectViaReadSession(readSession),
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
@@ -593,6 +610,7 @@ describe('goodbye message and /resume', () => {
|
||||
ctx.provide('tools', { get: () => undefined } as never)
|
||||
ctx.provide('sessionQuery', {
|
||||
listSessions: () => ++calls === 1 ? first.promise : Promise.resolve([]),
|
||||
projectSessions: async () => [],
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
@@ -685,16 +703,18 @@ describe('goodbye message and /resume', () => {
|
||||
handoffResume: handoff,
|
||||
async configureContext(ctx) {
|
||||
ctx.provide('tools', { get: () => undefined } as never)
|
||||
const readSession = () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Live target'),
|
||||
})
|
||||
ctx.provide('sessionQuery', {
|
||||
listSessions: () => Promise.resolve([{
|
||||
header: target,
|
||||
live: true,
|
||||
persisted: true,
|
||||
}]),
|
||||
readSession: () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Live target'),
|
||||
}),
|
||||
readSession,
|
||||
projectSessions: projectViaReadSession(readSession),
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
@@ -815,12 +835,14 @@ describe('goodbye message and /resume', () => {
|
||||
async configureContext(ctx) {
|
||||
ctx.provide('tools', { get: () => undefined } as never)
|
||||
ctx.on('session/flush', flush)
|
||||
const readSession = () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Dispose during preflight'),
|
||||
})
|
||||
ctx.provide('sessionQuery', {
|
||||
listSessions: () => ++listings === 1 ? Promise.resolve([record]) : secondListing.promise,
|
||||
readSession: () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Dispose during preflight'),
|
||||
}),
|
||||
readSession,
|
||||
projectSessions: projectViaReadSession(readSession),
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
@@ -847,16 +869,18 @@ describe('goodbye message and /resume', () => {
|
||||
handoffResume: handoff,
|
||||
async configureContext(ctx) {
|
||||
ctx.provide('tools', { get: () => undefined } as never)
|
||||
const readSession = () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Query without persistence'),
|
||||
})
|
||||
ctx.provide('sessionQuery', {
|
||||
listSessions: () => Promise.resolve([{
|
||||
header: target,
|
||||
live: false,
|
||||
persisted: true,
|
||||
}]),
|
||||
readSession: () => Promise.resolve({
|
||||
session: target,
|
||||
events: resumeEvents('Query without persistence'),
|
||||
}),
|
||||
readSession,
|
||||
projectSessions: projectViaReadSession(readSession),
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user