Merge #859: a chat view shows a Claude session's conversation, rendered and live (chat view 1/5)

# Conflicts:
#	docs/architecture-invariants.md
#	src/web/CLAUDE.md
#	src/web/public/settings-ui.js
This commit is contained in:
Codeman maintainer committed 2026-12-03 10:15:29 +01:00
commit 3397d11859
39 files changed
+3844 -244

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
/**
* @fileoverview The chat view's strings in Chinese (zh-CN), run through the real translator.
*
* chat-view.js looks its strings up itself (`_chatViewT`), because i18n.js skips the
* `data-i18n-skip` conversation. Pinned here:
* - each string the chat view draws reads in Chinese, and the numbers in it survive;
* - the setting that shows or hides the Chat / Terminal switch reads in Chinese.
*
* Port: N/A.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterAll, describe, expect, it } from 'vitest';
const I18N = readFileSync(resolve(import.meta.dirname, '../src/web/public/i18n.js'), 'utf8');
type Api = { t(s: string, vars?: Record<string, string>): string; configure(o: Record<string, string>): void };
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
runScripts: 'outside-only',
url: 'http://localhost/',
});
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
api.configure({ language: 'zh-CN' });
afterAll(() => dom.window.close());
describe('the chat view in zh-CN', () => {
it('translates the fold button, the empty thread and the dialog notice', () => {
expect(api.t('No messages yet.')).toBe('还没有消息。');
expect(api.t('Show all (3 lines)')).toBe('显示全部(3 行)');
expect(api.t('Claude is waiting for your answer in the terminal.')).toBe('Claude 正在终端中等待你的回答。');
// The notification drawer shows the same sentence without the period.
expect(api.t('Codex is waiting for your answer in the terminal')).toBe('Codex 正在终端中等待你的回答');
});
it('translates the Chat / Terminal switch setting', () => {
expect(api.t('Show the Chat / Terminal switch')).toBe('显示聊天 / 终端开关');
expect(
api.t(
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.'
)
).toBe('在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。');
});
});
+823
View File
@@ -0,0 +1,823 @@
/**
* @fileoverview The chat view (chat-view.js): a session's conversation as its main view.
*
* What is pinned, and why:
* - The pure helpers (`CodemanChatView` in constants.js): keep-warm turns are never drawn, a
* growing thread appends instead of redrawing, and long prompts fold.
* - Which sessions can show it comes from `window.__codemanChatViewModes` (the transcript
* capability), and remote and adopted sessions never do.
* - The chat view covers the terminal without removing it, and a session remembers its view.
* A focus that lands on the hidden terminal moves to the conversation.
* - A dialog in the pane shows the "waiting in the terminal" notice.
* - Codeman's own keep-alive turn shows no status line.
* - The toggle chord is swallowed by the xterm key handler, so it never types into the session.
*
* The real constants.js and chat-view.js run inside a JSDOM window.
*
* Port: none.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
type Msg = { role: string; text: string; turn?: number; keepAlive?: boolean; queued?: boolean };
interface ChatHelpers {
visibleMessages: (m: unknown) => Msg[];
messageKey: (m: Msg) => string;
renderPlan: (a: string[], b: string[]) => { mode: string; from?: number };
promptFold: (t: string) => { folded: boolean; head: string; totalLines: number };
promptText: (t: string) => string;
elapsed: (ms: number) => string;
}
function loadHelpers(): ChatHelpers {
const context = vm.createContext({ window: {}, globalThis: {} });
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
return (context.window as { CodemanChatView: ChatHelpers }).CodemanChatView;
}
describe('CodemanChatView helpers', () => {
const h = loadHelpers();
it('leaves out keep-warm turns and messages without text', () => {
const shown = h.visibleMessages([
{ role: 'user', text: 'Fix it', turn: 1 },
{ role: 'assistant', text: 'Done.', turn: 1 },
{ role: 'user', text: 'nudge', turn: 2, keepAlive: true },
{ role: 'assistant', text: 'ok', turn: 2, keepAlive: true },
{ role: 'assistant', text: ' ', turn: 3 },
null,
]);
expect(shown.map((m) => m.text)).toEqual(['Fix it', 'Done.']);
expect(h.visibleMessages(undefined)).toEqual([]);
});
it('appends when the thread only grew, and redraws when it changed', () => {
expect(h.renderPlan(['a', 'b'], ['a', 'b'])).toEqual({ mode: 'none' });
expect(h.renderPlan(['a', 'b'], ['a', 'b', 'c'])).toEqual({ mode: 'append', from: 2 });
expect(h.renderPlan([], ['a'])).toEqual({ mode: 'append', from: 0 });
expect(h.renderPlan(['a', 'b'], ['a', 'x', 'c'])).toEqual({ mode: 'replace' });
expect(h.renderPlan(['a', 'b'], ['a'])).toEqual({ mode: 'replace' });
});
it('keys a message by role, turn and text', () => {
const a = h.messageKey({ role: 'user', text: 'hi', turn: 1 });
expect(h.messageKey({ role: 'user', text: 'hi', turn: 1 })).toBe(a);
expect(h.messageKey({ role: 'user', text: 'hi', turn: 2 })).not.toBe(a);
expect(h.messageKey({ role: 'assistant', text: 'hi', turn: 1 })).not.toBe(a);
});
it('folds a prompt over 12 lines to its first 6, and one enormous line too', () => {
const short = Array.from({ length: 12 }, (_, i) => `line ${i}`).join('\n');
expect(h.promptFold(short).folded).toBe(false);
const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
const fold = h.promptFold(long);
expect(fold.folded).toBe(true);
expect(fold.totalLines).toBe(30);
expect(fold.head.split('\n')).toHaveLength(6);
const wide = h.promptFold('x'.repeat(5000));
expect(wide.folded).toBe(true);
expect(wide.head.length).toBeLessThanOrEqual(801);
});
it("unwraps Claude Code's pasted_content tag so a pasted prompt keeps its lines", () => {
expect(h.promptText('<pasted_content id="a9da">\nline 1\nline 2\n</pasted_content>')).toBe('line 1\nline 2');
expect(h.promptText('before <pasted_content>x</pasted_content> after')).toBe('before x after');
// Claude Code 2.1.331 repeats the id on the closing tag.
expect(h.promptText('<pasted_content id="a9da">\nA\nB\n</pasted_content id="a9da">')).toBe('A\nB');
expect(h.promptText('a <pasted_content id="1"> left open')).toBe('a <pasted_content id="1"> left open');
expect(h.promptText('plain')).toBe('plain');
});
it('formats the running time like the CLI', () => {
expect(h.elapsed(0)).toBe('0s');
expect(h.elapsed(14_900)).toBe('14s');
expect(h.elapsed(125_000)).toBe('2m 05s');
expect(h.elapsed(3_780_000)).toBe('1h 03m');
expect(h.elapsed(-5)).toBe('0s');
});
});
// ─── The module in a DOM ──────────────────────────────────────────────────────
type Api = ReturnType<typeof vi.fn>;
interface ChatApp {
activeSessionId: string | null;
sessions: Map<string, Record<string, unknown>>;
pendingHooks: Map<string, Set<string>>;
_api: Api;
_apiJson: Api;
showToast: Api;
_sendInputAsync: Api;
loadAppSettingsFromStorage: () => Record<string, unknown>;
_chatViewReload: () => void;
onChatViewTurnEvent: (id: string, idle: boolean, keepAlive?: boolean) => void;
chatViewEligible: (id: string) => boolean;
chatViewModeFor: (id: string) => string;
setChatViewMode: (id: string, mode: string) => void;
onChatViewActiveSession: (id: string) => void;
onChatViewHooksChanged: (id: string) => void;
_onChatViewTranscriptUpdate: (d: { sessionId: string }) => void;
_chatViewFetch: () => Promise<void>;
_chatViewForget: (id: string) => void;
_chatViewPruneModes: (ids: Set<string>) => void;
_chatViewHide: () => void;
_chatViewRenderStatus: () => void;
shouldToggleChatViewFromShortcut: (e: Partial<KeyboardEvent>) => boolean;
_chatView: {
root: HTMLElement;
toggle: HTMLElement;
thread: HTMLElement;
dialog: HTMLElement;
scroller: HTMLElement;
status: HTMLElement;
statusText: HTMLElement;
statusTimer: unknown;
};
}
function loadModule(opts: { messages?: Msg[][] } = {}) {
const dom = new JSDOM(
`<!doctype html><body><input type="file" id="attachFileInput" accept="image/*,.pdf">
<div class="terminal-wrap"><div id="terminalContainer"></div><textarea id="cjkInput"></textarea></div></body>`,
{ runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' }
);
const win = dom.window as unknown as Window & { eval: (s: string) => unknown; [k: string]: unknown };
win.__codemanChatViewModes = ['claude'];
// The window has a Date of its own. Tie it to the test's clock, so vi.setSystemTime reaches
// the module's elapsed times.
(win.Date as DateConstructor).now = () => Date.now();
win.eval('class CodemanApp {}; window.CodemanApp = CodemanApp;');
win.eval(read('constants.js'));
win.eval(read('chat-view.js'));
const proto = (win.CodemanApp as { prototype: object }).prototype;
const pages = [...(opts.messages ?? [[]])];
const app = Object.assign(Object.create(proto), {
activeSessionId: 's1',
sessions: new Map<string, Record<string, unknown>>([
['s1', { id: 's1', mode: 'claude', status: 'idle' }],
['s2', { id: 's2', mode: 'claude', status: 'idle', remote: { hostId: 'h' } }],
['s3', { id: 's3', mode: 'claude', status: 'idle', adopt: { target: 'x' } }],
['s4', { id: 's4', mode: 'codex', status: 'idle' }],
['s5', { id: 's5', mode: 'claude', status: 'idle', docker: { caseName: 'box' } }],
]),
pendingHooks: new Map<string, Set<string>>(),
loadAppSettingsFromStorage: () => ({}),
_getResponseViewerAgentLabel: () => 'Claude',
_buildResponseViewerMessage: (text: string, role: string, _label: string, meta?: { continuation?: boolean }) => {
const div = win.document.createElement('div');
div.className = `rv-message rv-msg-${role}`;
if (meta?.continuation) div.classList.add('rv-msg-cont');
const body = win.document.createElement('div');
body.className = 'rv-text';
body.textContent = text;
div.appendChild(body);
return div;
},
_bindResponseViewerInteractions: () => {},
_api: vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ success: true }) })),
_apiJson: vi.fn(async () => ({ messages: pages.length > 1 ? pages.shift() : pages[0] })),
showToast: vi.fn(),
_sendInputAsync: vi.fn(),
terminal: { focus: vi.fn() },
}) as ChatApp;
return { dom, win, app };
}
const settle = () => new Promise((r) => setTimeout(r, 0));
describe('chat view module', () => {
it('is offered only for sessions whose run mode has a Claude transcript, local or Docker', () => {
const { app } = loadModule();
expect(app.chatViewEligible('s1')).toBe(true);
expect(app.chatViewEligible('s5')).toBe(true); // Docker
expect(app.chatViewEligible('s2')).toBe(false); // remote
expect(app.chatViewEligible('s3')).toBe(false); // adopted
expect(app.chatViewEligible('s4')).toBe(false); // not in __codemanChatViewModes
expect(app.chatViewEligible('missing')).toBe(false);
});
it('is not offered on a phone, even one turned to landscape', () => {
const { win, app } = loadModule();
// A phone in landscape is wider than the phone breakpoint, so its width says "desktop".
win.MobileDetection = { isHandheldDevice: () => true, getDeviceType: () => 'desktop' };
expect(app.chatViewEligible('s1')).toBe(false);
win.MobileDetection = { isHandheldDevice: () => false, getDeviceType: () => 'desktop' };
expect(app.chatViewEligible('s1')).toBe(true);
});
it('opens in Chat when the device setting says so, unless the session remembers Terminal', () => {
const { win, app } = loadModule();
app.loadAppSettingsFromStorage = () => ({ chatViewDefault: true });
expect(app.chatViewModeFor('s1')).toBe('chat');
win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'terminal' }));
expect(app.chatViewModeFor('s1')).toBe('terminal');
});
it('marks the body while Chat shows, so the keyboard accessory bar stays hidden', () => {
const { win, app } = loadModule();
app.onChatViewActiveSession('s1');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
app.setChatViewMode('s1', 'chat');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
app.setChatViewMode('s1', 'terminal');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
});
it('moves a focus that lands in the hidden terminal to the conversation', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const inner = win.document.createElement('textarea');
win.document.getElementById('terminalContainer')!.appendChild(inner);
inner.focus();
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('moves a focus that lands on the CJK input field to the conversation', () => {
// With CJK input on, terminal.focus() lands on #cjkInput, outside #terminalContainer.
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
(win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus();
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('keeps a dropped file from opening in the browser while Chat shows', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
// The Chat / Terminal switch is a sibling of the chat view root, so it needs the guard too.
for (const target of [app._chatView.root, app._chatView.toggle]) {
for (const type of ['dragover', 'drop']) {
const ev = new win.Event(type, { bubbles: true, cancelable: true });
target.dispatchEvent(ev);
expect(ev.defaultPrevented).toBe(true);
}
}
});
it('hides the chat view, its switch and the body mark when the home screen shows', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(app._chatView.root.hidden).toBe(false);
app._chatViewHide();
expect(app._chatView.root.hidden).toBe(true);
expect(app._chatView.toggle.hidden).toBe(true);
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
});
it('starts in Terminal, covers the terminal once Chat is picked, and remembers the choice', async () => {
const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] });
app.onChatViewActiveSession('s1');
expect(app.chatViewModeFor('s1')).toBe('terminal');
expect(app._chatView.toggle.hidden).toBe(false);
expect(app._chatView.root.hidden).toBe(true);
app.setChatViewMode('s1', 'chat');
await settle();
expect(app._chatView.root.hidden).toBe(false);
// The terminal stays in the DOM underneath: nothing is removed or resized.
expect(win.document.getElementById('terminalContainer')).not.toBeNull();
expect(win.document.querySelector('.terminal-wrap')!.classList.contains('chat-view-active')).toBe(true);
expect(app._apiJson).toHaveBeenCalledWith('/api/sessions/s1/last-response?context=full');
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
// The per-session turn state goes with the session too.
const state = app as unknown as Record<string, Map<string, unknown> | Set<string>>;
state._chatViewTurnStarts = new Map([['s1', 1]]);
state._chatViewIdleSeen = new Set(['s1']);
state._chatViewKeepAliveTurns = new Set(['s1']);
// A detach sends the same event as a delete, so the view choice outlives it.
app._chatViewForget('s1');
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
for (const key of ['_chatViewTurnStarts', '_chatViewIdleSeen', '_chatViewKeepAliveTurns']) {
expect(state[key].has('s1')).toBe(false);
}
});
it("drops the view choices of sessions that are not in the init's session list", () => {
const { app, win } = loadModule();
win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'chat', gone: 'terminal' }));
app.setChatViewMode('s1', 'chat');
app.setChatViewMode('gone', 'terminal');
app._chatViewPruneModes(new Set(['s1', 's2']));
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
win.localStorage.clear();
expect(app.chatViewModeFor('gone')).toBe('terminal');
expect(app.chatViewModeFor('s1')).toBe('chat');
});
it('prunes the view choices from handleInit in app.js', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' handleInit(data) {');
const init = appJs.slice(start, appJs.indexOf('\n }\n', start));
expect(init).toContain('this._chatViewPruneModes?.(new Set(data.sessions.map((s) => s.id)));');
});
it('shows the Chat / Terminal switch when the device has no showChatViewSwitch setting', () => {
const { app } = loadModule();
app.loadAppSettingsFromStorage = () => ({});
app.onChatViewActiveSession('s1');
expect(app._chatView.toggle.hidden).toBe(false);
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true });
app._chatViewSync();
expect(app._chatView.toggle.hidden).toBe(false);
});
it('hides the switch when the setting is off, while Alt+Shift+C still switches views', async () => {
const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] });
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: false });
app.onChatViewActiveSession('s1');
expect(app._chatView.toggle.hidden).toBe(true);
app.toggleChatView();
await settle();
expect(app.chatViewModeFor('s1')).toBe('chat');
expect(app._chatView.root.hidden).toBe(false);
expect(app._chatView.toggle.hidden).toBe(true);
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
app.toggleChatView();
expect(app.chatViewModeFor('s1')).toBe('terminal');
expect(app._chatView.root.hidden).toBe(true);
// A settings save re-syncs: turning the setting back on shows the switch again.
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true });
app._chatViewSync();
expect(app._chatView.toggle.hidden).toBe(false);
});
it('hides the toggle for a session that cannot show the chat view', () => {
const { app } = loadModule();
app.onChatViewActiveSession('s1');
app.activeSessionId = 's4';
app.onChatViewActiveSession('s4');
expect(app._chatView.toggle.hidden).toBe(true);
expect(app._chatView.root.hidden).toBe(true);
});
it('draws the conversation without keep-warm turns, folds long prompts and appends new messages', async () => {
const long = Array.from({ length: 20 }, (_, i) => `log ${i}`).join('\n');
const first: Msg[] = [
{ role: 'user', text: long, turn: 1 },
{ role: 'assistant', text: 'Looked at it.', turn: 1 },
{ role: 'assistant', text: 'Checked the tests too.', turn: 1 },
{ role: 'user', text: 'keep-warm nudge', turn: 2, keepAlive: true },
{ role: 'assistant', text: 'keep-warm reply', turn: 2, keepAlive: true },
];
const second: Msg[] = [...first, { role: 'user', text: 'Next', turn: 3 }];
const { app } = loadModule({ messages: [first, second] });
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await settle();
const nodes = Array.from(app._chatView.thread.children) as HTMLElement[];
expect(nodes).toHaveLength(3);
expect(nodes[0].querySelector('.chat-view-show-all')!.textContent).toBe('Show all (20 lines)');
expect(nodes[0].textContent).not.toContain('log 10');
expect(app._chatView.thread.textContent).not.toContain('keep-warm');
// One badge per speaker per turn: Claude's second message in the turn continues the first.
expect(nodes[1].classList.contains('rv-msg-cont')).toBe(false);
expect(nodes[2].classList.contains('rv-msg-cont')).toBe(true);
await app._chatViewFetch();
const after = Array.from(app._chatView.thread.children);
expect(after).toHaveLength(4);
expect(after[0]).toBe(nodes[0]); // appended, not redrawn
(nodes[0].querySelector('.chat-view-show-all') as HTMLButtonElement).click();
expect(app._chatView.thread.children[0].textContent).toContain('log 19');
});
it('puts the Working line right under the last message, inside the scrolling list', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const view = app._chatView as unknown as { status: HTMLElement; thread: HTMLElement; scroller: HTMLElement };
expect(view.status.parentElement).toBe(view.scroller);
expect(view.thread.nextElementSibling).toBe(view.status);
});
it('counts a turn already running when the page loaded from the last Enter, not from the page load', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-24T12:00:00Z'));
const { app } = loadModule();
app.sessions.set('s1', {
id: 's1',
mode: 'claude',
status: 'busy',
workingDir: '/work',
lastSubmitAt: Date.now() - 73_000,
});
app.setChatViewMode('s1', 'chat');
const a = app as unknown as {
onChatViewTurnEvent: (id: string, idle: boolean) => void;
_chatView: { statusText: HTMLElement };
};
// A working event for a session this page never saw idle says nothing about the turn's start.
a.onChatViewTurnEvent('s1', false);
app.onChatViewActiveSession('s1');
expect(a._chatView.statusText.textContent).toBe('Working · 1m 13s');
// Stop the status line's ticking before the real clock comes back.
app.setChatViewMode('s1', 'terminal');
vi.useRealTimers();
});
it('counts a turn this page saw start from its session:working event', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-24T12:00:00Z'));
try {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
app.onChatViewTurnEvent('s1', true);
vi.setSystemTime(Date.now() + 30_000);
const session = app.sessions.get('s1')!;
session.status = 'busy';
// An older Enter, which must not be the start of the turn the page saw begin.
session.lastSubmitAt = Date.now() - 60_000;
app.onChatViewTurnEvent('s1', false);
vi.setSystemTime(Date.now() + 5_000);
app._chatViewRenderStatus();
expect(app._chatView.statusText.textContent).toBe('Working · 5s');
app.setChatViewMode('s1', 'terminal');
} finally {
vi.useRealTimers();
}
});
it("shows no status line during Codeman's keep-alive turn", () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const session = app.sessions.get('s1')!;
session.status = 'busy';
app.onChatViewTurnEvent('s1', false, true);
expect(app._chatView.status.hidden).toBe(true);
session.status = 'idle';
app.onChatViewTurnEvent('s1', true, true);
// A real turn shows it again.
session.status = 'busy';
app.onChatViewTurnEvent('s1', false);
expect(app._chatView.status.hidden).toBe(false);
session.status = 'idle';
app.onChatViewTurnEvent('s1', true);
});
/** A Chat session that is busy, on a device that is touch or not, with app.js's focus rule. */
function loadForFocus(touch: boolean) {
const loaded = loadModule();
const { win, app } = loaded;
// The rule the app applies to a tab switch (app.js), run as written.
const appJs = read('app.js');
const method = appJs.match(/\n {2}_shouldFocusTerminalForTabSwitch\(\) \{[\s\S]*?\n {2}\}\n/)![0];
Object.assign(app, win.eval(`({${method}})`) as object);
win.MobileDetection = {
isHandheldDevice: () => false,
getDeviceType: () => (touch ? 'tablet' : 'desktop'),
isTouchDevice: () => touch,
};
win.KeyboardHandler = { keyboardVisible: false };
app.sessions.get('s1')!.status = 'busy';
app.setChatViewMode('s1', 'terminal');
return loaded;
}
const nextFrame = (win: Window) => new Promise<void>((r) => win.requestAnimationFrame(() => r()));
it('follows the tab-switch focus rule on a touch device: no focus on a switch to Chat', async () => {
const { win, app } = loadForFocus(true);
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).not.toBe(app._chatView.scroller);
});
it('moves a focus left in the terminal to the conversation on a switch to Chat, on a touch device', async () => {
const { win, app } = loadForFocus(true);
const inner = win.document.createElement('textarea');
win.document.getElementById('terminalContainer')!.appendChild(inner);
inner.focus();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('moves a focus left on the CJK input field to the conversation on a switch to Chat, on a touch device', async () => {
const { win, app } = loadForFocus(true);
(win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus();
expect(win.document.activeElement?.id).toBe('cjkInput');
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('focuses the conversation on a desktop, on a switch to Chat', async () => {
const { win, app } = loadForFocus(false);
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('unfolds a long prompt in place, with the badge it was drawn with', () => {
const { win, app } = loadModule();
const a = app as unknown as {
_buildResponseViewerMessage: (t: string, r: string, l: string, m?: { continuation?: boolean }) => HTMLElement;
_chatViewBuildMessage: (m: Msg, label: string, continuation: boolean) => HTMLElement;
};
// As the real builder does: a prompt that is not a continuation carries its "You" badge.
const build = a._buildResponseViewerMessage;
a._buildResponseViewerMessage = (text, role, label, meta) => {
const el = build(text, role, label, meta);
if (!meta?.continuation) {
const badge = win.document.createElement('div');
badge.className = 'rv-role rv-role-user';
el.prepend(badge);
}
return el;
};
const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
const el = a._chatViewBuildMessage({ role: 'user', text: long, turn: 1 }, 'Claude', true);
expect(el.classList.contains('rv-msg-cont')).toBe(true);
(el.querySelector('.chat-view-show-all') as HTMLButtonElement).click();
expect(el.querySelector(':scope > .rv-role')).toBeNull();
expect(el.classList.contains('rv-msg-cont')).toBe(true);
expect(el.querySelector('.chat-view-show-all')).toBeNull();
expect(el.textContent).toContain('line 29');
});
it('shows the waiting notice while a permission prompt or question is pending', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(app._chatView.dialog.hidden).toBe(true);
app.pendingHooks.set('s1', new Set(['elicitation_dialog']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(false);
app.pendingHooks.set('s1', new Set(['idle_prompt']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(true);
// Claude's AskUserQuestion, plan approval and permission dialogs arrive as permission_prompt.
app.pendingHooks.set('s1', new Set(['permission_prompt']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(false);
});
it('re-reads on transcript:update only for its own session and only while showing', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const reload = vi.spyOn(app, '_chatViewReload').mockImplementation(() => {});
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
expect(reload).toHaveBeenCalledTimes(1);
app._onChatViewTranscriptUpdate({ sessionId: 's2' });
expect(reload).toHaveBeenCalledTimes(1);
app.setChatViewMode('s1', 'terminal');
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
expect(reload).toHaveBeenCalledTimes(1);
});
it('reads nothing once hidden, even for a re-read armed while Chat showed', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await vi.advanceTimersByTimeAsync(0);
const reads = app._apiJson.mock.calls.length;
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
app.setChatViewMode('s1', 'terminal');
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson.mock.calls.length).toBe(reads);
} finally {
vi.useRealTimers();
}
});
/** A read of the conversation that stays pending until the test resolves it. */
function deferredRead() {
let resolve!: (v: { messages: Msg[] }) => void;
const promise = new Promise<{ messages: Msg[] }>((r) => (resolve = r));
return { promise, resolve };
}
it('reads once more when an update arrived while a read was in flight', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
const first = deferredRead();
app._apiJson.mockImplementationOnce(() => first.promise);
app.setChatViewMode('s1', 'chat');
expect(app._apiJson).toHaveBeenCalledTimes(1);
// The update's debounced read finds the first one still in flight.
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson).toHaveBeenCalledTimes(1);
first.resolve({ messages: [{ role: 'user', text: 'Hi', turn: 1 }] });
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson).toHaveBeenCalledTimes(2);
app.setChatViewMode('s1', 'terminal');
} finally {
vi.useRealTimers();
}
});
it('drops a read that finishes after the user switched to another session', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
const s1Read = deferredRead();
app._apiJson.mockImplementationOnce(() => s1Read.promise);
app.setChatViewMode('s1', 'chat');
app.setChatViewMode('s5', 'chat');
app.activeSessionId = 's5';
app.onChatViewActiveSession('s5');
s1Read.resolve({ messages: [{ role: 'assistant', text: 'Answer for s1 only', turn: 1 }] });
// Checked before the debounced read for s5 runs, which would redraw the thread anyway.
await vi.advanceTimersByTimeAsync(0);
expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only');
await vi.advanceTimersByTimeAsync(300);
expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only');
app.setChatViewMode('s5', 'terminal');
} finally {
vi.useRealTimers();
}
});
describe('the Alt+Shift+C chord', () => {
const chord = { altKey: true, shiftKey: true, key: 'C', code: 'KeyC' };
/** The module with app.js's shortcut matcher, run as written, and a registry holding the chord. */
function loadForChord(disabled = false) {
const loaded = loadModule();
const { win, app } = loaded;
const method = read('app.js').match(/\n {2}matchesShortcutEvent\(e, shortcut\) \{[\s\S]*?\n {2}\}\n/)![0];
Object.assign(app, win.eval(`({${method}})`) as object, {
getShortcutRegistry: () => [
{ id: 'toggle-chat-view', bindings: [{ modifiers: ['alt', 'shift'], key: 'C', code: 'KeyC' }], disabled },
],
});
return loaded;
}
it('applies to an active session that can show the chat view', () => {
const { app } = loadForChord();
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(true);
});
it('reaches the terminal in a session that cannot show the chat view', () => {
const { app } = loadForChord();
app.sessions.set('s6', { id: 's6', mode: 'shell', status: 'idle' });
app.activeSessionId = 's6';
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
it('reaches the tiles while the tile grid owns the terminal', () => {
const { app } = loadForChord();
(app as unknown as { _tilesOwnTerminal: () => boolean })._tilesOwnTerminal = () => true;
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
it('needs a modifier', () => {
const { app } = loadForChord();
expect(app.shouldToggleChatViewFromShortcut({ key: 'C', code: 'KeyC' })).toBe(false);
});
it('does nothing when the user disabled the shortcut', () => {
const { app } = loadForChord(true);
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
});
it('stays hidden while the tile grid owns the terminal, so the keyboard bar shows for the tiles', () => {
const { win, app } = loadModule();
const a = app as unknown as {
_tileGrid?: { open: boolean };
_tilesOwnTerminal: () => boolean;
_chatViewSync: () => void;
};
a._tilesOwnTerminal = () => !!a._tileGrid?.open;
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
a._tileGrid = { open: true };
a._chatViewSync();
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
expect(app._chatView.root.hidden).toBe(true);
a._tileGrid = { open: false };
a._chatViewSync();
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
expect(app._chatView.root.hidden).toBe(false);
});
});
describe('chat view wiring', () => {
it("swallows the toggle chord in the xterm key handler and in Pane B's", () => {
const terminalUi = read('terminal-ui.js');
expect(terminalUi).toMatch(/shouldToggleChatViewFromShortcut\?\.\(ev\)\)\s*\{\s*return false;/);
const tile = read('terminal-tile.js');
expect(tile).toContain(
"if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;"
);
});
it('re-reads the conversation after an SSE reconnect onto the session on screen', () => {
const app = read('app.js');
expect(app).toMatch(
/void this\._onSessionNeedsRefresh\(\{ id: restoreId \}\);[\s\S]{0,300}?this\._chatViewReload\?\.\(\{ immediate: true \}\);/
);
});
it('hides the chat view when the home screen shows', () => {
const terminalUi = read('terminal-ui.js');
expect(terminalUi).toMatch(/\n {2}showWelcome\(\) \{\n {4}this\._chatViewHide\?\.\(\);/);
});
it('keeps the chat view layers under the narrow-width sidebar drawer', () => {
// The drawer (z-index 12, mobile.css) is a sibling of .terminal-wrap: the chat view's 20 and 21
// must stay inside the terminal area's own stacking context.
const css = read('styles.css');
expect(css).toMatch(/\n\.terminal-wrap \{[^}]*isolation: isolate;[^}]*\}/);
});
it('binds Alt+Shift+C to the toggle in the shortcut registry', () => {
const app = read('app.js');
expect(app).toMatch(
/id: 'toggle-chat-view',[\s\S]*?modifiers: \['alt', 'shift'\], key: 'C', code: 'KeyC'[\s\S]*?action: 'toggleChatView'/
);
expect(app).toContain('toggleChatView: () => this.toggleChatView?.()');
});
it('keeps chatViewDefault per device and out of the server PUT', () => {
const settings = read('settings-ui.js');
expect(settings).toMatch(/'showEditHistory', 'chatViewDefault',/);
expect(settings).toContain('chatViewDefault: _cvd,');
const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8');
expect(schemas).not.toContain('chatViewDefault');
});
it('keeps showChatViewSwitch per device, out of the server PUT, and on when absent', () => {
const settings = read('settings-ui.js');
expect(settings).toMatch(/'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',/);
expect(settings).toContain('showChatViewSwitch: _scvs,');
expect(settings).toContain(
"document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch !== false;"
);
const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8');
expect(schemas).not.toContain('showChatViewSwitch');
// A settings save re-syncs the chat view, so the switch follows the new value at once.
expect(settings).toMatch(/this\._chatViewSync\?\.\(\);/);
const html = read('index.html');
expect(html).toContain('id="appSettingsShowChatViewSwitch"');
});
it('passes the keep-alive flag of session:working and session:idle to the chat view', () => {
const app = read('app.js');
expect(app).toContain('this.onChatViewTurnEvent?.(data.id, true, data.keepAlive);');
expect(app).toContain('this.onChatViewTurnEvent?.(data.id, false, data.keepAlive);');
});
it('hides the CJK input field on a touch device while Chat shows', () => {
// The field is fixed over the bottom of the chat view there, and its text goes into the pane.
const css = read('styles.css');
expect(css).toMatch(
/\nbody\.chat-view-showing\.touch-device #cjkInput\.cjk-input-visible \{\s*display: none !important;\s*\}/
);
});
it("starts the chat layer and its switch below Pane A's split header", () => {
const css = read('styles.css');
expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view \{\s*top: 28px;\s*\}/);
expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view-toggle \{\s*top: 36px;\s*\}/);
});
it('centres the empty notice over the Response Viewer paragraph margin', () => {
// The notice is a <p> directly inside .response-viewer-body, whose `> p` margin rule
// outranks `.chat-view-empty` alone and left it against the window's left edge.
const css = read('styles.css');
expect(css).toMatch(/\.chat-view-scroll > \.chat-view-empty \{\s*margin-left: auto;\s*margin-right: auto;\s*\}/);
});
it('loads chat-view.js after local-model-ui.js', () => {
const html = read('index.html');
expect(html.indexOf('src="chat-view.js"')).toBeGreaterThan(html.indexOf('src="local-model-ui.js"'));
});
});
@@ -0,0 +1,51 @@
/**
* @fileoverview A Docker session's reported transcript path is watched on the host
* (src/web/claude-conversation-report.ts).
*
* Claude in a Docker case runs with `HOME=/home/agent`, so a hook or the statusline reports a
* transcript under `/home/agent/.claude/projects`, which does not exist on the host. The case
* mounts the host's `~/.claude/projects` there, so the watcher must follow the host's copy.
*/
import { homedir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { hostTranscriptPath, noteClaudeConversationReport } from '../src/web/claude-conversation-report.js';
import { CONTAINER_CLAUDE_DIR } from '../src/docker-hosts.js';
import type { Session } from '../src/session.js';
const docker = { docker: { containerName: 'codeman-case' } } as unknown as Pick<Session, 'docker'>;
const reported = `${CONTAINER_CLAUDE_DIR}/projects/-workspace-app/abc.jsonl`;
describe('hostTranscriptPath', () => {
it("maps a Docker session's container path into the host's projects folder", () => {
expect(hostTranscriptPath(docker, reported)).toBe(
join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl')
);
});
it('leaves a local session, a path outside the projects folder and a path with `..` as reported', () => {
expect(hostTranscriptPath({ docker: undefined }, reported)).toBe(reported);
expect(hostTranscriptPath(undefined, reported)).toBe(reported);
expect(hostTranscriptPath(docker, '/home/agent/elsewhere/abc.jsonl')).toBe('/home/agent/elsewhere/abc.jsonl');
const escape = `${CONTAINER_CLAUDE_DIR}/projects/../../.ssh/id_rsa`;
expect(hostTranscriptPath(docker, escape)).toBe(escape);
});
});
describe('noteClaudeConversationReport', () => {
it("starts a Docker session's watcher on the host path", () => {
const startTranscriptWatcher = vi.fn();
const session = { ...docker, claudeSessionChain: [], adoptClaudeSessionId: vi.fn() };
const ctx = {
sessions: new Map([['s1', session]]),
startTranscriptWatcher,
persistSessionState: vi.fn(),
} as unknown as Parameters<typeof noteClaudeConversationReport>[0];
noteClaudeConversationReport(ctx, 's1', { transcript_path: reported });
expect(startTranscriptWatcher).toHaveBeenCalledWith(
's1',
join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl')
);
});
});
+216
View File
@@ -0,0 +1,216 @@
/**
* @fileoverview The incremental Claude transcript reader behind `last-response`
* (src/web/claude-response-transcript.ts).
*
* Every read must answer what a parse of the whole file answers, whatever the file did between
* reads: grew, grew by half a line, shrank, was replaced, or was rewritten in place. A read must
* also parse only the bytes appended since the last one, and overlapping reads of one file must
* share their passes.
*/
import { appendFileSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import fs from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
ClaudeResponseParser,
ClaudeTranscriptReader,
parseClaudeResponseTranscript,
} from '../src/web/claude-response-transcript.js';
import { KEEP_WARM_NUDGE } from '../src/prompt-cache-keepwarm.js';
const user = (text: string, extra: Record<string, unknown> = {}) =>
JSON.stringify({ type: 'user', timestamp: '2026-11-27T10:00:00Z', message: { content: text }, ...extra });
const assistant = (text: string, ts = '2026-11-27T10:00:01Z') =>
JSON.stringify({ type: 'assistant', timestamp: ts, message: { content: [{ type: 'text', text }] } });
const toolUse = () =>
JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id: 't', name: 'Bash', input: {} }] } });
const toolResult = () =>
JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', content: 'ok' }] } });
const queued = (prompt: string) =>
JSON.stringify({
type: 'attachment',
attachment: { type: 'queued_command', prompt, commandMode: 'prompt', origin: { kind: 'human' } },
});
/** A conversation that exercises turns, queued prompts, replays, keep-warm turns and tool rows. */
const LINES = [
user('first prompt'),
user('first prompt'), // a replayed row, collapsed
toolUse(),
toolResult(),
assistant('first answer'),
assistant('first answer'), // a replayed snapshot, collapsed
user('second prompt'),
queued('queued while working'),
assistant('second answer — with ünïcödé and 漢字 to cut mid-character'),
JSON.stringify({ type: 'user', isSidechain: true, message: { content: 'sidechain' } }),
user(KEEP_WARM_NUDGE),
assistant('ok'),
'{ not json',
user('<system-reminder>synthetic</system-reminder>'),
user('third prompt'),
assistant('third answer'),
];
describe('ClaudeResponseParser', () => {
it('answers the same whether fed at once or line by line, and its answers never change later', () => {
const whole = parseClaudeResponseTranscript(LINES.join('\n') + '\n');
const parser = new ClaudeResponseParser();
const early = (() => {
for (const line of LINES.slice(0, 5)) parser.feedLine(line);
return parser.result();
})();
for (const line of LINES.slice(5)) parser.feedLine(line);
expect(parser.result()).toEqual(whole);
expect(early.messages).toHaveLength(2);
expect(whole.text).toBe('third answer');
expect(whole.messages.map((m) => m.text)).toEqual([
'first prompt',
'first answer',
'second prompt',
'queued while working',
'second answer — with ünïcödé and 漢字 to cut mid-character',
KEEP_WARM_NUDGE,
'ok',
'third prompt',
'third answer',
]);
expect(whole.messages.filter((m) => m.keepAlive).map((m) => m.text)).toEqual([KEEP_WARM_NUDGE, 'ok']);
});
it('leaves the original untouched when a clone parses more', () => {
const parser = new ClaudeResponseParser();
parser.feedLine(user('p'));
const copy = parser.clone();
copy.feedLine(assistant('a'));
expect(parser.result().messages).toHaveLength(1);
expect(copy.result().messages).toHaveLength(2);
});
});
describe('ClaudeTranscriptReader', () => {
let dir: string;
let file: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'claude-transcript-reader-'));
file = join(dir, 'conversation.jsonl');
});
afterEach(() => {
vi.restoreAllMocks();
rmSync(dir, { recursive: true, force: true });
});
const whole = () => parseClaudeResponseTranscript(LINES.join('\n') + '\n');
it('answers a parse of the whole file after each append, at any byte boundary', async () => {
const bytes = Buffer.from(LINES.join('\n') + '\n', 'utf8');
// A tiny chunk size makes reads cut lines and multi-byte characters.
const reader = new ClaudeTranscriptReader({ chunkBytes: 7 });
writeFileSync(file, '');
for (let cut = 0; cut < bytes.length; ) {
const next = Math.min(bytes.length, cut + 1 + ((cut * 37) % 53));
appendFileSync(file, bytes.subarray(cut, next));
cut = next;
const expected = parseClaudeResponseTranscript(bytes.subarray(0, cut).toString('utf8'));
// A cut inside a multi-byte character leaves a line that is not JSON either way.
expect(await reader.read(file)).toEqual(expected);
}
expect(await reader.read(file)).toEqual(whole());
});
it('parses only the bytes appended since the last read', async () => {
writeFileSync(file, LINES.slice(0, 8).join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const expected = whole();
const feed = vi.spyOn(ClaudeResponseParser.prototype, 'feedLine');
appendFileSync(file, LINES.slice(8).join('\n') + '\n');
expect(await reader.read(file)).toEqual(expected);
// Only the appended lines; the empty string after the last newline is never fed.
expect(feed.mock.calls.map(([line]) => line)).toEqual(LINES.slice(8));
feed.mockClear();
expect(await reader.read(file)).toEqual(expected);
expect(feed).not.toHaveBeenCalled();
});
it('answers a last line that has no newline yet, and parses it once its newline arrives', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}`);
const reader = new ClaudeTranscriptReader();
expect((await reader.read(file)).text).toBe('a');
appendFileSync(file, `\n${assistant('b')}\n`);
expect(await reader.read(file)).toEqual(
parseClaudeResponseTranscript(`${user('p')}\n${assistant('a')}\n${assistant('b')}\n`)
);
});
it('starts again from byte 0 when the file shrank', async () => {
writeFileSync(file, LINES.join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
await reader.read(file);
writeFileSync(file, `${user('new')}\n${assistant('fresh')}\n`);
expect(await reader.read(file)).toEqual(parseClaudeResponseTranscript(`${user('new')}\n${assistant('fresh')}\n`));
});
it('starts again from byte 0 when another file replaced it', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}\n`);
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const replacement = join(dir, 'replacement.jsonl');
writeFileSync(replacement, LINES.join('\n') + '\n');
renameSync(replacement, file);
expect(await reader.read(file)).toEqual(whole());
});
it('starts again from byte 0 when the file was rewritten in place to a larger size', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}\n`);
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const handle = await fs.open(file, 'r+');
await handle.truncate(0);
await handle.write(LINES.join('\n') + '\n', 0);
await handle.close();
expect(await reader.read(file)).toEqual(whole());
});
it('shares one pass between reads asked for while a read runs', async () => {
writeFileSync(file, LINES.join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
const open = vi.spyOn(fs, 'open');
const results = await Promise.all([reader.read(file), reader.read(file), reader.read(file), reader.read(file)]);
for (const result of results) expect(result).toEqual(whole());
// The first read, then one pass for every read that waited on it.
expect(open).toHaveBeenCalledTimes(2);
});
it('sees bytes appended while an earlier read ran', async () => {
writeFileSync(file, `${user('p')}\n`);
const reader = new ClaudeTranscriptReader();
const first = reader.read(file);
appendFileSync(file, `${assistant('late')}\n`);
const second = reader.read(file);
await first;
expect((await second).text).toBe('late');
});
it('rejects for a missing file, and reads it once it exists', async () => {
const reader = new ClaudeTranscriptReader();
await expect(reader.read(file)).rejects.toThrow();
writeFileSync(file, `${assistant('there')}\n`);
expect((await reader.read(file)).text).toBe('there');
});
it('awaits between chunks, so a large first read does not hold the event loop in one step', async () => {
const big = Array.from({ length: 4000 }, (_, i) => `${user(`p${i}`)}\n${assistant(`a${i}`)}`).join('\n') + '\n';
writeFileSync(file, big);
const reader = new ClaudeTranscriptReader({ chunkBytes: 16 * 1024 });
let ticks = 0;
const timer = setInterval(() => ticks++, 0);
const result = await reader.read(file);
clearInterval(timer);
expect(result).toEqual(parseClaudeResponseTranscript(big));
expect(ticks).toBeGreaterThan(0);
});
});
@@ -41,6 +41,9 @@ const SCANNED_FILES = [
// The harness a local model is paired with arrives as a label in the payload
// (`Candidate.cliLabel`); the card names no CLI and compares no id.
'local-model-ui.js',
// Which sessions can show the chat view comes from the injected transcript capability
// (window.__codemanChatViewModes), never from an id here.
'chat-view.js',
];
/**
+94
View File
@@ -0,0 +1,94 @@
/**
* @fileoverview KeyedThrottle (src/utils/keyed-throttle.ts), the per-key throttle behind the
* server's `transcript:update` broadcast.
*
* Pinned: the first call sends at once, a burst inside the interval collapses into one trailing
* send at the interval's end, the trailing send runs the newest send it was given, a call after
* the interval sends at once, keys are independent, and cancelKey()/dispose() drop a pending
* trailing send.
*
* Port: N/A
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { KeyedThrottle } from '../src/utils/index.js';
describe('KeyedThrottle', () => {
let throttle: KeyedThrottle;
let sends: Array<{ key: string; at: number }>;
const fire = (key: string) => throttle.fire(key, () => sends.push({ key, at: Date.now() }));
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(10_000);
throttle = new KeyedThrottle(750);
sends = [];
});
afterEach(() => {
throttle.dispose();
vi.useRealTimers();
});
it('sends the first call at once', () => {
fire('a');
expect(sends).toEqual([{ key: 'a', at: 10_000 }]);
});
it('collapses a burst into one trailing send at the end of the interval', () => {
fire('a');
vi.advanceTimersByTime(100);
fire('a');
fire('a');
vi.advanceTimersByTime(300);
fire('a');
expect(sends).toHaveLength(1);
vi.advanceTimersByTime(349);
expect(sends).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(sends).toEqual([
{ key: 'a', at: 10_000 },
{ key: 'a', at: 10_750 },
]);
vi.advanceTimersByTime(5000);
expect(sends).toHaveLength(2);
});
it('runs the newest send it was given when the trailing send fires', () => {
const labels: string[] = [];
throttle.fire('a', () => labels.push('first'));
throttle.fire('a', () => labels.push('second'));
throttle.fire('a', () => labels.push('third'));
vi.advanceTimersByTime(750);
expect(labels).toEqual(['first', 'third']);
});
it('sends at once again once the interval has passed', () => {
fire('a');
vi.advanceTimersByTime(800);
fire('a');
expect(sends.map((s) => s.at)).toEqual([10_000, 10_800]);
});
it('throttles each key on its own', () => {
fire('a');
fire('b');
expect(sends.map((s) => s.key)).toEqual(['a', 'b']);
});
it('drops a pending trailing send on cancelKey() and dispose()', () => {
fire('a');
fire('a');
fire('b');
fire('b');
throttle.cancelKey('a');
vi.advanceTimersByTime(1000);
expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b']);
fire('c');
fire('c');
throttle.dispose();
vi.advanceTimersByTime(1000);
expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b', 'c']);
});
});
+10
View File
@@ -263,6 +263,16 @@ describe('WebServer.renderIndexHtml', () => {
}
});
it('injects the chat view modes from the transcript capability, in solo windows too', async () => {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer();
const html = await render(server, solo);
const match = html.match(/window\.__codemanChatViewModes=(\[[^<]*\]);/);
expect(match).not.toBeNull();
expect(JSON.parse(match![1])).toEqual(['claude']);
}
});
it('escapes the solo id so it cannot break out of the inline <script>', async () => {
const { server } = makeServer({});
const html = await render(server, 'a</script><b>');
@@ -8,13 +8,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import fsPromises from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { KEEP_WARM_NUDGE } from '../../src/prompt-cache-keepwarm.js';
interface LocalHarness {
app: FastifyInstance;
@@ -239,6 +241,261 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
]);
});
it('starts a transcript watcher for the chat view when the session has none, and only then', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// The brief view and agent pollers read without starting anything.
await getLastResponse(sessionId, false);
expect(start).not.toHaveBeenCalled();
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
expect(start.mock.calls[0][0]).toBe(sessionId);
expect(String(start.mock.calls[0][1])).toMatch(new RegExp(`${sessionId}\\.jsonl$`));
// A watcher already running (a hook reported its path) is left alone.
current.mockReturnValue('/some/path.jsonl');
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
});
it('moves a watcher it started itself to the new file after /clear', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
const fileA = String(start.mock.calls[0][1]);
current.mockReturnValue(fileA);
// The same file again: nothing to move.
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// A /clear starts a new conversation file, and no hook moves the watcher onto it.
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000001';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(2);
expect(start.mock.calls[1][0]).toBe(sessionId);
expect(String(start.mock.calls[1][1])).toMatch(new RegExp(`${clearedId}\\.jsonl$`));
});
it('never moves a watcher whose path a hook set', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// A hook started the watcher on a path this read never recorded.
current.mockReturnValue('/hook/reported.jsonl');
await getLastResponse(sessionId, true);
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000002';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).not.toHaveBeenCalled();
});
it('leaves a watcher it started alone once a hook moved it', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// The read starts the watcher on transcript A.
current.mockReturnValue(null);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// A hook then moves it to B, and a /clear leaves the conversation in C.
current.mockReturnValue('/hook/moved.jsonl');
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000003';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// The read forgot its record, so a later read leaves the hook's watcher alone too.
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// Even once the watcher is back on the path the read first recorded, and the conversation
// moved on to a new file: a read that still held its record would move the watcher there.
current.mockReturnValue(String(start.mock.calls[0][1]));
const laterId = 'b0c1d2e3-0000-4000-8000-000000000004';
session.claudeSessionId = laterId;
writeTranscript(laterId, [userEntry('Later'), assistantEntry('Later still.', '2026-07-21T00:00:03Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
});
it('starts no transcript watcher for a session removed while the read was in flight', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
// A delete or detach between the route's lookup and the transcript scan leaves the
// session out of the server's map; nothing would ever stop a watcher started for it.
harness.ctx.sessions.delete(sessionId);
const result = await harness.ctx.lastResponseFor!(session as never, 'full');
expect(start).not.toHaveBeenCalled();
expect((result as { messages?: unknown[] }).messages?.length).toBeGreaterThan(0);
});
it('remembers where a transcript was found, and scans again once the file moved', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const projectsDir = join(testHome, '.claude', 'projects');
const readdir = vi.spyOn(fsPromises, 'readdir');
const projectScans = () => readdir.mock.calls.filter((call) => String(call[0]) === projectsDir).length;
try {
await getLastResponse(sessionId, true);
expect(projectScans()).toBe(1);
const second = await getLastResponse(sessionId, true);
expect(projectScans()).toBe(1);
expect(second.body.data.text).toBe('Hello.');
// The file moves to another project folder: the remembered path fails, the scan finds it.
const movedDir = join(projectsDir, '-elsewhere');
mkdirSync(movedDir, { recursive: true });
renameSync(join(projectsDir, '-workspace', `${sessionId}.jsonl`), join(movedDir, `${sessionId}.jsonl`));
const third = await getLastResponse(sessionId, true);
expect(projectScans()).toBe(2);
expect(third.body.data.text).toBe('Hello.');
} finally {
readdir.mockRestore();
}
});
it("marks Codeman's keep-warm turns so the chat view can leave them out", async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('Fix the bug'),
assistantEntry('Fixed.', '2026-07-21T00:00:01Z'),
userEntry(KEEP_WARM_NUDGE),
assistantEntry('ok', '2026-07-21T00:00:02Z'),
userEntry('Thanks'),
assistantEntry('You are welcome.', '2026-07-21T00:00:03Z'),
]);
const { body } = await getLastResponse(sessionId, true);
expect(
body.data.messages.map((message: { role: string; text: string; keepAlive?: boolean }) => [
message.role,
message.text,
message.keepAlive === true,
])
).toEqual([
['user', 'Fix the bug', false],
['assistant', 'Fixed.', false],
['user', KEEP_WARM_NUDGE, true],
['assistant', 'ok', true],
['user', 'Thanks', false],
['assistant', 'You are welcome.', false],
]);
});
it('keeps a prompt the user queued during a keep-warm turn, and the answer to it', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry(KEEP_WARM_NUDGE),
queuedEntry('Also run the tests', '2026-07-21T00:00:01Z'),
assistantEntry('ok. Tests pass.', '2026-07-21T00:00:02Z'),
]);
const { body } = await getLastResponse(sessionId, true);
expect(
body.data.messages.map((message: { text: string; keepAlive?: boolean }) => [
message.text,
message.keepAlive === true,
])
).toEqual([
[KEEP_WARM_NUDGE, true],
['Also run the tests', false],
['ok. Tests pass.', false],
]);
});
it('opens a keep-warm turn of its own after a turn that ended without assistant text', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('Fix the bug'),
{ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'tool-1' }] } },
userEntry(KEEP_WARM_NUDGE),
assistantEntry('ok', '2026-07-21T00:00:02Z'),
]);
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; text: string; turn: number; keepAlive?: boolean }>;
const prompt = messages.find((message) => message.text === 'Fix the bug');
const reply = messages.find((message) => message.text === 'ok');
expect(prompt?.keepAlive).toBeUndefined();
expect(reply?.keepAlive).toBe(true);
expect(reply?.turn).not.toBe(prompt?.turn);
});
/**
* A prompt typed while Claude is working is absorbed mid-turn and recorded
* ONLY as an attachment row — 160 of the 347 user cards across a real
@@ -727,7 +984,7 @@ describe('GET /api/sessions/:id/last-response (relocated Claude config folder, #
expect(pane.adoptClaudeSessionId).toHaveBeenCalledWith('after-clear');
});
it("keeps a Docker session off its override, which names a folder inside the container", async () => {
it('keeps a Docker session off its override, which names a folder inside the container', async () => {
const home = join(testHome, '.claude');
writeTranscript(home, 'conversation-a', 'what the host folder holds');
writeTranscript(relocated, 'conversation-a', 'a host folder that only shares the path');
+126
View File
@@ -13,6 +13,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerStatusTelemetryRoutes } from '../../src/web/routes/status-telemetry-routes.js';
import { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js';
import { SessionPromptCache, SessionStatusTelemetry } from '../../src/web/sse-events.js';
import { Session } from '../../src/session.js';
@@ -81,6 +82,131 @@ describe('POST /api/status-telemetry', () => {
});
});
describe('the conversation the pane runs', () => {
// As measured on Claude Code 2.1.332: the statusline runs about a second after a `/clear`,
// with the new conversation's id and transcript path, before any hook reports them.
const cleared = {
session_id: 'conv-2',
transcript_path: '/home/u/.claude/projects/-w/conv-2.jsonl',
};
it('follows the new conversation the statusline reports after /clear', async () => {
const res = await post({ sessionId: SID, data: cleared });
expect(res.statusCode).toBe(200);
expect(h.ctx._session.claudeSessionId).toBe('conv-2');
expect(h.ctx._session.claudeSessionIdIsFirstHand).toBe(true);
expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path);
expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1);
// The next render reports the same conversation: nothing is persisted again.
await post({ sessionId: SID, data: cleared });
expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1);
});
/**
* The exporter backgrounds its POST when it wraps the user's own statusline, so a report sent
* before the `/clear` can land after the one sent after it. That old report must not move the
* session back to the conversation the `/clear` ended.
*/
it('ignores a delayed report that names an earlier conversation', async () => {
const report = (id: string) => ({
sessionId: SID,
data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` },
});
await post(report('conv-1'));
await post(report('conv-2'));
await post(report('conv-1')); // the delayed old POST
const session = h.ctx._session;
expect(session.claudeSessionId).toBe('conv-2');
expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-2');
expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-2').data.transcript_path);
});
/**
* With workspace hooks off no hook ever follows a `/resume`, so a statusline report that names
* an earlier conversation must move the session back once the last move is old enough that no
* delayed POST from before it can still arrive.
*/
it('follows a /resume back to an earlier conversation once the last move is more than 10 s old', async () => {
const report = (id: string) => ({
sessionId: SID,
data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` },
});
// Only the clock is faked: Fastify's inject still needs real timers.
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(new Date('2026-11-26T10:00:00Z'));
await post(report('conv-1'));
await post(report('conv-2'));
vi.setSystemTime(new Date('2026-11-26T10:00:11Z'));
await post(report('conv-1')); // the /resume back
} finally {
vi.useRealTimers();
}
const session = h.ctx._session;
expect(session.claudeSessionId).toBe('conv-1');
expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-1');
expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-1').data.transcript_path);
});
/**
* A report naming the session's current conversation is never refused, so after a server
* restart the statusline still starts the transcript watcher for it.
*/
it('starts the transcript watcher for a report that names the current conversation', async () => {
await post({ sessionId: SID, data: cleared });
h.ctx.startTranscriptWatcher.mockClear();
await post({ sessionId: SID, data: cleared });
expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path);
});
/**
* The run summary records a `prompt_submitted` only for a `/clear` successor's first prompt.
* The statusline adopts the successor before that prompt's hook, so the hook must still learn
* that the conversation moved.
*/
it("records the /clear successor's first prompt in the run summary after the statusline moved it", async () => {
const both = await createRouteTestHarness(
(app, ctx) => {
registerStatusTelemetryRoutes(app, ctx);
registerHookEventRoutes(app, ctx);
},
{ sessionId: SID }
);
const tracker = { recordHookEvent: vi.fn() };
both.ctx.runSummaryTrackers.set(SID, tracker as never);
const prompt = () =>
both.app.inject({
method: 'POST',
url: '/api/hook-event',
payload: { event: 'prompt_submitted', sessionId: SID, data: { session_id: 'conv-2' } },
});
await both.app.inject({
method: 'POST',
url: '/api/status-telemetry',
payload: { sessionId: SID, data: cleared },
});
await prompt();
expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1);
expect(tracker.recordHookEvent).toHaveBeenCalledWith('prompt_submitted', expect.any(Object));
await prompt(); // the next prompt in the same conversation
expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1);
});
it('refuses a transcript path with shell syntax in it', async () => {
await post({ sessionId: SID, data: { ...cleared, transcript_path: '/tmp/$(id).jsonl' } });
expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled();
});
it('takes no report from a CLI without a statusline exporter', async () => {
h.ctx._session.mode = 'shell';
await post({ sessionId: SID, data: cleared });
expect(h.ctx._session.claudeSessionId).not.toBe('conv-2');
expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled();
});
});
it('does not broadcast for an unknown session; returns an EMPTY footer, never a brand word', async () => {
const res = await post({ sessionId: 'does-not-exist', data: REAL });
expect(res.statusCode).toBe(200);
+2
View File
@@ -118,6 +118,8 @@ describe('WebServer index.html <title> templating (#82)', () => {
.replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '')
// And the keyboard-hold mode list, built the same way.
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '')
// And the chat view mode list, built the same way.
.replace(/<script>window\.__codemanChatViewModes=\[.*?\];<\/script>\n/, '')
// And the wheel-forwarding rules: an object keyed by run mode, always injected.
.replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, '');
const beforeTitle = rawTemplate.split('<title>Codeman</title>')[0];
+14
View File
@@ -199,6 +199,20 @@ describe('parking the main terminal', () => {
app.closeTileGrid({ reselect: false });
expect(app.selectSession).not.toHaveBeenCalled();
});
it('opening and closing re-sync the chat view, so it hides for the tiles and comes back after', () => {
const app = makeApp();
// What the grid reported when the chat view was told, one entry per call.
const owned: boolean[] = [];
app._chatViewSync = vi.fn(() => owned.push(app._tilesOwnTerminal()));
app.openTileGrid(IDS);
expect(owned).toContain(true);
owned.length = 0;
app.closeTileGrid({ reselect: false });
expect(owned).toContain(false);
});
});
/** An app with the grid open on IDS (focus s-a), or closed, for the paired guard checks. */
+88
View File
@@ -0,0 +1,88 @@
/**
* @fileoverview The server path from a transcript watcher's `transcript:update` event to the
* throttled `transcript:update` SSE broadcast, which the chat view's live updates depend on.
*
* Pinned: the first update broadcasts at once and a second one inside the interval broadcasts
* once at its end (750 ms), stopTranscriptWatcher drops a pending trailing broadcast, and no
* watcher starts for a session that cleanup is removing.
*
* Strategy: construct WebServer on port 0 in test mode (nothing listens until start()) and call
* its private watcher methods directly.
*
* Port: N/A (no server start)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type { EventEmitter } from 'node:events';
import { WebServer } from '../src/web/server.js';
import { SseEvent } from '../src/web/sse-events.js';
interface ServerInternals {
broadcast: (event: string, data: unknown) => void;
startTranscriptWatcher: (sessionId: string, transcriptPath: string) => void;
stopTranscriptWatcher: (sessionId: string) => void;
transcriptWatchers: Map<string, EventEmitter>;
cleaningUp: Set<string>;
}
describe('transcript:update broadcast', () => {
const SID = 'transcript-update-session';
let server: ServerInternals;
let broadcast: ReturnType<typeof vi.spyOn>;
let transcriptPath: string;
const updates = () => broadcast.mock.calls.filter(([event]) => event === SseEvent.TranscriptUpdate);
beforeEach(() => {
server = new WebServer(0, false, true) as unknown as ServerInternals;
broadcast = vi.spyOn(server, 'broadcast').mockImplementation(() => {});
transcriptPath = join(mkdtempSync(join(tmpdir(), 'codeman-transcript-update-')), 'conv.jsonl');
writeFileSync(transcriptPath, '');
});
afterEach(() => {
server.stopTranscriptWatcher(SID);
vi.useRealTimers();
});
it('broadcasts the first update at once and a second one at the end of the interval', () => {
server.startTranscriptWatcher(SID, transcriptPath);
const watcher = server.transcriptWatchers.get(SID);
expect(watcher).toBeDefined();
vi.useFakeTimers();
watcher!.emit('transcript:update');
watcher!.emit('transcript:update');
expect(updates()).toHaveLength(1);
expect(updates()[0][1]).toMatchObject({ sessionId: SID });
vi.advanceTimersByTime(749);
expect(updates()).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(updates()).toHaveLength(2);
expect(updates()[1][1]).toMatchObject({ sessionId: SID });
});
it('drops a pending trailing broadcast when the watcher stops', () => {
server.startTranscriptWatcher(SID, transcriptPath);
const watcher = server.transcriptWatchers.get(SID)!;
vi.useFakeTimers();
watcher.emit('transcript:update');
watcher.emit('transcript:update');
server.stopTranscriptWatcher(SID);
vi.advanceTimersByTime(1000);
expect(updates()).toHaveLength(1);
expect(server.transcriptWatchers.has(SID)).toBe(false);
});
it('starts no watcher for a session that cleanup is removing', () => {
server.cleaningUp.add(SID);
server.startTranscriptWatcher(SID, transcriptPath);
expect(server.transcriptWatchers.has(SID)).toBe(false);
server.cleaningUp.delete(SID);
});
});