agentpen-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/session.js ADDED
@@ -0,0 +1,447 @@
1
+ // The session room: live terminal + people + chat + attributed prompts, and
2
+ // the replay player for sessions that have ended.
3
+ import { Terminal } from '/vendor/xterm.mjs';
4
+ import { FitAddon } from '/vendor/addon-fit.mjs';
5
+ import { h, fill, api, toast, copy, avatar, avatars, pill, clock, duration, eventText, go, ago } from '/app.js';
6
+
7
+ // "Their laptop is shut" stops being a dead end: the command that rebuilds the
8
+ // session (conversation and code) on the reader's own machine.
9
+ function pickupPanel(meta, lead) {
10
+ const hf = meta.handoff;
11
+ if (!hf) return null;
12
+ const cmd = `agentpen pickup ${location.origin}/s/${meta.id}`;
13
+ const what = hf.hasCode
14
+ ? `the conversation and ${meta.host.name}’s code${hf.branch ? ` on ${hf.branch}` : ''}${hf.changed ? `, including ${hf.changed} uncommitted file${hf.changed === 1 ? '' : 's'}` : ''}`
15
+ : 'the conversation';
16
+ return h('.pickup', { role: 'status' },
17
+ h('div', {}, h('b', {}, lead), h('div.small', {}, `Carry on from your own machine. Last checkpoint ${ago(hf.at)}: ${what}. Run this in your clone of the repository:`)),
18
+ h('.cmd', {}, h('span', {}, cmd), h('button.btn.small', { onclick: () => copy(cmd, 'Command copied') }, 'Copy')));
19
+ }
20
+
21
+ const THEME = { background: '#0e0c0a', foreground: '#e6dfd6', cursor: '#f0a35e', selectionBackground: '#5a4632' };
22
+ const FONT = 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace';
23
+
24
+ // The terminal always has the host's exact cols x rows; we scale the font so
25
+ // that grid fits the viewer's window instead of resizing the host's agent.
26
+ function makeTerminal(wrap, cols, rows, opts = {}) {
27
+ const term = new Terminal({ cols, rows, fontFamily: FONT, fontSize: 14, theme: THEME, scrollback: 5000, cursorBlink: true, ...opts });
28
+ const fit = new FitAddon();
29
+ term.loadAddon(fit);
30
+ term.open(wrap);
31
+ const scale = () => {
32
+ for (let i = 0; i < 4; i++) {
33
+ const d = fit.proposeDimensions();
34
+ if (!d || !d.cols || !d.rows) return;
35
+ const f = term.options.fontSize;
36
+ const next = Math.max(5, Math.min(16, Math.floor(f * Math.min(d.cols / term.cols, d.rows / term.rows) * 4) / 4));
37
+ if (Math.abs(next - f) < 0.25) return;
38
+ term.options.fontSize = next;
39
+ }
40
+ };
41
+ const ro = new ResizeObserver(scale);
42
+ ro.observe(wrap);
43
+ scale();
44
+ return { term, scale, dispose: () => { ro.disconnect(); term.dispose(); } };
45
+ }
46
+
47
+ function eventRow(e) {
48
+ return h('.evt', {}, h('b', {}, e.actor || 'System'), ' ', eventText(e.type), h('time', {}, clock(e.at)),
49
+ e.detail && (e.type === 'session.prompt' ? h('span.q', {}, e.detail) : h('span', {}, ` - ${e.detail}`)));
50
+ }
51
+
52
+ // ---- conversation view (Codex app sessions) --------------------------------
53
+
54
+ // Just enough Markdown for agent replies: fenced code, inline code, bold, lists.
55
+ function inline(s) {
56
+ return s.split(/(`[^`\n]+`|\*\*[^*\n]+\*\*)/).filter(Boolean).map((p) => (
57
+ p.startsWith('`') && p.length > 2 ? h('code', {}, p.slice(1, -1)) : p.startsWith('**') && p.length > 4 ? h('b', {}, p.slice(2, -2)) : p));
58
+ }
59
+ function prose(text) {
60
+ const out = [];
61
+ text.split(/```/).forEach((part, i) => {
62
+ if (i % 2) return out.push(h('pre', {}, part.replace(/^[\w+-]*\n/, '').replace(/\n$/, '')));
63
+ for (const block of part.split(/\n{2,}/)) {
64
+ const lines = block.split('\n').filter((l) => l.trim());
65
+ if (!lines.length) continue;
66
+ if (lines.every((l) => /^\s*([-*]|\d+\.)\s+/.test(l))) out.push(h('ul', {}, lines.map((l) => h('li', {}, inline(l.replace(/^\s*([-*]|\d+\.)\s+/, ''))))));
67
+ else if (/^#{1,4}\s/.test(lines[0]) && lines.length === 1) out.push(h('h4', {}, inline(lines[0].replace(/^#+\s/, ''))));
68
+ else out.push(h('p', {}, lines.flatMap((l, n) => (n ? [h('br'), ...inline(l)] : inline(l)))));
69
+ }
70
+ });
71
+ return out;
72
+ }
73
+
74
+ function threadView() {
75
+ const list = h('.turns');
76
+ const working = h('.thinking', { hidden: true }, h('span.pill.working', {}, 'Codex is working'));
77
+ const el = h('.transcript', { tabindex: 0, 'aria-label': 'Conversation' }, list, working);
78
+ const turns = new Map();
79
+ let order = [];
80
+ const item = (it) => {
81
+ if (it.role === 'user') return h('.bubble.user', {}, it.by && h('.by', {}, avatar(it.by), h('b', {}, it.by), h('span.muted', {}, ' via Agentpen')), h('p', {}, it.text),
82
+ it.status === 'queued' && h('.queued', {}, 'Queued. Codex picks it up when it is free.'));
83
+ if (it.role === 'assistant') return h('.bubble.agent', {}, prose(it.text));
84
+ if (it.role === 'plan') return h('.bubble.agent.plan', {}, h('.label', {}, 'Plan'), prose(it.text));
85
+ const row = h('summary', {}, h('code', {}, it.text.length > 140 ? it.text.slice(0, 140) + '…' : it.text), it.status && it.status !== 'completed' && h('span.tag', {}, it.status === 'inProgress' ? 'running' : it.status));
86
+ return it.detail ? h('details.tool', {}, row, h('pre', {}, it.detail)) : h('.tool', {}, row);
87
+ };
88
+ const turnEl = (t) => h('.turn', {}, t.items.map(item), t.status === 'failed' && h('.tool.failed', {}, t.error || 'This turn failed.'), t.status === 'interrupted' && h('.tool', {}, 'Interrupted'));
89
+ const draw = () => {
90
+ const stick = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
91
+ fill(list, order.length ? order.map((id) => turns.get(id)).filter(Boolean).map(turnEl)
92
+ : h('p.muted', { style: 'padding:24px 0' }, 'Nothing in this conversation yet. It will appear here as soon as the host sends a message in the Codex app.'));
93
+ if (stick) el.scrollTop = el.scrollHeight;
94
+ };
95
+ return {
96
+ el,
97
+ set(all) { turns.clear(); order = all.map((t) => t.id); for (const t of all) turns.set(t.id, t); draw(); el.scrollTop = el.scrollHeight; },
98
+ merge(m) { for (const t of m.turns || []) { turns.set(t.id, t); if (!order.includes(t.id)) order.push(t.id); } if (m.order) order = m.order; draw(); },
99
+ busy(on) { working.hidden = !on; },
100
+ };
101
+ }
102
+
103
+ // "Catch me up": a note written by an invited agent from what the session shows.
104
+ const NO_AGENT = 'No agent is connected yet. An admin can add Claude, Grok or Muse under Settings.';
105
+
106
+ // Which invited agent the next request goes to, when a workspace has more than one.
107
+ function agentPicker(meta) {
108
+ const agents = meta.agents || [];
109
+ let current = agents[0] || null;
110
+ const listeners = [];
111
+ const select = h('select.input', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'Which agent to invite', onchange: (e) => { current = agents.find((a) => a.id === e.target.value); listeners.forEach((f) => f()); } },
112
+ agents.map((a) => h('option', { value: a.id }, a.name)));
113
+ select.hidden = agents.length < 2;
114
+ return { select, get: () => current, any: () => agents.length > 0, onChange: (f) => listeners.push(f) };
115
+ }
116
+
117
+ function summaryBox(meta, pick) {
118
+ const box = h('.summary');
119
+ const draw = (s) => fill(box, s && [
120
+ h('.label', {}, `Catch-up by ${s.by || 'Claude'}`, h('time', {}, ago(s.at))),
121
+ h('p', {}, h('b', {}, 'Goal: '), s.goal),
122
+ s.done?.length ? h('ul', {}, s.done.map((d) => h('li', {}, d))) : null,
123
+ h('p', {}, h('b', {}, 'Now: '), s.state),
124
+ h('p', {}, h('b', {}, 'Next: '), s.next)]);
125
+ draw(meta.summary);
126
+ const btn = h('button.btn.small', { title: 'Have an agent read this session and summarise it', onclick: async () => {
127
+ if (!pick.any()) return toast(NO_AGENT);
128
+ btn.disabled = true; btn.textContent = 'Reading…';
129
+ try { draw((await api('POST', `/api/sessions/${meta.id}/summary`, { agent: pick.get().id })).summary); box.scrollIntoView({ block: 'nearest' }); } catch (x) { toast(x.message); }
130
+ btn.disabled = false; btn.textContent = 'Catch me up';
131
+ } }, 'Catch me up');
132
+ return { box, btn };
133
+ }
134
+
135
+ export async function sessionPage(id, guest, { mount, me }) {
136
+ const meta = await api('GET', `/api/sessions/${id}${guest ? `?guest=${encodeURIComponent(guest)}` : ''}`);
137
+ document.title = `${meta.title} · Agentpen`;
138
+ if (meta.status === 'live') return liveRoom(meta, guest, mount, me);
139
+ return replayRoom(meta, mount);
140
+ }
141
+
142
+ function roomBar(meta, ...right) {
143
+ const home = meta.workspace.slug ? `/w/${meta.workspace.slug}` : '/';
144
+ return h('header.roombar', {},
145
+ h('a.btn.ghost.small', { href: home, 'aria-label': `Back to ${meta.workspace.name}` }, '←'),
146
+ h('.title', {}, h('h1', {}, meta.title),
147
+ h('.meta', {}, [meta.host.name, meta.workspace.name, meta.project, meta.branch, meta.agent].filter(Boolean).join(' · '))),
148
+ h('span.spacer'), right);
149
+ }
150
+
151
+ // ---- live ------------------------------------------------------------------
152
+
153
+ function liveRoom(meta, guest, mount, me) {
154
+ let ws = null;
155
+ let you = { canType: false };
156
+ let closed = false;
157
+ let ended = false;
158
+ let retry = null;
159
+ let mode = 'chat';
160
+ let tab = 'chat';
161
+ let unread = 0;
162
+ let privateNow = meta.access === 'private';
163
+ let inited = false;
164
+ const chat = [];
165
+ const events = [...meta.events];
166
+ let agentBusy = null; // name of an invited agent that is reading the session right now
167
+ const pick = agentPicker(meta);
168
+ const summary = meta.guest ? null : summaryBox(meta, pick);
169
+ const driverSlot = h('div');
170
+ const drawDriver = (d) => fill(driverSlot, d && h('.banner.driver', { role: 'status' },
171
+ h('span', {}, h('b', {}, `${d.name} has the wheel`), ` · step ${Math.max(1, d.step)} of ${d.max} · ${d.goal}`), h('span.spacer'),
172
+ meta.canManage && h('button.btn.small', { onclick: async () => { try { await api('DELETE', `/api/sessions/${meta.id}/driver`); } catch (x) { toast(x.message); } } }, 'Take it back')));
173
+
174
+ const isThread = meta.kind === 'thread';
175
+ const wrap = h('.termwrap');
176
+ const view = isThread ? threadView() : null;
177
+ const banner = h('div');
178
+ const stateSlot = h('span');
179
+ const peopleSlot = h('span.hide-sm');
180
+ const peopleList = h('.people');
181
+ const feed = h('.feed', { 'aria-live': 'polite' });
182
+ const t = isThread ? null : makeTerminal(wrap, 100, 30, { disableStdin: true });
183
+ const enc = new TextEncoder();
184
+ t?.term.onData((d) => { if (you.canType && ws?.readyState === 1) ws.send(enc.encode(d)); });
185
+
186
+ const setBanner = (state) => {
187
+ if (ended) return;
188
+ if (state === 'blocked') fill(banner, h('.banner.blocked', { role: 'status' }, isThread ? `Codex is waiting on ${meta.host.name} to approve or answer in the app.` : 'The agent is waiting on a human.', !isThread && you.canType ? ' Click the terminal to answer.' : ''));
189
+ else if (state === 'reconnecting') fill(banner, h('.banner.reconnecting', { role: 'status' }, `${meta.host.name}'s machine went offline. Waiting for it to reconnect…`), pickupPanel(meta, 'Can’t wait?'));
190
+ else if (you.guest) fill(banner, h('.banner.info', {}, `You are watching ${meta.host.name}'s session as a guest.`));
191
+ else if (privateNow) fill(banner, h('.banner.info', {}, 'Private. Only you can see this session. Change it at the top right whenever you want to share.'));
192
+ else if (!you.canType) fill(banner, h('.banner.info', {}, `Watch only. The host has ${isThread ? 'prompting' : 'typing'} turned off for teammates.`));
193
+ else fill(banner);
194
+ };
195
+ const setState = (state) => { fill(stateSlot, pill(state)); setBanner(state); };
196
+ let state = 'working';
197
+
198
+ const drawPeople = (people) => {
199
+ fill(peopleSlot, avatars(people, 5));
200
+ fill(peopleList, people.map((p) => h('.p', {}, avatar(p.name), h('span', {}, p.name),
201
+ h('span.tag', {}, p.id === meta.host.id ? 'host' : p.guest ? 'guest' : p.canType ? (isThread ? 'can prompt' : 'can type') : 'watching'))));
202
+ };
203
+
204
+ const chatTab = h('button.btn.ghost.small', { onclick: () => setTab('chat') }, 'Chat');
205
+ const actTab = h('button.btn.ghost.small', { onclick: () => setTab('activity') }, 'Activity');
206
+ const drawFeed = () => {
207
+ chatTab.classList.toggle('on', tab === 'chat');
208
+ actTab.classList.toggle('on', tab === 'activity');
209
+ chatTab.textContent = unread ? `Chat (${unread})` : 'Chat';
210
+ if (tab === 'chat') {
211
+ fill(feed, chat.length || agentBusy ? [chat.map((m) => h(`.msg${m.agent ? '.agent' : ''}${m.error ? '.err' : ''}`, {}, h('b', {}, m.name), m.agent && h('span.tag', {}, m.via ? `invited by ${m.via}` : 'agent'), h('span', {}, m.text), h('time', {}, clock(m.at)))),
212
+ agentBusy && h('.msg.agent', {}, h('b', {}, agentBusy), h('span.muted', {}, 'is reading the session…'))]
213
+ : h('p.small.muted', {}, 'Talk to the people in this session. Chat never reaches the agent. Start a message with @claude, @grok or @muse to bring in a second opinion.'));
214
+ } else {
215
+ fill(feed, events.length ? events.map(eventRow) : h('p.small.muted', {}, 'Joins and prompts show up here.'));
216
+ }
217
+ feed.scrollTop = feed.scrollHeight;
218
+ };
219
+ const setTab = (next) => { tab = next; if (tab === 'chat') unread = 0; drawFeed(); };
220
+
221
+ // composer: two clearly different destinations
222
+ const input = h('textarea.input', { rows: 2, 'aria-label': 'Message' });
223
+ const sendBtn = h('button.btn.primary.small', { type: 'submit' });
224
+ const toAgent = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('prompt') }, isThread ? 'Ask Codex' : 'Prompt the agent');
225
+ const toTeam = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('chat') }, 'Chat with team');
226
+ // invite another model in: anyone can ask it, only the host can give it the wheel
227
+ const needAgent = () => { if (pick.any()) return true; toast(NO_AGENT); return false; };
228
+ const askClaude = h('button.btn.ghost.small', { type: 'button', title: 'An invited agent reads this session and answers in chat', onclick: () => {
229
+ if (!needAgent()) return;
230
+ setMode('chat');
231
+ input.value = `@${pick.get().id} ${input.value.replace(/^@\w+\s*/, '')}`;
232
+ input.focus();
233
+ } });
234
+ const giveWheel = h('button.btn.ghost.small', { type: 'button', title: 'An invited agent steers your agent toward a goal, for a few steps', onclick: () => { if (needAgent()) setMode('drive'); } }, 'Hand over');
235
+ const nameAgent = () => { askClaude.textContent = `Ask ${pick.get()?.name || 'an agent'}`; if (mode === 'drive') setMode('drive'); };
236
+ pick.onChange(nameAgent);
237
+ giveWheel.hidden = !meta.isHost;
238
+ askClaude.hidden = !!meta.guest;
239
+ const setMode = (m) => {
240
+ mode = (m === 'prompt' && !you.canType) || (m === 'drive' && !meta.isHost) ? 'chat' : m;
241
+ toAgent.hidden = !you.canType;
242
+ toAgent.classList.toggle('on', mode === 'prompt');
243
+ toTeam.classList.toggle('on', mode === 'chat');
244
+ giveWheel.classList.toggle('on', mode === 'drive');
245
+ if (mode === 'drive') { input.placeholder = `What should ${pick.get()?.name || 'the agent'} get done? It steers your agent for up to 8 steps and never approves anything for you.`; sendBtn.textContent = 'Hand over the wheel'; return; }
246
+ input.placeholder = mode === 'prompt' ? (isThread ? 'Ask Codex. Queued into the conversation under your name.' : 'Tell the agent what to do. Sent under your name.') : 'Message the people in this session';
247
+ sendBtn.textContent = mode === 'prompt' ? (isThread ? 'Send to Codex' : 'Send to agent') : 'Send';
248
+ };
249
+ const submit = () => {
250
+ const text = input.value.trim();
251
+ if (!text || ws?.readyState !== 1) return;
252
+ if (mode === 'drive') {
253
+ api('POST', `/api/sessions/${meta.id}/driver`, { goal: text, agent: pick.get().id }).then(() => { input.value = ''; setMode('chat'); setTab('chat'); }).catch((x) => toast(x.message));
254
+ return;
255
+ }
256
+ ws.send(JSON.stringify({ t: mode, text }));
257
+ input.value = '';
258
+ if (mode === 'chat') setTab('chat'); else if (!isThread) setTab('activity');
259
+ };
260
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); submit(); } });
261
+ const composer = h('form.composer', { onsubmit: (e) => { e.preventDefault(); submit(); } },
262
+ h('.modes', {}, toTeam, toAgent, askClaude, giveWheel, pick.select), input, h('.row', {}, h('span.small.muted', {}, 'Enter to send'), h('span.spacer'), sendBtn));
263
+
264
+ // host / admin controls
265
+ const access = h('select.input.hide-sm', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'What teammates can do',
266
+ onchange: async (e) => { try { await api('PATCH', `/api/sessions/${meta.id}`, { access: e.target.value }); } catch (x) { toast(x.message); } } },
267
+ h('option', { value: 'control' }, isThread ? 'Teammates can prompt' : 'Teammates can type'), h('option', { value: 'view' }, 'Teammates watch only'),
268
+ meta.isHost && h('option', { value: 'private' }, 'Private (only you)'));
269
+ const controls = [];
270
+ if (summary) controls.push(summary.btn);
271
+ if (!meta.guest) controls.push(h('button.btn.small', { onclick: () => copy(`${location.origin}/s/${meta.id}`, 'Link copied. Teammates in the workspace can open it.') }, 'Copy link'));
272
+ if (meta.canManage) {
273
+ controls.unshift(access);
274
+ controls.push(
275
+ h('button.btn.small.hide-sm', { title: 'View-only link for someone outside the workspace', onclick: async () => {
276
+ try { const r = await api('POST', `/api/sessions/${meta.id}/guest-link`); await copy(r.url, 'Guest link copied. View-only, dies with the session.'); } catch (x) { toast(x.message); }
277
+ } }, 'Guest link'),
278
+ h('button.btn.small.danger', { onclick: async () => {
279
+ if (!confirm(isThread ? 'Stop sharing this conversation? It carries on in the Codex app.' : 'End this session for everyone? The agent on the host machine will be stopped.')) return;
280
+ try { await api('POST', `/api/sessions/${meta.id}/end`); } catch (x) { toast(x.message); }
281
+ } }, 'End'));
282
+ }
283
+
284
+ const onEnd = (reason) => {
285
+ ended = true;
286
+ fill(stateSlot, h('span.pill', {}, 'Ended'));
287
+ fill(banner, h('.banner.info', { role: 'status' }, /private/.test(reason) ? `${reason}.` : `Session ended (${reason}).`, h('span.spacer'),
288
+ !meta.guest && !/private/.test(reason) && h('button.btn.small', { onclick: () => go(`/s/${meta.id}`, true) }, 'Watch the replay')));
289
+ composer.hidden = true;
290
+ };
291
+
292
+ const connect = () => {
293
+ ws = new WebSocket(`${location.origin.replace(/^http/, 'ws')}/ws/session/${meta.id}${guest ? `?guest=${encodeURIComponent(guest)}` : ''}`);
294
+ ws.binaryType = 'arraybuffer';
295
+ ws.onmessage = (e) => {
296
+ if (typeof e.data !== 'string') return t?.term.write(new Uint8Array(e.data));
297
+ const m = JSON.parse(e.data);
298
+ if (m.t === 'init') {
299
+ you = m.you;
300
+ if (t) {
301
+ t.term.reset();
302
+ t.term.resize(m.cols, m.rows);
303
+ t.scale();
304
+ t.term.options.disableStdin = !you.canType;
305
+ } else view.set(m.thread || []);
306
+ chat.length = 0;
307
+ chat.push(...m.chat);
308
+ access.value = m.session.access;
309
+ privateNow = m.session.access === 'private';
310
+ state = m.session.state;
311
+ setState(state);
312
+ view?.busy(state === 'working');
313
+ // in a conversation the natural thing to do is ask the agent
314
+ setMode(isThread && !inited ? 'prompt' : mode);
315
+ inited = true;
316
+ drawPeople(m.session.people);
317
+ drawDriver(m.driver);
318
+ drawFeed();
319
+ if (you.canType) t?.term.focus();
320
+ } else if (m.t === 'state') { state = m.state; setState(state); view?.busy(state === 'working'); }
321
+ else if (m.t === 'thread') view?.merge(m);
322
+ else if (m.t === 'notice') toast(m.text);
323
+ else if (m.t === 'agent') { agentBusy = m.busy ? m.name : null; if (m.busy && tab !== 'chat') setTab('chat'); else drawFeed(); }
324
+ else if (m.t === 'driver') drawDriver(m.driver);
325
+ else if (m.t === 'people') drawPeople(m.people);
326
+ else if (m.t === 'resize') { t?.term.resize(m.cols, m.rows); t?.scale(); }
327
+ else if (m.t === 'chat') { chat.push(m.msg); if (tab !== 'chat') unread++; drawFeed(); }
328
+ else if (m.t === 'activity') { events.push(m.event); drawFeed(); }
329
+ else if (m.t === 'access') {
330
+ you.canType = m.canType;
331
+ access.value = m.access;
332
+ privateNow = m.access === 'private';
333
+ if (t) t.term.options.disableStdin = !you.canType;
334
+ setMode(mode);
335
+ setBanner(state);
336
+ } else if (m.t === 'end') onEnd(m.reason);
337
+ };
338
+ ws.onclose = () => {
339
+ if (closed || ended) return;
340
+ // lost our own connection, or the session is gone: find out which
341
+ retry = setTimeout(async () => {
342
+ try {
343
+ const now = await api('GET', `/api/sessions/${meta.id}${guest ? `?guest=${encodeURIComponent(guest)}` : ''}`);
344
+ if (now.status === 'live') return connect();
345
+ onEnd('ended');
346
+ } catch (x) { if (x.status) onEnd('you no longer have access'); else connect(); }
347
+ }, 1500);
348
+ };
349
+ };
350
+
351
+ setState(state);
352
+ setMode('chat');
353
+ nameAgent();
354
+ drawFeed();
355
+ mount(h('.room', {},
356
+ roomBar(meta, stateSlot, peopleSlot, controls),
357
+ h('.roombody', {},
358
+ h(`.stage${isThread ? '.light' : ''}`, {}, driverSlot, banner, isThread ? view.el : wrap),
359
+ h('aside.side', {}, peopleList, summary?.box, h('.tabs', {}, chatTab, actTab), feed, composer))),
360
+ () => { closed = true; clearTimeout(retry); ws?.close(); t?.dispose(); });
361
+ connect();
362
+ }
363
+
364
+ // ---- replay ----------------------------------------------------------------
365
+
366
+ async function replayRoom(meta, mount) {
367
+ const bar = roomBar(meta, h('span.pill', {}, 'Ended'), h('span.small.muted.hide-sm', {}, `${new Date(meta.started_at).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })} · ${duration((meta.ended_at || meta.started_at) - meta.started_at)}`));
368
+ // the host decides whether an ended session (its recording and checkpoint) stays visible
369
+ if (meta.isHost) {
370
+ bar.append(h('select.input', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'Who can see this session', value: meta.access === 'private' ? 'private' : 'view',
371
+ onchange: async (e) => { try { await api('PATCH', `/api/sessions/${meta.id}`, { access: e.target.value }); toast(e.target.value === 'private' ? 'Only you can see this now' : 'Visible to the workspace'); } catch (x) { toast(x.message); } } },
372
+ h('option', { value: 'view', selected: meta.access !== 'private' }, 'Visible to the workspace'), h('option', { value: 'private', selected: meta.access === 'private' }, 'Private (only you)')));
373
+ }
374
+ const offline = meta.endReason === 'host disconnected';
375
+ const panel = pickupPanel(meta, offline ? `${meta.host.name}’s machine went offline mid-session.` : `Pick up where ${meta.host.name} left off.`);
376
+ const pick = agentPicker(meta);
377
+ const summary = summaryBox(meta, pick);
378
+ bar.append(pick.select, summary.btn);
379
+ const side = h('aside.side', {}, summary.box, h('.tabs', {}, h('button.btn.ghost.small.on', {}, 'Activity')),
380
+ h('.feed', {}, meta.events.length ? meta.events.map(eventRow) : h('p.small.muted', {}, 'No recorded activity.')));
381
+ if (meta.kind === 'thread' && meta.hasRecording) {
382
+ const view = threadView();
383
+ view.set((await (await fetch(`/api/sessions/${meta.id}/recording`)).json()).turns || []);
384
+ return mount(h('.room', {}, bar, h('.roombody', {}, h('.stage.light', {}, panel, view.el), side)));
385
+ }
386
+ if (!meta.hasRecording) {
387
+ return mount(h('.room', {}, bar, h('.roombody', {}, h('.stage', {}, h('.termwrap', {}, h('p.muted', {}, 'This session has ended and has no recording.'))), side)));
388
+ }
389
+ const text = await (await fetch(`/api/sessions/${meta.id}/recording`)).text();
390
+ const lines = text.split('\n').filter(Boolean);
391
+ const head = JSON.parse(lines[0]);
392
+ const evs = [];
393
+ for (const l of lines.slice(1)) { try { evs.push(JSON.parse(l)); } catch {} }
394
+ // squeeze dead air: nobody wants to watch a 20-minute pause
395
+ const at = [];
396
+ let prev = 0;
397
+ let acc = 0;
398
+ for (const e of evs) { acc += Math.min(2, Math.max(0, e[0] - prev)); prev = e[0]; at.push(acc); }
399
+ const total = Math.max(acc, 0.1);
400
+
401
+ const wrap = h('.termwrap');
402
+ const t = makeTerminal(wrap, head.width, head.height, { disableStdin: true, cursorBlink: false });
403
+ let idx = 0;
404
+ let pos = 0;
405
+ let playing = false;
406
+ let speed = 1;
407
+ let raf = null;
408
+ let last = 0;
409
+
410
+ const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
411
+ const play = h('button.btn.small', { onclick: () => (playing ? pause() : start()) }, 'Play');
412
+ const range = h('input', { type: 'range', min: 0, max: 1000, value: 0, 'aria-label': 'Position', oninput: (e) => seek((e.target.value / 1000) * total) });
413
+ const time = h('span.mono', { style: 'min-width:92px;text-align:right' });
414
+ const speedSel = h('select.input', { style: 'width:auto;height:30px;background:#2a2520;border-color:#3a332c;color:#efe8df', 'aria-label': 'Speed', onchange: (e) => { speed = Number(e.target.value); } },
415
+ [1, 2, 4, 8].map((s) => h('option', { value: s }, `${s}×`)));
416
+
417
+ const apply = (e) => {
418
+ if (e[1] === 'o') t.term.write(e[2]);
419
+ else if (e[1] === 'r') { const [c, r] = String(e[2]).split('x').map(Number); if (c && r) { t.term.resize(c, r); t.scale(); } }
420
+ };
421
+ const ui = () => { range.value = Math.round((pos / total) * 1000); time.textContent = `${fmt(pos)} / ${fmt(total)}`; play.textContent = playing ? 'Pause' : idx >= evs.length ? 'Replay' : 'Play'; };
422
+ const advance = () => { while (idx < evs.length && at[idx] <= pos) apply(evs[idx++]); };
423
+ function seek(to) {
424
+ t.term.reset();
425
+ t.term.resize(head.width, head.height);
426
+ idx = 0;
427
+ pos = to;
428
+ advance();
429
+ t.scale();
430
+ ui();
431
+ }
432
+ function frame(now) {
433
+ pos = Math.min(total, pos + ((now - last) / 1000) * speed);
434
+ last = now;
435
+ advance();
436
+ if (idx >= evs.length) { playing = false; ui(); return; }
437
+ ui();
438
+ raf = requestAnimationFrame(frame);
439
+ }
440
+ function start() { if (idx >= evs.length) seek(0); playing = true; last = performance.now(); raf = requestAnimationFrame(frame); ui(); }
441
+ function pause() { playing = false; cancelAnimationFrame(raf); ui(); }
442
+
443
+ mount(h('.room', {}, bar, h('.roombody', {},
444
+ h('.stage', {}, panel, wrap, h('.player', {}, play, range, time, speedSel)), side)),
445
+ () => { cancelAnimationFrame(raf); t.dispose(); });
446
+ seek(total); // open on the final screen; Play restarts from the top
447
+ }