From b7ee38fef028167013791a6562378af5f47f0ca6 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 31 Jul 2026 16:39:33 +0800 Subject: [PATCH] feat(tui): open the /resume picker immediately with a loading state The selector overlay opens as soon as the command dispatches: the picker renders a loading placeholder over an undefined candidate set, owns terminal input from its first frame, answers Enter with a still-loading error, and cancels on Escape exactly like the loaded list. The finished scan swaps rows in through setCandidates without replacing the overlay; a scan failure closes it and keeps the existing notice. --- ...resume-selector-batch-projection.i18n.yaml | 4 +- ...-07-31-resume-selector-batch-projection.md | 4 +- ...-31-resume-selector-batch-projection.zh.md | 4 +- packages/ui/tui/README.i18n.yaml | 4 +- packages/ui/tui/README.md | 2 +- packages/ui/tui/README.zh.md | 2 +- packages/ui/tui/src/chat/resume.ts | 60 ++++++++++++------- packages/ui/tui/src/components/dialogs.ts | 44 ++++++++++---- .../resume-sessions-loading.expected.txt | 47 +++++++++++++++ packages/ui/tui/tests/tui.snapshot.ts | 18 +++++- packages/ui/tui/tests/tui.spec.ts | 36 +++++++++++ 11 files changed, 181 insertions(+), 44 deletions(-) create mode 100644 packages/ui/tui/tests/snapshots/resume-sessions-loading.expected.txt diff --git a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.i18n.yaml index c0faa37e8d..0e733bbb4d 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.md -2026-07-31-resume-selector-batch-projection.md: 0aad3d57079819165d345d494071eb04d0b50abd -2026-07-31-resume-selector-batch-projection.zh.md: 055e11c440114987c0c37a2d268bce3328d4b1bd +2026-07-31-resume-selector-batch-projection.md: 1120a0777bf6a6ca17dd0704d145a3c742be0695 +2026-07-31-resume-selector-batch-projection.zh.md: 79db30170765925a00be180ba2b56de8a87ba130 diff --git a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.md b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.md index 0aad3d5707..1120a0777b 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.md +++ b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.md @@ -14,6 +14,8 @@ Opening the TUI `/resume` selector called `sessionQuery.readSession()` once per The `/resume` selector builds all candidate rows from one `projectSessions` batch; a rejected projection degrades to that row's disabled "Unreadable session" fallback exactly as a failed `readSession` did. `summarizeResumeCandidate` takes the borrowed source and retains only the record and derived scalars. The pre-handoff preflight still reads the single chosen session through `readSession`, keeping full replay validation before the process re-execs; its redundant live-session shortcut was dropped because `readSession` is already live-preferred. +The selector overlay opens synchronously when `/resume` dispatches, before the scan settles: an `undefined` candidate set renders a "Loading sessions…" placeholder, the picker owns terminal input from its first frame (so keystrokes during a long scan reach the search field rather than the editor), Enter reports that sessions are still loading, and Escape cancels exactly as it does on the loaded list. The finished scan swaps rows in through `setCandidates` without replacing the overlay; a queued activation behind a closing predecessor receives an already-scanned set at construction; a scan failure closes the overlay and reports the existing failure notice. + ## Alternatives considered **Fix only the O(N²) listing inside `SessionCorpus.load()`.** Rejected as the primary fix: the per-candidate full decompress, replay validation, and triple clone dominate on large logs and remain O(total log bytes). The redundant pre-listing in `load()` is still a candidate cleanup, but it changes not-found/consistency error semantics and is not needed once the selector stops calling `readSession` per row. @@ -24,4 +26,4 @@ The `/resume` selector builds all candidate rows from one `projectSessions` batc ## Consequences -Opening `/resume` performs one listing plus one bounded-concurrency pass instead of N listings and N validated full copies; memory stays bounded by the concurrency limit because each projected log is released before its worker dequeues another id. Selector rows are no longer replay-validated — a log that lists and parses but would fail replay shows as a normal row until preflight rejects it, which preflight always re-checks before handoff. Fake `sessionQuery` services in TUI tests must now provide `projectSessions` alongside `listSessions`/`readSession`. +Opening `/resume` performs one listing plus one bounded-concurrency pass instead of N listings and N validated full copies; memory stays bounded by the concurrency limit because each projected log is released before its worker dequeues another id. Selector rows are no longer replay-validated — a log that lists and parses but would fail replay shows as a normal row until preflight rejects it, which preflight always re-checks before handoff. Fake `sessionQuery` services in TUI tests must now provide `projectSessions` alongside `listSessions`/`readSession`. Because the picker takes focus immediately, starting a second scan requires dismissing the current overlay first — a second `/resume` typed during a scan lands in the search field, which is the intended input capture. diff --git a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.zh.md b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.zh.md index 055e11c440..79db301707 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-07-31-resume-selector-batch-projection.zh.md @@ -14,6 +14,8 @@ Status: implemented `/resume` 选择器通过一次 `projectSessions` 批量调用构建全部候选行;被拒绝的投影会退化为该行的禁用"Unreadable session"回退,与之前 `readSession` 失败时的行为完全一致。`summarizeResumeCandidate` 接受借用的来源,且只保留记录和推导出的标量。移交前的预检仍通过 `readSession` 读取用户选中的单个会话,在进程 re-exec 前保留完整回放验证;其中冗余的实时会话捷径被删除,因为 `readSession` 本身已是实时优先。 +选择器 overlay 在 `/resume` 分发时同步打开,早于扫描结算:`undefined` 候选集渲染"Loading sessions…"加载占位符,选择器从第一帧起就拥有终端输入(长扫描期间的按键会进入搜索字段而非编辑器),Enter 提示会话仍在加载,Escape 的取消方式与已加载列表完全相同。扫描完成后通过 `setCandidates` 换入行数据,不替换 overlay;排在正在关闭的前任之后的排队激活会在构造时直接收到已扫描的集合;扫描失败会关闭 overlay 并报告既有的失败通知。 + ## Alternatives considered **只修复 `SessionCorpus.load()` 内部的 O(N²) 列表查询。** 作为主要修复被拒绝:在大日志上,按候选行执行的完整解压、回放验证和三重克隆才是主要开销,且仍是 O(日志总字节数)。`load()` 中的冗余预列表查询仍是一个候选清理项,但它会改变 not-found/一致性错误语义,而且一旦选择器不再按行调用 `readSession`,这项清理就不再必要。 @@ -24,4 +26,4 @@ Status: implemented ## Consequences -打开 `/resume` 只执行一次列表查询加一次有界并发扫描,而不是 N 次列表查询和 N 份经验证的完整副本;内存受并发上限约束,因为每个投影完的日志会在其 worker 出队下一个 id 前被释放。选择器行不再经过回放验证——一份可列出、可解析但回放会失败的日志会显示为普通行,直到预检拒绝它,而预检在移交前总会重新检查。TUI 测试中的伪造 `sessionQuery` 服务现在必须在 `listSessions`/`readSession` 之外提供 `projectSessions`。 +打开 `/resume` 只执行一次列表查询加一次有界并发扫描,而不是 N 次列表查询和 N 份经验证的完整副本;内存受并发上限约束,因为每个投影完的日志会在其 worker 出队下一个 id 前被释放。选择器行不再经过回放验证——一份可列出、可解析但回放会失败的日志会显示为普通行,直到预检拒绝它,而预检在移交前总会重新检查。TUI 测试中的伪造 `sessionQuery` 服务现在必须在 `listSessions`/`readSession` 之外提供 `projectSessions`。由于选择器立即接管焦点,启动第二次扫描需要先关闭当前 overlay——扫描期间输入的第二个 `/resume` 会落入搜索字段,这正是预期的输入捕获行为。 diff --git a/packages/ui/tui/README.i18n.yaml b/packages/ui/tui/README.i18n.yaml index e94be1a857..6cfcd6d8fe 100644 --- a/packages/ui/tui/README.i18n.yaml +++ b/packages/ui/tui/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/ui/tui/README.md -README.md: 63c888b1d51c02fa85a8f0cc1617874debd87c4e -README.zh.md: ca5efc9ae26a9833d271991f73a21c607d8fb09d +README.md: 74dbf0dc26f99d0d7a6586fe6caec1f0ccdb2f36 +README.zh.md: d0ec1acbecf6e82ef35027a72268ba16fee65d6f diff --git a/packages/ui/tui/README.md b/packages/ui/tui/README.md index 63c888b1d5..74dbf0dc26 100644 --- a/packages/ui/tui/README.md +++ b/packages/ui/tui/README.md @@ -32,7 +32,7 @@ The footer sums the session's reported usage as `↑ `/status` adds a point-in-time diagnostics card to the transcript and remains available while the agent runs. It reports the session id, title, working directory, selected provider/model, selected reasoning effort or default behavior, reasoning-block visibility, agent state, event/turn/step/tool-call counts, exact input/output/cache token buckets, KV-cache hit rate, token-meter context use and capacity, creation time, and latest event time. Missing titles, models, cache input, or context capacity are labeled instead of inferred. The card is terminal-only and does not duplicate the compact footer. -`/resume` opens a full-viewport keyboard selector instead of a centered dialog. Two scopes cover the same candidate set: the current workspace, which it opens on, and all workspaces, which Tab toggles to. The scope line under the search field names the active scope and the count the other holds, and each row in the all-workspaces scope also reports its own workspace. Toggling clears the search and selection so the highlighted row always belongs to the visible list. +`/resume` opens a full-viewport keyboard selector instead of a centered dialog. The selector opens as soon as the command runs and takes input focus while the session scan is still pending, showing a loading placeholder until the rows arrive; Escape cancels an in-flight scan the same way it cancels the loaded list. Two scopes cover the same candidate set: the current workspace, which it opens on, and all workspaces, which Tab toggles to. The scope line under the search field names the active scope and the count the other holds, and each row in the all-workspaces scope also reports its own workspace. Toggling clears the search and selection so the highlighted row always belongs to the visible list. Its focused search field starts immediately after the search glyph and emits pi-tui's cursor marker, so terminal IME composition remains anchored inside the field. Candidates are sorted by last logged activity and searchable by log-backed title or session id, and by workspace label in the all-workspaces scope; each row reports current/live/persisted state, last turn outcome, recent provider/model, and durable goal phase when present. Up/Down and Page Up/Page Down navigate, Enter resumes, Escape clears a non-empty search before a second Escape cancels, and Ctrl+C cancels directly. The current session, a session already live in this runtime, an unreadable log, a session with no recorded workspace to run in, or a session whose logged provider has no current adapter remains visible but disabled; a workspace other than the current one is a scope rather than a disabled reason, because resume enters that directory. diff --git a/packages/ui/tui/README.zh.md b/packages/ui/tui/README.zh.md index ca5efc9ae2..d0ec1acbec 100644 --- a/packages/ui/tui/README.zh.md +++ b/packages/ui/tui/README.zh.md @@ -32,7 +32,7 @@ Footer 将会话报告的用量汇总为 `↑`;任 `/status` 会向 transcript 添加一张时间点诊断卡片,并在 agent 运行时保持可用。它报告会话 id、标题、工作目录、所选提供方/模型、所选推理强度或默认行为、reasoning 块可见性、agent 状态、事件/轮次/步骤/工具调用计数、精确输入/输出/缓存 token bucket、KV-cache 命中率、token-meter 上下文用量与容量、创建时间和最新事件时间。缺失标题、模型、缓存输入或上下文容量时会明确标记,而非推断。该卡片只存在于终端,不会重复紧凑 footer。 -`/resume` 会打开全 viewport 键盘选择器,而非居中对话框。两个作用域覆盖同一候选项集合:打开时所处的当前工作区,以及按 Tab 切换到的所有工作区。搜索字段下方的作用域行会给出当前作用域的名称以及另一个作用域包含的数量,且在所有工作区作用域中每行还会报告自身所属的工作区。切换会清除搜索与选择,使高亮行始终属于可见列表。 +`/resume` 会打开全 viewport 键盘选择器,而非居中对话框。选择器在命令执行时立即打开并接管输入焦点,会话扫描仍在进行时显示加载占位符,直到行数据就绪;Escape 取消进行中的扫描,方式与取消已加载列表相同。两个作用域覆盖同一候选项集合:打开时所处的当前工作区,以及按 Tab 切换到的所有工作区。搜索字段下方的作用域行会给出当前作用域的名称以及另一个作用域包含的数量,且在所有工作区作用域中每行还会报告自身所属的工作区。切换会清除搜索与选择,使高亮行始终属于可见列表。 获得焦点的搜索字段紧跟搜索 glyph 开始,并发出 pi-tui 的 cursor marker,使终端 IME 组合保持锚定在字段内。候选项按最近记录的活动排序,可按日志支持的标题或会话 id 搜索,在所有工作区作用域中还可按工作区标签搜索;每行报告 current/live/persisted 状态、上一轮次结果、近期提供方/模型,以及存在时的持久目标阶段。Up/Down 与 Page Up/Page Down 导航,Enter 恢复,Escape 会先清除非空搜索,再次按下才取消,Ctrl+C 则直接取消。当前会话、已在本运行时中活跃的会话、不可读日志、没有可运行的已记录工作区的会话,或日志所记提供方没有当前适配器的会话仍会显示,但不可选择;不同于当前工作区的工作区属于作用域而非禁用原因,因为恢复会进入该目录。 diff --git a/packages/ui/tui/src/chat/resume.ts b/packages/ui/tui/src/chat/resume.ts index e6558ee4c3..b1386ba10d 100644 --- a/packages/ui/tui/src/chat/resume.ts +++ b/packages/ui/tui/src/chat/resume.ts @@ -195,6 +195,38 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro } const scan = ++resumeScan void resumeOverlay?.close() + // The picker opens before the scan settles so the terminal stops feeding + // the editor immediately; a queued activation (the closing predecessor + // still holds the slot) receives an already-scanned set through + // `scanned` instead of a loading placeholder. + let picker: ResumePicker | undefined + let scanned: ResumeCandidate[] | undefined + const session = overlayManager.open({ + create: (host) => { + picker = new ResumePicker( + scanned, + resolved.maxResumeOptions, + workspaceLabel(agent.session.header.cwd), + () => host.viewport.rows, + palette, + (candidate) => { void handoffResume(candidate, session) }, + () => { void session.close() }, + ) + return picker + }, + options: { + width: '100%', + maxHeight: '100%', + anchor: 'top-left', + margin: 0, + }, + }) + resumeOverlay = session + void session.closed.then(() => { + /* v8 ignore next -- overlay FIFO closes this session before a replacement can become the tracked resume overlay */ + if (resumeOverlay === session) resumeOverlay = undefined + }) + deps.requestRender() void listQuery.listSessions().then(async (records) => { if (deps.isDisposed() || scan !== resumeScan) return // Every workspace in the store is summarized; the picker owns the @@ -222,31 +254,13 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro candidates.sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.record.header.id.localeCompare(b.record.header.id)) if (deps.isDisposed() || scan !== resumeScan) return - const session = overlayManager.open({ - create: host => new ResumePicker( - candidates, - resolved.maxResumeOptions, - workspaceLabel(agent.session.header.cwd), - () => host.viewport.rows, - palette, - (candidate) => { void handoffResume(candidate, session) }, - () => { void session.close() }, - ), - options: { - width: '100%', - maxHeight: '100%', - anchor: 'top-left', - margin: 0, - }, - }) - resumeOverlay = session - void session.closed.then(() => { - /* v8 ignore next -- overlay FIFO closes this session before a replacement can become the tracked resume overlay */ - if (resumeOverlay === session) resumeOverlay = undefined - }) + scanned = candidates + picker?.setCandidates(candidates) deps.requestRender() }, (error: unknown) => { - if (!deps.isDisposed() && scan === resumeScan) deps.appendNotice(`Resume session scan failed: ${errorChain(error)}`, 'error') + if (deps.isDisposed() || scan !== resumeScan) return + void session.close() + deps.appendNotice(`Resume session scan failed: ${errorChain(error)}`, 'error') }) }, } diff --git a/packages/ui/tui/src/components/dialogs.ts b/packages/ui/tui/src/components/dialogs.ts index 604f1858de..6139a94773 100644 --- a/packages/ui/tui/src/components/dialogs.ts +++ b/packages/ui/tui/src/components/dialogs.ts @@ -537,6 +537,10 @@ export type ResumeScope = 'workspace' | 'all' * current session's workspace, `all` lists every workspace and labels each row * with its own. Tab toggles between them; the search query and selection reset * on a scope change so the highlighted row always belongs to the visible list. + * + * The picker opens before the session scan settles: an `undefined` candidate + * set renders a loading placeholder that keeps input away from the editor, + * and `setCandidates` swaps the scanned rows in without replacing the overlay. */ export class ResumePicker implements Component, Focusable { private readonly search = new Input() @@ -544,27 +548,41 @@ export class ResumePicker implements Component, Focusable { private selectedIndex = 0 private error = '' private scope: ResumeScope = 'workspace' + private candidates: readonly ResumeCandidate[] | undefined focused = false constructor( - private readonly candidates: readonly ResumeCandidate[], + candidates: readonly ResumeCandidate[] | undefined, private readonly maxVisible: number, private readonly workspaceLabel: string, private readonly viewportRows: () => number, private readonly palette: Palette, private readonly done: (candidate: ResumeCandidate) => void, private readonly cancel: () => void, - ) {} + ) { + this.candidates = candidates + } invalidate(): void { this.search.invalidate() } + /** + * Replace the loading placeholder with the scanned candidate set. + * @param candidates - the summarized rows the finished scan produced. + */ + setCandidates(candidates: readonly ResumeCandidate[]): void { + this.candidates = candidates + this.selectedIndex = 0 + this.invalidate() + } + /** Candidates in the active scope, before the search query narrows them. */ private scoped(): ResumeCandidate[] { + const candidates = this.candidates ?? [] return this.scope === 'all' - ? [...this.candidates] - : this.candidates.filter(candidate => candidate.currentWorkspace) + ? [...candidates] + : candidates.filter(candidate => candidate.currentWorkspace) } private filtered(): ResumeCandidate[] { @@ -646,7 +664,8 @@ export class ResumePicker implements Component, Focusable { this.error = '' } else if (matchesKey(data, Key.enter)) { const selected = filtered[this.selectedIndex] - if (selected === undefined) this.error = 'No session matches this search.' + if (this.candidates === undefined) this.error = 'Sessions are still loading.' + else if (selected === undefined) this.error = 'No session matches this search.' else if (selected.disabledReason !== undefined) this.error = selected.disabledReason else this.done(selected) } else { @@ -666,12 +685,13 @@ export class ResumePicker implements Component, Focusable { * workspace it means, and the inactive scope with the count Tab would reveal. */ private renderScopeLine(): string { - const inWorkspace = this.candidates.filter(candidate => candidate.currentWorkspace).length + const candidates = this.candidates ?? [] + const inWorkspace = candidates.filter(candidate => candidate.currentWorkspace).length const active = this.scope === 'workspace' ? `this workspace ${displayText(this.workspaceLabel)}` - : `all workspaces (${this.candidates.length})` + : `all workspaces (${candidates.length})` const other = this.scope === 'workspace' - ? `all workspaces (${this.candidates.length})` + ? `all workspaces (${candidates.length})` : `this workspace (${inWorkspace})` return `${this.palette.accent(active)}${this.palette.dim(` ⇥ ${other}`)}` } @@ -686,9 +706,12 @@ export class ResumePicker implements Component, Focusable { if (this.selectedIndex >= filtered.length) this.selectedIndex = Math.max(0, filtered.length - 1) const selected = filtered[this.selectedIndex] const position = selected === undefined ? 0 : this.selectedIndex + 1 + const title = this.candidates === undefined + ? 'Resume session' + : `Resume session (${position} of ${filtered.length})` const lines: string[] = [ '', - `${indent}${this.palette.bold(this.palette.accent(`Resume session (${position} of ${filtered.length})`))}`, + `${indent}${this.palette.bold(this.palette.accent(title))}`, '', ] @@ -737,7 +760,8 @@ export class ResumePicker implements Component, Focusable { push(this.palette.warning(` unavailable: ${displayText(candidate.disabledReason)}`)) } } - if (filtered.length === 0) push(this.palette.warning('No matching sessions.')) + if (this.candidates === undefined) push(this.palette.dim('Loading sessions…')) + else if (filtered.length === 0) push(this.palette.warning('No matching sessions.')) if (this.error !== '') { lines.push('') push(this.palette.error(displayText(this.error))) diff --git a/packages/ui/tui/tests/snapshots/resume-sessions-loading.expected.txt b/packages/ui/tui/tests/snapshots/resume-sessions-loading.expected.txt new file mode 100644 index 0000000000..e44621ad60 --- /dev/null +++ b/packages/ui/tui/tests/snapshots/resume-sessions-loading.expected.txt @@ -0,0 +1,47 @@ +terminal 92x32 buffer=normal length=32 base=0 viewport=0 +lifecycle started=1 stopped=0 progress=inactive +title "DSH snapshot" +cursor hidden column=6 viewportRow=4 bufferRow=4 +buffer +0| " " +1| " Resume session " + style 2-15 fg=bright-magenta bold +2| " " +3| " ╭──────────────────────────────────────────────────────────────────────────────────────╮ " + style 2-89 dim +4| " │ ⌕ │ " + style 2-2 dim + style 6-6 inverse + style 89-89 dim +5| " ╰──────────────────────────────────────────────────────────────────────────────────────╯ " + style 2-89 dim +6| " " +7| " this workspace /workspace/project ⇥ all workspaces (0) " + style 2-34 fg=bright-magenta + style 35-56 dim +8| " " +9| " Loading sessions… " + style 2-18 dim +10| " " +11| " " +12| " " +13| " " +14| " " +15| " " +16| " " +17| " " +18| " " +19| " " +20| " " +21| " " +22| " " +23| " " +24| " " +25| " " +26| " " +27| " " +28| " " +29| " " +30| " Type to search • ↑/↓ navigate • Tab scope • Enter resume • Esc clear/cancel " + style 2-84 dim +31| " " diff --git a/packages/ui/tui/tests/tui.snapshot.ts b/packages/ui/tui/tests/tui.snapshot.ts index 18f0a9a793..91d1a67d78 100644 --- a/packages/ui/tui/tests/tui.snapshot.ts +++ b/packages/ui/tui/tests/tui.snapshot.ts @@ -57,6 +57,7 @@ const CHECKPOINTS = [ 'model-switching', 'errors-and-help', 'disposed-terminal', + 'resume-sessions-loading', 'resume-sessions', 'resume-sessions-all-workspaces', 'status-diagnostics', @@ -883,9 +884,13 @@ describe('TUI terminal-state snapshots', () => { { type: 'session/end-seed', seq: 8, time: Date.parse('2026-07-23T07:59:00.000Z'), data: {} }, ], }) + const listGate = Promise.withResolvers() const harness = await setupSnapshot({ sessionPersistence: { - list: async () => [earlier, elsewhere], + list: async () => { + await listGate.promise + return [earlier, elsewhere] + }, load: async id => id === elsewhere.id ? log(elsewhere, 'Other workspace work', '2024-02-02') : log(earlier, 'Resume selector design', '2024-01-01'), @@ -893,8 +898,15 @@ describe('TUI terminal-state snapshots', () => { }, { columns: 92, rows: 32 }) harness.terminal.send('/resume') harness.terminal.send('\r') - // `/resume` scans persistence asynchronously, so the listing renders a tick - // after submit (the unit suite waits the same way); settle, then flush. + // The picker opens as soon as the command dispatches and owns input while + // the persistence scan is still pending, rendering a loading placeholder + // in place of rows; only the scan is gated, so this settle never lists. + await new Promise(resolve => setTimeout(resolve, 60)) + await harness.terminal.flush() + await checkpoint('resume-sessions-loading', harness.terminal, { includeScrollback: true }) + listGate.resolve(undefined) + // With the scan released, the listing renders a tick later (the unit suite + // waits the same way); settle, then flush. await new Promise(resolve => setTimeout(resolve, 60)) await harness.terminal.flush() await checkpoint('resume-sessions', harness.terminal, { includeScrollback: true }) diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 3729a1bd5b..bf7d646e24 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -616,6 +616,11 @@ describe('goodbye message and /resume', () => { }) result.terminal.send('/resume') result.terminal.send('\r') + // The loading picker owns input as soon as /resume runs, so the second + // scan starts after dismissing the first overlay, not by typing a second + // slash command over it. + result.terminal.send('\u001B') + await tick() result.terminal.send('/resume') result.terminal.send('\r') await tick() @@ -646,6 +651,37 @@ describe('goodbye message and /resume', () => { expect(result.terminal.stopped).toBeGreaterThan(0) }) + it('opens a loading picker immediately and swaps in the scanned rows', async () => { + const target = header('late-listing', 10, '/workspace') + const listing = Promise.withResolvers() + const result = await setup({ + cwd: '/workspace', + async configureContext(ctx) { + ctx.provide('tools', { get: () => undefined } as never) + const readSession = () => Promise.resolve({ + session: target, + events: resumeEvents('Late listing'), + }) + ctx.provide('sessionQuery', { + listSessions: () => listing.promise, + readSession, + projectSessions: projectViaReadSession(readSession), + } as never) + }, + }) + result.terminal.send('/resume') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Loading sessions…') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Sessions are still loading.') + listing.resolve([{ header: target, live: false, persisted: true }]) + await tick(); await tick() + expect(result.terminal.output).toContain('Late listing') + await dispose(result) + }) + it('drops loaded selector summaries when the TUI disposed during log reads', async () => { const target = header('dispose-during-load', 10, '/workspace') const loading = Promise.withResolvers<{ meta: SessionHeader; events: SessionEvent[] }>()