feat(client): upgrade Terminal (.cast v2, reconnect, cleanup) & AI drawer (cancel, targetId)

This commit is contained in:
tyuXX 2026-11-28 05:17:39 +00:00
parent c003afa9df
commit 5b09c8ada1
2 changed files with 109 additions and 12 deletions

View file

@ -7,6 +7,7 @@ import {
extractErrorMessage, extractErrorMessage,
type ClientState, type ClientState,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup'; export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup';
@ -27,6 +28,7 @@ export interface OpenAiDrawerOptions {
contextText?: string; contextText?: string;
serverId?: string; serverId?: string;
targetPath?: string; targetPath?: string;
targetId?: string;
defaultDraftKind?: ClientAiDraftKind; defaultDraftKind?: ClientAiDraftKind;
onInsertTerminalText?: (cmd: string) => void; onInsertTerminalText?: (cmd: string) => void;
onApplied?: () => Promise<void> | void; onApplied?: () => Promise<void> | void;
@ -103,18 +105,29 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
const statusLine = el('p', { class: 'form-msg muted' }, ''); const statusLine = el('p', { class: 'form-msg muted' }, '');
const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send'); const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send');
const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Stop'); const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Cancel Stream');
const history: Array<{ role: 'user' | 'assistant'; content: string }> = []; const history: Array<{ role: 'user' | 'assistant'; content: string }> = [];
let activeChatId: string | null = null; let activeChatId: string | null = null;
let currentReply = ''; let currentReply = '';
let unsubWs: (() => void) | null = null; let unsubWs: (() => void) | null = null;
let unsubChannel: (() => void) | null = null;
const releaseChannel = () => {
if (unsubChannel) {
unsubChannel();
unsubChannel = null;
}
};
const cleanup = () => { const cleanup = () => {
if (activeChatId) { if (activeChatId) {
opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId }); const cid = activeChatId;
opts.wsClient.send({ type: 'ai:cancel', chatId: cid });
void apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(() => undefined);
activeChatId = null; activeChatId = null;
} }
releaseChannel();
if (unsubWs) { if (unsubWs) {
unsubWs(); unsubWs();
unsubWs = null; unsubWs = null;
@ -170,7 +183,11 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
| { valid: false; issues: Array<{ path: string; message: string }> } | { valid: false; issues: Array<{ path: string; message: string }> }
>('/api/ai/validate-draft', { >('/api/ai/validate-draft', {
method: 'POST', method: 'POST',
body: { kind: draftKindSel.value, jsonText: jsonBlock }, body: {
kind: draftKindSel.value,
jsonText: jsonBlock,
...(opts.targetId ? { targetId: opts.targetId } : {}),
},
}); });
draftOutputBox.replaceChildren(); draftOutputBox.replaceChildren();
@ -238,11 +255,14 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
if (currentReply) history.push({ role: 'assistant', content: currentReply }); if (currentReply) history.push({ role: 'assistant', content: currentReply });
appendBoundedStreamText(streamPre, '\n'); appendBoundedStreamText(streamPre, '\n');
activeChatId = null; activeChatId = null;
releaseChannel();
sendBtn.disabled = false; sendBtn.disabled = false;
stopBtn.disabled = true; stopBtn.disabled = true;
if (!frame.error) { if (!frame.error) {
statusLine.className = 'form-msg ok-text'; statusLine.className = 'form-msg ok-text';
statusLine.textContent = 'Response complete. Review any extracted draft below.'; statusLine.textContent = 'Response complete. Review any extracted draft below.';
} else {
showToast(frame.error, 'err');
} }
refreshDraftActions(); refreshDraftActions();
} }
@ -301,13 +321,17 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
}, },
}); });
activeChatId = started.chatId; activeChatId = started.chatId;
opts.wsClient.subscribe([`ai:${started.chatId}`]); releaseChannel();
unsubChannel = opts.wsClient.subscribe([`ai:${started.chatId}`]);
} catch (err) { } catch (err) {
history.pop(); history.pop();
releaseChannel();
sendBtn.disabled = false; sendBtn.disabled = false;
stopBtn.disabled = true; stopBtn.disabled = true;
const errMsg = extractErrorMessage(err);
statusLine.className = 'form-msg err-text'; statusLine.className = 'form-msg err-text';
statusLine.textContent = extractErrorMessage(err); statusLine.textContent = errMsg;
showToast(errMsg, 'err');
} }
}); });

View file

