((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 off 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 === true;"
);
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 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"'));
});
});