@ -3,7 +3,16 @@ import type { FitAddon } from '@xterm/addon-fit';
import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js'; import {
el,
extractErrorMessage,
fmtTime,
isAiEnabled,
registerViewCleanup,
type ClientState,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
import { import {
clearTerminalComposition, clearTerminalComposition,
@ -175,6 +184,7 @@ export async function renderTerminalView(
root.replaceChildren(); root.replaceChildren();
const q = state.routeQuery ?? {}; const q = state.routeQuery ?? {};
const targetServer = q.server ?? q.serverId;
const [sessionsRes, serversRes] = await Promise.all([ const [sessionsRes, serversRes] = await Promise.all([
apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'), apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'),
apiFetch<{ servers: ServerEntry[] }>('/api/servers'), apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
@ -185,13 +195,13 @@ export async function renderTerminalView(
if (q.session && sessions.some((s) => s.sessionId === q.session)) { if (q.session && sessions.some((s) => s.sessionId === q.session)) {
activeSessionId = q.session; activeSessionId = q.session;
} else if (q.server && q.cwd !== undefined && servers.some((s) => s.config.id === q.server)) { } else if (targetServer && q.cwd !== undefined && servers.some((s) => s.config.id === targetServer)) {
// Open-Terminal-Here shortcut if not disabled by Safe Mode // Open-Terminal-Here shortcut if not disabled by Safe Mode
if (!state.safeMode) { if (!state.safeMode) {
try { try {
const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', { const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', {
method: 'POST', method: 'POST',
body: { serverId: q.server, cwd: q.cwd, cols: 90, rows: 26 }, body: { serverId: targetServer, cwd: q.cwd, cols: 90, rows: 26 },
}); });
sessions = [created.session, ...sessions]; sessions = [created.session, ...sessions];
activeSessionId = created.session.sessionId; activeSessionId = created.session.sessionId;
@ -213,7 +223,7 @@ export async function renderTerminalView(
serverSel.append( serverSel.append(
el( el(
'option', 'option',
{ value: s.config.id, selected: q.server === s.config.id }, { value: s.config.id, selected: targetServer === s.config.id },
`${s.config.name} (${s.config.id})`, `${s.config.name} (${s.config.id})`,
), ),
); );
@ -282,6 +292,15 @@ export async function renderTerminalView(
el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn), el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn),
), ),
tabsRow, tabsRow,
...(state.safeMode
? [
el(
'p',
{ class: 'warn-text mono' },
'[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.',
),
]
: []),
msgEl, msgEl,
), ),
); );
@ -318,6 +337,40 @@ export async function renderTerminalView(
}, },
'Export ANSI', 'Export ANSI',
); );
const exportCastBtn = el(
'a',
{
href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=cast`,
class: 'btn btn-sm',
download: '',
},
'Export .cast',
);
const reconnectPtyBtn = el(
'button',
{
type: 'button',
class: 'btn btn-sm btn-primary mutating-action',
hidden: !current.exited,
},
'Reconnect Session',
);
reconnectPtyBtn.addEventListener('click', async () => {
reconnectPtyBtn.disabled = true;
try {
await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/reconnect`, {
method: 'POST',
body: {},
});
showToast('PTY session reconnected.', 'ok');
await renderTerminalView(root, state, wsClient);
} catch (err) {
msgEl.className = 'form-msg err-text';
msgEl.textContent = extractErrorMessage(err);
showToast(extractErrorMessage(err), 'err');
reconnectPtyBtn.disabled = false;
}
});
let term: Terminal | null = null; let term: Terminal | null = null;
let fitAddon: FitAddon | null = null; let fitAddon: FitAddon | null = null;
@ -490,7 +543,7 @@ export async function renderTerminalView(
{ class: 'mono muted' }, { class: 'mono muted' },
`${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`, `${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`,
), ),
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn), el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), reconnectPtyBtn, exportPlainBtn, exportAnsiBtn, exportCastBtn, closeTabBtn),
), ),
el('div', { class: 'term-shell' }, termContainer, touchBar), el('div', { class: 'term-shell' }, termContainer, touchBar),
), ),
@ -630,6 +683,14 @@ export async function renderTerminalView(
typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null;
ro?.observe(termContainer); ro?.observe(termContainer);
const themeObs =
typeof MutationObserver !== 'undefined'
? new MutationObserver(() => {
if (term) term.options.theme = readXtermTheme();
})
: null;
themeObs?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => { const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => {
if (!term || !termContainer.isConnected) return; if (!term || !termContainer.isConnected) return;
if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) { if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) {
@ -638,6 +699,8 @@ export async function renderTerminalView(
} }
term.write(frame.data); term.write(frame.data);
} else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) { } else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) {
current.exited = true;
reconnectPtyBtn.hidden = false;
term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`); term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`);
} else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') { } else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') {
msgEl.className = 'form-msg warn-text'; msgEl.className = 'form-msg warn-text';
@ -645,9 +708,17 @@ export async function renderTerminalView(
} }
}); });
currentCleanup = () => { const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]);
let cleaned = false;
const disposeTerminalView = () => {
if (cleaned) return;
cleaned = true;
currentCleanup = null;
if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); if (fitRaf !== null) window.cancelAnimationFrame(fitRaf);
unsubChannel();
unsubFrame(); unsubFrame();
themeObs?.disconnect();
ro?.disconnect(); ro?.disconnect();
window.removeEventListener('resize', scheduleFit); window.removeEventListener('resize', scheduleFit);
window.visualViewport?.removeEventListener('resize', scheduleFit); window.visualViewport?.removeEventListener('resize', scheduleFit);
@ -657,7 +728,9 @@ export async function renderTerminalView(
term?.dispose(); term?.dispose();
}; };
wsClient.subscribe([`pty:${current.sessionId}`]); currentCleanup = disposeTerminalView;
registerViewCleanup(disposeTerminalView);
wsClient.send({ wsClient.send({
type: 'pty:resize', type: 'pty:resize',
sessionId: current.sessionId, sessionId: current.sessionId,