durable-chat 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1695 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Input, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import { getNativeClipboard } from "@earendil-works/pi-tui";
4
+ import { withCancel } from "@earendil-works/chord/context";
5
+ import { selectModel } from "../models.js";
6
+ import { rollbackChoices, rollbackSource } from "../rollback.js";
7
+ import { describeConfig } from "../config.js";
8
+ import { parseId } from "../commands.js";
9
+ import { jobView } from "../format.js";
10
+ import { announceJobStart, compactConversation, createJobInCommit, findJobConversation, jobConversationId, jobCreateOptionsOf, jobRecord, jobInputDraft, normalizeBrief, scanJobs, } from "../jobs.js";
11
+ import { buildJobRows, clampScroll, filterJobs, moveSelection, reconcileJobSelection, targetLabel } from "./state.js";
12
+ import { backgroundLine, bold, dim, fg, padLines, shortenHome, statusText, usageTotals, ACCENT, BORDER, COMPOSER_BG, GREEN, MUTED, RED, TEXT, TRANSCRIPT_BG, YELLOW } from "./format.js";
13
+ import { attachmentLabel, createImagePaster, MAX_ATTACHMENTS } from "../images.js";
14
+ import { compactionLimit, contextPercent, formatTokenCount } from "../context-usage.js";
15
+ import { Transcript } from "./transcript.js";
16
+ import { overlayDialog } from "./dialog.js";
17
+ import { JOB_KIND } from "../tasks.js";
18
+ import { TranscriptSelection } from "./selection.js";
19
+ import { openBrowser } from "./browser.js";
20
+ const FLASH_MS = 5000;
21
+ const QUIT_REPEAT_MS = 1500;
22
+ const CHROME_ROWS = 8; // Header + spacer, status spacer + status, three composer rows, and hint.
23
+ const PANE_HEADING_ROWS = 2; // Title + spacer.
24
+ const MIN_ROWS = CHROME_ROWS + PANE_HEADING_ROWS + 1;
25
+ const JOB_ROW_HEIGHT = 3; // Status, brief, and a spacer between jobs.
26
+ function shortcut(keys, description) {
27
+ return `${bold(keys.toUpperCase())} ${fg(description, MUTED)}`;
28
+ }
29
+ /** Full-screen dashboard over one AppRuntime. All durable semantics stay in the runtime. */
30
+ export class Dashboard {
31
+ capturesViewportInput = true;
32
+ selection;
33
+ runtime;
34
+ rowsOf;
35
+ requestRender;
36
+ onQuit;
37
+ onReboot;
38
+ onRollback;
39
+ onModel;
40
+ onProvider;
41
+ initialNotice;
42
+ onEditConfig;
43
+ paster;
44
+ attachments = [];
45
+ input = new Input({
46
+ prompt: "",
47
+ placeholder: "type a message or Ctrl-N for a job",
48
+ placeholderStyle: (text) => fg(text, BORDER, { dim: true }),
49
+ });
50
+ state = {
51
+ focus: "composer",
52
+ target: { kind: "main" },
53
+ mode: "chat",
54
+ filter: "",
55
+ showFinished: true,
56
+ toolsExpanded: false,
57
+ steer: false,
58
+ };
59
+ main;
60
+ current;
61
+ graph;
62
+ nodes = new Map();
63
+ records = new Map();
64
+ rowsAll = [];
65
+ visible = [];
66
+ scroll = 0;
67
+ jobsScroll;
68
+ contextScroll = 0;
69
+ targetConversationId;
70
+ lastWidth = 120;
71
+ toast;
72
+ actionLabel;
73
+ actionCancel;
74
+ pending;
75
+ pendingResetHandoff;
76
+ pendingRollbackSource;
77
+ rollbackFiles = [];
78
+ modelItems = [];
79
+ modelIndex = 0;
80
+ modelLoading = false;
81
+ modelVersion = 0;
82
+ modelController;
83
+ modelWarning;
84
+ lastStatuses = new Map();
85
+ scanTimer;
86
+ clock;
87
+ scanning = false;
88
+ scanAgain = false;
89
+ started = false;
90
+ pinVersion = 0;
91
+ quitRequested = false;
92
+ quitArmedAt;
93
+ quitArmTimer;
94
+ constructor(options) {
95
+ this.selection = new TranscriptSelection(options.copySelection ?? (async (text) => {
96
+ process.stdout.write(`\x1b]52;c;${Buffer.from(text).toString("base64")}\x07`);
97
+ return true;
98
+ }), (result) => this.flash(result === true ? "copied to clipboard" : typeof result === "string" ? result : "Copy failed", result === true ? "info" : "error"), options.requestRender, options.openUrl ?? ((url) => { void openBrowser(url).catch((error) => this.flash(`Could not open link: ${message(error)}`, "error")); }));
99
+ this.runtime = options.runtime;
100
+ this.rowsOf = options.rows;
101
+ this.requestRender = options.requestRender;
102
+ this.onQuit = options.onQuit;
103
+ this.onReboot = options.onReboot;
104
+ this.onRollback = options.onRollback;
105
+ this.onModel = options.onModel;
106
+ this.onProvider = options.onProvider;
107
+ this.initialNotice = options.notice;
108
+ this.onEditConfig = options.onEditConfig;
109
+ this.paster = options.paster ?? createImagePaster(getNativeClipboard());
110
+ this.main = new Transcript(options.runtime.root);
111
+ this.main.onUpdate = () => this.renderSoon();
112
+ }
113
+ async start() {
114
+ await this.main.start(this.runtime.context, this.runtime.config.contextWindow);
115
+ this.current = this.main;
116
+ await this.refreshJobs(true);
117
+ this.graph = await this.runtime.harness.watchTaskGraph(this.runtime.context);
118
+ this.graph.start(async (call) => {
119
+ if (call.kind !== "value")
120
+ return;
121
+ this.onGraph(call.value);
122
+ });
123
+ this.clock = setInterval(() => {
124
+ if (this.nodes.size > 0 || this.actionLabel !== undefined || this.toast !== undefined)
125
+ this.requestRender();
126
+ }, 1000);
127
+ this.clock.unref?.();
128
+ // Resume pending work and continue interrupted phases from the previous process.
129
+ this.runtime.harness.resume();
130
+ this.started = true;
131
+ if (this.runtime.previousStateArchive !== undefined)
132
+ this.flash(`Previous state archive: ${this.runtime.previousStateArchive}`);
133
+ if (this.initialNotice !== undefined)
134
+ this.flash(this.initialNotice.text, this.initialNotice.error === true ? "error" : "info");
135
+ this.requestRender();
136
+ }
137
+ async stop() {
138
+ this.selection.reset();
139
+ this.started = false;
140
+ this.modelController?.abort();
141
+ this.modelVersion++;
142
+ this.disarmQuit();
143
+ this.actionCancel?.();
144
+ if (this.clock !== undefined)
145
+ clearInterval(this.clock);
146
+ if (this.scanTimer !== undefined)
147
+ clearTimeout(this.scanTimer);
148
+ await this.graph?.stop();
149
+ this.graph = undefined;
150
+ await this.current?.stop();
151
+ if (this.current !== this.main)
152
+ await this.main.stop();
153
+ }
154
+ invalidate() {
155
+ // Each pane rebuilds its own cache; this only asks the TUI for a frame.
156
+ this.requestRender();
157
+ }
158
+ renderSoon() {
159
+ if (this.started)
160
+ this.requestRender();
161
+ }
162
+ now() {
163
+ return Date.now();
164
+ }
165
+ onGraph(graph) {
166
+ const next = new Map();
167
+ for (const node of Object.values(graph.tasks))
168
+ next.set(Number(node.id), node);
169
+ this.nodes = next;
170
+ if (this.scanTimer !== undefined)
171
+ clearTimeout(this.scanTimer);
172
+ this.scanTimer = setTimeout(() => {
173
+ this.scanTimer = undefined;
174
+ void this.refreshJobs();
175
+ }, 120);
176
+ this.renderSoon();
177
+ }
178
+ async refreshJobs(initial = false) {
179
+ if (this.scanning) {
180
+ this.scanAgain = true;
181
+ return;
182
+ }
183
+ this.scanning = true;
184
+ try {
185
+ const records = await scanJobs(this.runtime.harness, this.runtime.context, 200);
186
+ this.records = new Map(records.map((record) => [Number(record.id), record]));
187
+ this.rowsAll = buildJobRows(records, [...this.nodes.values()]);
188
+ const previousStatuses = this.lastStatuses;
189
+ this.lastStatuses = new Map(this.rowsAll.map((row) => [row.id, row.status]));
190
+ if (!initial) {
191
+ for (const row of this.rowsAll) {
192
+ const before = previousStatuses.get(row.id);
193
+ if (before !== undefined && before !== row.status && !row.live) {
194
+ const ok = row.status.includes("completed") || row.status.includes("handed off");
195
+ this.flash(`job #${row.id} ${row.status}`, ok ? "info" : "error");
196
+ }
197
+ }
198
+ }
199
+ this.applyView();
200
+ this.renderSoon();
201
+ }
202
+ catch (error) {
203
+ this.flash(`job list failed: ${message(error)}`, "error");
204
+ }
205
+ finally {
206
+ this.scanning = false;
207
+ if (this.scanAgain) {
208
+ this.scanAgain = false;
209
+ void this.refreshJobs();
210
+ }
211
+ }
212
+ }
213
+ applyView() {
214
+ const previous = this.visible;
215
+ this.visible = filterJobs(this.rowsAll, this.state.filter, this.state.showFinished);
216
+ const selected = reconcileJobSelection(this.visible, previous, this.state.target, this.state.selectedJobId);
217
+ if (selected !== this.state.selectedJobId)
218
+ this.jobsScroll = undefined;
219
+ this.state.selectedJobId = selected;
220
+ }
221
+ async pinMain() {
222
+ this.pinVersion++;
223
+ if (this.current !== undefined && this.current !== this.main) {
224
+ const old = this.current;
225
+ this.current = this.main;
226
+ void old.stop();
227
+ }
228
+ this.current = this.main;
229
+ this.state.target = { kind: "main" };
230
+ this.state.selectedJobId = reconcileJobSelection(this.visible, [], this.state.target, this.state.selectedJobId);
231
+ this.targetConversationId = undefined;
232
+ this.scroll = 0;
233
+ this.jobsScroll = undefined;
234
+ this.contextScroll = 0;
235
+ this.renderSoon();
236
+ }
237
+ async pinJob(id) {
238
+ const version = ++this.pinVersion;
239
+ const row = this.rowsAll.find((item) => item.id === id);
240
+ this.state.target = { kind: "job", id };
241
+ this.scroll = 0;
242
+ this.jobsScroll = undefined;
243
+ this.contextScroll = 0;
244
+ this.state.selectedJobId = id;
245
+ const conversationId = row?.conversationId ?? await jobConversationId(this.runtime.harness, id, this.runtime.context);
246
+ if (version !== this.pinVersion)
247
+ return false;
248
+ this.targetConversationId = conversationId;
249
+ if (conversationId === undefined) {
250
+ const old = this.current;
251
+ this.current = undefined;
252
+ if (old !== undefined && old !== this.main)
253
+ void old.stop();
254
+ this.flash(`job #${id} has no conversation yet`, "error");
255
+ this.renderSoon();
256
+ return false;
257
+ }
258
+ const conversation = await this.runtime.harness.conversation(conversationId, this.runtime.context);
259
+ if (version !== this.pinVersion)
260
+ return false;
261
+ if (conversation === undefined) {
262
+ this.flash(`conversation #${conversationId} is unavailable`, "error");
263
+ this.renderSoon();
264
+ return false;
265
+ }
266
+ const old = this.current;
267
+ const transcript = new Transcript(conversation);
268
+ transcript.onUpdate = () => this.renderSoon();
269
+ try {
270
+ await transcript.start(this.runtime.context, this.runtime.config.contextWindow);
271
+ }
272
+ catch (error) {
273
+ await transcript.stop();
274
+ this.current = undefined;
275
+ this.flash(`could not read the job transcript: ${message(error)}`, "error");
276
+ this.renderSoon();
277
+ return false;
278
+ }
279
+ if (version !== this.pinVersion) {
280
+ void transcript.stop();
281
+ return false;
282
+ }
283
+ if (old !== undefined && old !== this.main)
284
+ void old.stop();
285
+ this.current = transcript;
286
+ this.renderSoon();
287
+ return true;
288
+ }
289
+ async openSelected() {
290
+ const id = this.state.selectedJobId;
291
+ if (id === undefined)
292
+ return;
293
+ try {
294
+ if (await this.pinJob(id)) {
295
+ this.state.focus = "transcript";
296
+ this.input.focused = false;
297
+ this.renderSoon();
298
+ }
299
+ }
300
+ catch (error) {
301
+ this.flash(message(error), "error");
302
+ }
303
+ }
304
+ async toggleTarget() {
305
+ try {
306
+ const selected = this.state.selectedJobId;
307
+ if (this.state.target.kind === "main") {
308
+ if (selected === undefined) {
309
+ this.flash("no job selected; start one with Ctrl-N", "info");
310
+ return;
311
+ }
312
+ if (await this.pinJob(selected))
313
+ this.flash(`target job #${selected}`, "info");
314
+ }
315
+ else {
316
+ await this.pinMain();
317
+ this.flash("target main", "info");
318
+ }
319
+ }
320
+ catch (error) {
321
+ this.flash(message(error), "error");
322
+ }
323
+ }
324
+ resizeJobs(delta) {
325
+ const max = Math.max(22, Math.min(52, Math.floor(this.lastWidth * 0.45)));
326
+ const current = this.state.jobsPane ?? this.jobsWidth(this.lastWidth);
327
+ this.state.jobsPane = Math.max(22, Math.min(max, current + delta));
328
+ this.renderSoon();
329
+ }
330
+ resizeContext(delta) {
331
+ const max = Math.max(20, Math.min(48, Math.floor(this.lastWidth * 0.4)));
332
+ const current = this.state.contextPane ?? (this.lastWidth >= 110 ? this.contextWidth(this.lastWidth) : 30);
333
+ this.state.contextPane = Math.max(20, Math.min(max, current + delta));
334
+ this.renderSoon();
335
+ }
336
+ beginPrompt(mode) {
337
+ this.state.mode = mode;
338
+ this.input.setValue("");
339
+ this.state.focus = "composer";
340
+ this.input.focused = true;
341
+ this.renderSoon();
342
+ }
343
+ cancelPrompt() {
344
+ this.modelController?.abort();
345
+ this.modelVersion++;
346
+ this.state.mode = "chat";
347
+ this.input.setValue("");
348
+ this.pending = undefined;
349
+ this.pendingResetHandoff = undefined;
350
+ this.pendingRollbackSource = undefined;
351
+ this.rollbackFiles = [];
352
+ this.renderSoon();
353
+ }
354
+ flash(text, kind = "info") {
355
+ const at = this.now();
356
+ this.toast = { text, kind, at };
357
+ this.renderSoon();
358
+ const timer = setTimeout(() => {
359
+ if (this.toast?.at === at) {
360
+ this.toast = undefined;
361
+ this.renderSoon();
362
+ }
363
+ }, FLASH_MS);
364
+ timer.unref?.();
365
+ }
366
+ async runAction(label, run) {
367
+ if (this.actionCancel !== undefined) {
368
+ this.flash("an action is already running", "error");
369
+ return;
370
+ }
371
+ const cancellable = withCancel(this.runtime.context);
372
+ this.actionLabel = label;
373
+ this.actionCancel = cancellable.cancel;
374
+ this.renderSoon();
375
+ try {
376
+ await run(cancellable.context);
377
+ }
378
+ catch (error) {
379
+ this.flash(message(error), "error");
380
+ }
381
+ finally {
382
+ this.actionLabel = undefined;
383
+ this.actionCancel = undefined;
384
+ this.renderSoon();
385
+ }
386
+ }
387
+ async pasteAttachments() {
388
+ try {
389
+ await this.addAttachments(await this.paster.paste());
390
+ }
391
+ catch (error) {
392
+ this.flash(message(error), "error");
393
+ }
394
+ }
395
+ async addAttachments(next) {
396
+ if (this.state.target.kind !== "main") {
397
+ this.flash("images go to main only", "error");
398
+ return;
399
+ }
400
+ if (!this.runtime.supportsImages()) {
401
+ this.flash(`${this.runtime.modelLabel} does not take image input`, "error");
402
+ return;
403
+ }
404
+ if (next.length === 0) {
405
+ this.flash("nothing to attach", "error");
406
+ return;
407
+ }
408
+ if (this.attachments.length + next.length > MAX_ATTACHMENTS) {
409
+ this.flash(`at most ${MAX_ATTACHMENTS} images per message`, "error");
410
+ return;
411
+ }
412
+ this.attachments.push(...next);
413
+ this.flash(`attached ${attachmentLabel(this.attachments)}`);
414
+ this.renderSoon();
415
+ }
416
+ async submit() {
417
+ const value = this.input.getValue();
418
+ const text = value.trim();
419
+ if (this.state.mode === "newJob") {
420
+ if (text.length === 0) {
421
+ this.flash("a job needs a brief", "error");
422
+ return;
423
+ }
424
+ let brief;
425
+ try {
426
+ brief = normalizeBrief(text);
427
+ }
428
+ catch (error) {
429
+ this.flash(message(error), "error");
430
+ return;
431
+ }
432
+ this.state.mode = "chat";
433
+ this.input.setValue("");
434
+ await this.runAction("starting job", async (context) => {
435
+ const started = await this.runtime.root.commit((tx) => createJobInCommit(tx, brief, this.runtime.model, this.runtime.jobExtensions, this.runtime.cwd, {
436
+ ...jobCreateOptionsOf(this.runtime.config),
437
+ notifyMain: true,
438
+ }), context);
439
+ let notifyError;
440
+ try {
441
+ await announceJobStart(this.runtime.root, started, brief, context);
442
+ }
443
+ catch (error) {
444
+ notifyError = message(error);
445
+ }
446
+ this.runtime.harness.resume();
447
+ await this.refreshJobs();
448
+ await this.pinJob(Number(started.taskId));
449
+ this.state.focus = "transcript";
450
+ this.flash(notifyError === undefined
451
+ ? `job #${started.taskId} started`
452
+ : `job #${started.taskId} started; main was not notified: ${notifyError}`, notifyError === undefined ? "info" : "error");
453
+ });
454
+ return;
455
+ }
456
+ if (this.state.mode === "compact") {
457
+ const instructions = text.length === 0 ? undefined : text;
458
+ const target = this.state.target;
459
+ this.state.mode = "chat";
460
+ this.input.setValue("");
461
+ await this.runAction(`compacting ${targetLabel(target)}`, async (context) => {
462
+ const conversation = target.kind === "main"
463
+ ? this.runtime.root
464
+ : await findJobConversation(this.runtime.harness, target.id, context);
465
+ if (conversation === undefined)
466
+ throw new Error(`job #${target.kind === "job" ? target.id : "?"} has no conversation`);
467
+ const result = await compactConversation(this.runtime.harness, conversation, instructions, context);
468
+ this.flash(result.noop ? "compaction no-op" : `compacted ${targetLabel(target)}`, "info");
469
+ });
470
+ return;
471
+ }
472
+ if (this.state.mode === "model") {
473
+ if (this.modelLoading)
474
+ return;
475
+ const selected = this.matchingModels()[this.modelIndex];
476
+ if (selected === undefined) {
477
+ this.flash("No matching model.", "error");
478
+ return;
479
+ }
480
+ this.chooseModel(selected.lookup);
481
+ return;
482
+ }
483
+ if (this.state.mode === "rollback") {
484
+ try {
485
+ this.pendingRollbackSource = rollbackSource(text, this.rollbackFiles, this.runtime.storePath);
486
+ }
487
+ catch (error) {
488
+ this.flash(message(error), "error");
489
+ return;
490
+ }
491
+ this.pending = "rollback";
492
+ this.state.mode = "confirmRollback";
493
+ this.input.setValue("");
494
+ this.renderSoon();
495
+ return;
496
+ }
497
+ if (this.state.mode === "reset") {
498
+ this.pending = "reset";
499
+ this.pendingResetHandoff = text.length === 0 ? undefined : text;
500
+ this.state.mode = "confirmReset";
501
+ this.input.setValue("");
502
+ this.renderSoon();
503
+ return;
504
+ }
505
+ if (this.state.mode === "filter") {
506
+ this.state.filter = text;
507
+ this.state.mode = "chat";
508
+ this.input.setValue("");
509
+ this.applyView();
510
+ this.renderSoon();
511
+ return;
512
+ }
513
+ if (text.length === 0 && this.attachments.length === 0)
514
+ return;
515
+ if (text.startsWith("/")) {
516
+ this.input.setValue("");
517
+ try {
518
+ await this.submitSlash(text);
519
+ }
520
+ catch (error) {
521
+ this.flash(message(error), "error");
522
+ }
523
+ this.renderSoon();
524
+ return;
525
+ }
526
+ const target = this.state.target;
527
+ if (this.attachments.length > 0 && target.kind !== "main") {
528
+ this.flash("images go to main only", "error");
529
+ return;
530
+ }
531
+ const attachments = this.attachments;
532
+ this.attachments = [];
533
+ this.input.setValue("");
534
+ this.scroll = 0;
535
+ this.renderSoon();
536
+ await this.runAction(`sending to ${targetLabel(target)}`, async (context) => {
537
+ if (target.kind === "main") {
538
+ const content = attachments.length === 0
539
+ ? text
540
+ : [...(text.length > 0 ? [{ type: "text", text }] : []), ...attachments.map((image) => ({ type: "image", data: image.data, mimeType: image.mimeType }))];
541
+ await this.runtime.root.submit({
542
+ type: "input",
543
+ content,
544
+ whenBusy: this.state.steer ? "steer" : "followUp",
545
+ }, context);
546
+ this.flash(this.state.steer ? "steered main" : "sent to main");
547
+ return;
548
+ }
549
+ const conversation = await findJobConversation(this.runtime.harness, target.id, context);
550
+ if (conversation === undefined)
551
+ throw new Error(`job #${target.id} has no conversation`);
552
+ await conversation.submit(jobInputDraft(text, this.state.steer), context);
553
+ this.flash(this.state.steer ? `steered job #${target.id}` : `sent to job #${target.id}`);
554
+ });
555
+ }
556
+ async submitSlash(text) {
557
+ const source = text.slice(1).trim();
558
+ const command = source.split(/\s+/, 1)[0].toLowerCase();
559
+ const tail = source.slice(command.length).trim();
560
+ const rawId = tail.split(/\s+/, 1)[0];
561
+ switch (command) {
562
+ case "":
563
+ case "help":
564
+ this.state.mode = "help";
565
+ return;
566
+ case "info":
567
+ this.state.mode = "inspector";
568
+ return;
569
+ case "model": {
570
+ if (this.onModel === undefined)
571
+ throw new Error("Model switching is unavailable here.");
572
+ this.modelController?.abort();
573
+ const controller = new AbortController();
574
+ this.modelController = controller;
575
+ const version = ++this.modelVersion;
576
+ this.modelItems = [];
577
+ this.modelIndex = 0;
578
+ this.modelLoading = true;
579
+ this.modelWarning = undefined;
580
+ this.beginPrompt("model");
581
+ try {
582
+ const choices = await this.runtime.listModels(controller.signal);
583
+ if (version !== this.modelVersion || controller.signal.aborted)
584
+ return;
585
+ this.modelItems = choices.items;
586
+ this.modelWarning = choices.warning;
587
+ if (tail.length > 0) {
588
+ this.input.setValue(tail);
589
+ this.chooseModel(selectModel(tail, choices.items).lookup);
590
+ }
591
+ }
592
+ catch (error) {
593
+ if (!controller.signal.aborted)
594
+ this.flash(message(error), "error");
595
+ }
596
+ finally {
597
+ if (version === this.modelVersion) {
598
+ this.modelLoading = false;
599
+ this.renderSoon();
600
+ }
601
+ }
602
+ return;
603
+ }
604
+ case "provider": {
605
+ if (this.onProvider === undefined)
606
+ throw new Error("Provider switching is unavailable here.");
607
+ const entries = this.runtime.config.providers;
608
+ if (tail.length === 0) {
609
+ this.flash(`providers: ${entries.map((entry) => `${entry.name}${entry.name === this.runtime.config.provider ? " (current)" : ""}`).join(", ")}`);
610
+ return;
611
+ }
612
+ const entry = entries.find((candidate) => candidate.name === tail);
613
+ if (entry === undefined) {
614
+ this.flash(`No configured provider "${tail}". Known: ${entries.map((candidate) => candidate.name).join(", ")}`, "error");
615
+ return;
616
+ }
617
+ this.chooseProvider(tail);
618
+ return;
619
+ }
620
+ case "image": {
621
+ if (tail.length === 0)
622
+ throw new Error("Usage: /image <path>");
623
+ await this.addAttachments([await this.paster.fromPath(tail)]);
624
+ return;
625
+ }
626
+ case "thinking": {
627
+ if (tail.length === 0) {
628
+ this.flash(`thinking: ${this.runtime.thinkingLevel}`);
629
+ return;
630
+ }
631
+ await this.runAction(`thinking ${tail}`, async () => {
632
+ this.flash(`thinking level: ${await this.runtime.setThinkingLevel(tail)}`);
633
+ });
634
+ return;
635
+ }
636
+ case "rollback":
637
+ if (this.onRollback === undefined)
638
+ throw new Error("Rollback is unavailable here.");
639
+ this.rollbackFiles = rollbackChoices(this.runtime.storePath, this.runtime.previousStateArchive);
640
+ this.beginPrompt("rollback");
641
+ if (tail.length > 0) {
642
+ this.input.setValue(tail);
643
+ await this.submit();
644
+ }
645
+ return;
646
+ case "reboot":
647
+ if (tail.length > 0)
648
+ throw new Error("Usage: /reboot");
649
+ if (this.onReboot === undefined)
650
+ throw new Error("Reboot is unavailable here.");
651
+ this.pending = "reboot";
652
+ this.state.mode = "confirmReboot";
653
+ return;
654
+ case "quit":
655
+ case "exit":
656
+ this.requestQuit();
657
+ return;
658
+ case "tasks":
659
+ await this.refreshJobs();
660
+ this.state.focus = this.lastWidth >= 64 ? "jobs" : "transcript";
661
+ if (this.lastWidth < 64)
662
+ this.flash(`${this.visible.length} jobs: ${this.visible.map((row) => `#${row.id}`).join(", ") || "none"}`);
663
+ return;
664
+ case "task":
665
+ case "show":
666
+ case "log":
667
+ case "cancel": {
668
+ const id = parseId(rawId);
669
+ if ((await jobRecord(this.runtime.harness, id, this.runtime.context))?.kind !== JOB_KIND)
670
+ throw new Error(`No job #${id}.`);
671
+ if (!(await this.pinJob(id)))
672
+ return;
673
+ this.state.focus = "transcript";
674
+ if (command === "cancel")
675
+ this.requestCancel();
676
+ return;
677
+ }
678
+ case "new":
679
+ case "compact":
680
+ case "reset":
681
+ case "filter":
682
+ this.beginPrompt(command === "new" ? "newJob" : command);
683
+ this.input.setValue(tail);
684
+ if (tail.length > 0 || command === "compact" || command === "reset")
685
+ await this.submit();
686
+ return;
687
+ case "send":
688
+ case "steer": {
689
+ const id = parseId(rawId);
690
+ const content = tail.slice(rawId.length).trim();
691
+ if (content.length === 0)
692
+ throw new Error(`Usage: /${command} <id> <message>`);
693
+ await this.runAction(`${command} job #${id}`, async (context) => {
694
+ const conversation = await findJobConversation(this.runtime.harness, id, context);
695
+ if (conversation === undefined)
696
+ throw new Error(`No conversation for job #${id}.`);
697
+ await conversation.submit(jobInputDraft(content, command === "steer"), context);
698
+ this.flash(command === "steer" ? `steered job #${id}` : `sent to job #${id}`);
699
+ });
700
+ return;
701
+ }
702
+ case "wait":
703
+ await this.runAction("waiting for jobs", async (context) => {
704
+ const pending = (await this.runtime.harness.inspect(context)).tasks.filter((task) => task.record.kind === JOB_KIND);
705
+ await Promise.all(pending.map((task) => this.runtime.harness.waitForTask(task.record.id, context)));
706
+ await this.refreshJobs();
707
+ this.flash(pending.length === 0 ? "no live jobs" : "jobs settled");
708
+ });
709
+ return;
710
+ default:
711
+ this.flash(`Unknown command /${command}. Use /help.`, "error");
712
+ }
713
+ }
714
+ disarmQuit() {
715
+ const armed = this.quitArmedAt !== undefined;
716
+ this.quitArmedAt = undefined;
717
+ if (this.quitArmTimer !== undefined)
718
+ clearTimeout(this.quitArmTimer);
719
+ this.quitArmTimer = undefined;
720
+ if (armed)
721
+ this.renderSoon();
722
+ }
723
+ interrupt() {
724
+ if (this.quitRequested)
725
+ return;
726
+ const now = this.now();
727
+ const elapsed = this.quitArmedAt === undefined ? undefined : now - this.quitArmedAt;
728
+ this.disarmQuit();
729
+ if (elapsed !== undefined && elapsed >= 0 && elapsed < QUIT_REPEAT_MS) {
730
+ this.requestQuit();
731
+ return;
732
+ }
733
+ if (this.state.mode !== "chat") {
734
+ this.cancelPrompt();
735
+ }
736
+ else if (this.actionCancel !== undefined) {
737
+ this.actionCancel();
738
+ this.flash("stopped waiting; durable work continues");
739
+ }
740
+ else {
741
+ this.input.setValue("");
742
+ this.flash("cleared");
743
+ }
744
+ this.quitArmedAt = now;
745
+ this.quitArmTimer = setTimeout(() => this.disarmQuit(), QUIT_REPEAT_MS);
746
+ this.quitArmTimer.unref?.();
747
+ this.renderSoon();
748
+ }
749
+ matchingModels() {
750
+ const query = this.input.getValue().trim().toLowerCase();
751
+ return this.modelItems.filter((item) => `${item.lookup} ${item.name}`.toLowerCase().includes(query));
752
+ }
753
+ chooseModel(id) {
754
+ this.state.mode = "chat";
755
+ this.input.setValue("");
756
+ this.quitRequested = true;
757
+ this.onModel?.(id);
758
+ }
759
+ chooseProvider(name) {
760
+ this.state.mode = "chat";
761
+ this.input.setValue("");
762
+ this.quitRequested = true;
763
+ this.onProvider?.(name);
764
+ }
765
+ requestQuit() {
766
+ if (this.quitRequested)
767
+ return;
768
+ if (this.actionLabel !== undefined || this.nodes.size > 0) {
769
+ this.pending = "quit";
770
+ this.state.mode = "confirmQuit";
771
+ this.renderSoon();
772
+ return;
773
+ }
774
+ this.quitRequested = true;
775
+ this.onQuit();
776
+ }
777
+ confirm() {
778
+ const pending = this.pending;
779
+ this.pending = undefined;
780
+ this.state.mode = "chat";
781
+ if (pending === "cancel") {
782
+ const id = this.state.target.kind === "job" ? this.state.target.id : undefined;
783
+ if (id === undefined)
784
+ return;
785
+ void this.runAction(`cancelling job #${id}`, async (context) => {
786
+ await this.runtime.harness.abortTask(id, context);
787
+ this.flash(`cancel requested for job #${id}`, "info");
788
+ await this.refreshJobs();
789
+ });
790
+ return;
791
+ }
792
+ if (pending === "reset") {
793
+ const target = this.state.target;
794
+ const handoff = this.pendingResetHandoff;
795
+ this.pendingResetHandoff = undefined;
796
+ void this.runAction(`resetting ${targetLabel(target)}`, async (context) => {
797
+ const conversation = target.kind === "main"
798
+ ? this.runtime.root
799
+ : await findJobConversation(this.runtime.harness, target.id, context);
800
+ if (conversation === undefined)
801
+ throw new Error(`job #${target.kind === "job" ? target.id : "?"} has no conversation`);
802
+ await conversation.reset(handoff, context);
803
+ this.flash(`reset ${targetLabel(target)}`, "info");
804
+ });
805
+ return;
806
+ }
807
+ if (pending === "abortMain") {
808
+ void this.runAction("aborting main run", async (context) => {
809
+ await this.runtime.root.abort(context);
810
+ this.flash("main run aborted (jobs survive)", "info");
811
+ });
812
+ return;
813
+ }
814
+ if (pending === "rollback") {
815
+ const source = this.pendingRollbackSource;
816
+ this.pendingRollbackSource = undefined;
817
+ if (source === undefined)
818
+ return;
819
+ this.quitRequested = true;
820
+ this.onRollback?.(source);
821
+ return;
822
+ }
823
+ if (pending === "reboot") {
824
+ this.quitRequested = true;
825
+ this.onReboot?.();
826
+ return;
827
+ }
828
+ if (pending === "quit") {
829
+ this.quitRequested = true;
830
+ this.onQuit();
831
+ }
832
+ }
833
+ async editConfig() {
834
+ if (this.onEditConfig === undefined) {
835
+ this.flash("config editing is unavailable here", "error");
836
+ return;
837
+ }
838
+ this.state.mode = "chat";
839
+ this.renderSoon();
840
+ try {
841
+ const result = await this.onEditConfig();
842
+ this.flash(result);
843
+ }
844
+ catch (error) {
845
+ this.flash(message(error), "error");
846
+ }
847
+ finally {
848
+ this.renderSoon();
849
+ }
850
+ }
851
+ requestCancel() {
852
+ if (this.state.target.kind !== "job") {
853
+ this.flash("select a job first (Tab, then j/k and Enter)", "error");
854
+ return;
855
+ }
856
+ this.pending = "cancel";
857
+ this.state.mode = "confirmCancel";
858
+ this.renderSoon();
859
+ }
860
+ requestReset() {
861
+ this.pendingResetHandoff = undefined;
862
+ this.state.mode = "reset";
863
+ this.input.setValue("");
864
+ this.state.focus = "composer";
865
+ this.input.focused = true;
866
+ this.renderSoon();
867
+ }
868
+ requestAbortMain() {
869
+ this.pending = "abortMain";
870
+ this.state.mode = "confirmAbortMain";
871
+ this.renderSoon();
872
+ }
873
+ transcriptLines(width) {
874
+ if (this.current === undefined)
875
+ return [];
876
+ const lines = [...this.current.lines(width, this.state.toolsExpanded), ...this.current.liveLines(width)];
877
+ // A trailing entry spacer must not occupy the only content row in a short terminal.
878
+ while (lines.length > 0 && stripTerminalSequences(lines.at(-1)).trim().length === 0)
879
+ lines.pop();
880
+ return lines;
881
+ }
882
+ scrollBy(delta) {
883
+ const transcript = this.current;
884
+ if (transcript === undefined)
885
+ return;
886
+ const width = this.paneWidths(this.lastWidth).transcriptWidth;
887
+ const total = this.transcriptLines(width).length;
888
+ const height = this.contentHeight();
889
+ this.scroll = clampScroll(this.scroll + delta, total, height);
890
+ if (delta > 0 && this.scroll > 0 && transcript.hasOlder) {
891
+ void transcript.older(this.runtime.context).then((more) => {
892
+ if (more)
893
+ this.renderSoon();
894
+ });
895
+ }
896
+ this.renderSoon();
897
+ }
898
+ contentHeight() {
899
+ return Math.max(1, this.bodyHeight() - PANE_HEADING_ROWS);
900
+ }
901
+ bodyHeight() {
902
+ return Math.max(3, Math.max(MIN_ROWS, Math.round(this.rowsOf())) - CHROME_ROWS);
903
+ }
904
+ /** Shared by rendering, transcript wrapping and pointer hit testing after pane resizes. */
905
+ paneWidths(width) {
906
+ const jobsWidth = width >= 64 ? this.jobsWidth(width) : 0;
907
+ let contextWidth = this.contextWidth(width);
908
+ const separators = (jobsWidth > 0 ? 1 : 0) + (contextWidth > 0 ? 1 : 0);
909
+ let transcriptWidth = width - jobsWidth - contextWidth - separators;
910
+ if (transcriptWidth < 30) {
911
+ contextWidth = 0;
912
+ transcriptWidth = width - jobsWidth - (jobsWidth > 0 ? 1 : 0);
913
+ }
914
+ return { jobsWidth, transcriptWidth, contextWidth };
915
+ }
916
+ jobsOffset(height) {
917
+ const capacity = Math.max(1, Math.floor((height - PANE_HEADING_ROWS + 1) / JOB_ROW_HEIGHT));
918
+ const selectedIndex = Math.max(0, this.visible.findIndex((row) => row.id === this.state.selectedJobId));
919
+ const centered = Math.max(0, Math.min(selectedIndex - Math.floor(capacity / 2), this.visible.length - capacity));
920
+ return clampScroll(this.jobsScroll ?? centered * JOB_ROW_HEIGHT, Math.max(0, this.visible.length * JOB_ROW_HEIGHT - 1), Math.max(1, height - PANE_HEADING_ROWS));
921
+ }
922
+ jobsWidth(width) {
923
+ if (this.state.jobsPane !== undefined) {
924
+ return Math.max(22, Math.min(this.state.jobsPane, Math.max(22, width - 42)));
925
+ }
926
+ return Math.max(24, Math.min(30, Math.round(width * 0.22)));
927
+ }
928
+ contextWidth(width) {
929
+ if (this.state.contextPane !== undefined) {
930
+ if (width < 76)
931
+ return 0;
932
+ return Math.max(20, Math.min(this.state.contextPane, Math.max(20, width - this.jobsWidth(width) - 32)));
933
+ }
934
+ return width >= 110 ? Math.max(26, Math.min(36, Math.round(width * 0.23))) : 0;
935
+ }
936
+ copy() {
937
+ const target = this.state.target;
938
+ let text = "";
939
+ if (target.kind === "job") {
940
+ const record = this.records.get(target.id);
941
+ text = record === undefined ? "" : (jobView(record).answer ?? "");
942
+ }
943
+ if (text.length === 0 && this.current !== undefined) {
944
+ for (const entry of [...this.current.entries].reverse()) {
945
+ if (entry.kind !== "pi.assistant")
946
+ continue;
947
+ const messages = (entry.model ?? []);
948
+ const last = messages.at(-1);
949
+ if (last === undefined)
950
+ continue;
951
+ text = contentText(last.content);
952
+ if (text.length > 0)
953
+ break;
954
+ }
955
+ }
956
+ if (text.length === 0) {
957
+ this.flash("nothing to copy", "error");
958
+ return;
959
+ }
960
+ process.stdout.write(`\x1b]52;c;${Buffer.from(text).toString("base64")}\x07`);
961
+ this.flash("copied to clipboard");
962
+ }
963
+ render(width) {
964
+ this.lastWidth = width;
965
+ const height = Math.max(MIN_ROWS, Math.round(this.rowsOf()));
966
+ const bodyHeight = this.bodyHeight();
967
+ if (this.state.mode !== "chat")
968
+ this.selection.update();
969
+ let body;
970
+ if (this.state.mode === "help")
971
+ body = this.renderHelp(width, bodyHeight);
972
+ else if (this.state.mode === "inspector")
973
+ body = this.renderInspector(width, bodyHeight);
974
+ else if (this.state.mode === "model")
975
+ body = this.renderModels(width, bodyHeight);
976
+ else if (this.state.mode === "rollback")
977
+ body = this.panel("Rollback state", [
978
+ "Choose an archive number or enter a database file path.",
979
+ "Esc cancels. A separate confirmation follows selection.", "",
980
+ ...(this.rollbackFiles.length === 0 ? ["No recent archives; enter a file path."] : this.rollbackFiles.map((path, index) => `${index + 1}. ${path}`)),
981
+ ], width, bodyHeight);
982
+ else if (this.state.mode === "confirmCancel" || this.state.mode === "confirmReset" || this.state.mode === "confirmAbortMain") {
983
+ body = this.renderConfirm(width, bodyHeight);
984
+ }
985
+ else {
986
+ body = this.renderBody(width, bodyHeight);
987
+ }
988
+ const frame = [
989
+ this.renderHeader(width),
990
+ " ".repeat(width),
991
+ ...padLines(body, bodyHeight, width),
992
+ " ".repeat(width),
993
+ this.renderStatus(width),
994
+ ...this.renderComposer(width),
995
+ this.renderHint(width),
996
+ ].slice(0, height);
997
+ if (this.state.mode === "confirmRollback")
998
+ return overlayDialog(frame, width, "Rollback all state?", `Restore from ${this.pendingRollbackSource}. Current state will be archived first; the selected file stays unchanged. Restored jobs resume. Project files and worktrees stay in place.`, "Y restore · Enter / N / Esc cancel");
999
+ if (this.state.mode === "confirmReboot")
1000
+ return overlayDialog(frame, width, "Reboot all state?", `Archive this store’s conversations, jobs and tags, then start fresh at ${this.runtime.storePath}. Durable work stays paused in the archive. Project files and worktrees stay in place.`, "Y reboot · Enter / N / Esc cancel");
1001
+ if (this.state.mode !== "confirmQuit")
1002
+ return frame;
1003
+ const live = this.rowsAll.filter((row) => row.live).length;
1004
+ const tasks = this.nodes.size;
1005
+ const detail = tasks === 0 ? "No live work." : `${live} live job${live === 1 ? "" : "s"} and ${tasks} live task${tasks === 1 ? "" : "s"} pause and resume on the next run.`;
1006
+ return overlayDialog(frame, width, "Quit durable-chat?", detail, "Enter / y quit · n / Esc cancel");
1007
+ }
1008
+ renderHeader(width) {
1009
+ const live = this.rowsAll.filter((row) => row.live).length;
1010
+ const mcp = !this.runtime.mcpAttempted ? "mcp off" : this.runtime.mcpConnected ? "substrate" : "substrate down";
1011
+ const left = `${bold("durable-chat")}${dim(` ${this.runtime.modelLabel}`)}${live > 0 ? fg(` ${live} live`, ACCENT) : ""}${dim(` ${mcp}`)}`;
1012
+ return truncateToWidth(left, width, "", true);
1013
+ }
1014
+ renderBody(width, height) {
1015
+ const { jobsWidth, transcriptWidth, contextWidth } = this.paneWidths(width);
1016
+ const jobs = jobsWidth > 0 ? padLines(this.renderJobs(jobsWidth, height), height, jobsWidth) : [];
1017
+ const transcript = padLines(this.renderTranscript(transcriptWidth, height), height, transcriptWidth)
1018
+ .map((line) => backgroundLine(line, transcriptWidth, TRANSCRIPT_BG));
1019
+ if (this.state.mode === "chat") {
1020
+ this.selection.update({ x: jobsWidth > 0 ? jobsWidth + 1 : 0, y: 2 + PANE_HEADING_ROWS, width: transcriptWidth, lines: transcript.slice(PANE_HEADING_ROWS), source: this.current });
1021
+ transcript.splice(PANE_HEADING_ROWS, height - PANE_HEADING_ROWS, ...this.selection.lines());
1022
+ }
1023
+ const context = contextWidth > 0 ? padLines(this.renderContext(contextWidth, height), height, contextWidth) : [];
1024
+ const lines = [];
1025
+ for (let index = 0; index < height; index++) {
1026
+ let line = jobsWidth > 0 ? `${jobs[index]}${dim("│")}${transcript[index]}` : transcript[index];
1027
+ if (contextWidth > 0)
1028
+ line += `${dim("│")}${context[index]}`;
1029
+ lines.push(truncateToWidth(line, width, "", true));
1030
+ }
1031
+ return lines;
1032
+ }
1033
+ renderJobs(width, height) {
1034
+ const live = this.rowsAll.filter((row) => row.live).length;
1035
+ const title = `${bold("JOBS")} ${dim(`${live} live`)}${this.state.filter.length > 0 ? ` ${dim(`/${this.state.filter}`)}` : ""}`;
1036
+ const lines = [truncateToWidth(title, width, "", true), ""];
1037
+ if (this.visible.length === 0) {
1038
+ lines.push(dim(this.state.filter.length > 0 ? ` No jobs match /${this.state.filter}.` : " No jobs. Ctrl-N starts one."));
1039
+ return lines;
1040
+ }
1041
+ const content = [];
1042
+ for (const [index, row] of this.visible.entries()) {
1043
+ if (index > 0)
1044
+ content.push("");
1045
+ const selected = row.id === this.state.selectedJobId;
1046
+ const marker = selected ? fg("▸", ACCENT) : " ";
1047
+ const id = `#${row.id}`.padEnd(6);
1048
+ const state = truncateToWidth(compactJobStatus(row.status), 9).padEnd(9);
1049
+ const age = row.startedAt === undefined ? "—" : compactDuration(Math.max(0, (row.endedAt ?? this.now()) - row.startedAt));
1050
+ const head = `${marker} ${selected ? bold(id) : id}${statusText(state)} ${dim(age.padStart(3))}`;
1051
+ content.push(truncateToWidth(head, width, "", true));
1052
+ const briefWidth = Math.max(4, width - 3);
1053
+ const origin = row.fork === undefined ? "" : `↳ ${row.fork.jobId === undefined ? "main" : `#${row.fork.jobId}`} · `;
1054
+ const labels = row.tags?.length ? `[${row.tags.join(", ")}] ` : "";
1055
+ const brief = truncateToWidth(`${labels}${origin}${row.brief.replace(/\s+/g, " ")}`, briefWidth, "…");
1056
+ content.push(selected ? ` ${fg(brief, TEXT)}` : dim(` ${brief}`));
1057
+ }
1058
+ const start = this.jobsOffset(height);
1059
+ if (this.jobsScroll !== undefined)
1060
+ this.jobsScroll = start;
1061
+ return [...lines, ...content.slice(start, start + Math.max(1, height - PANE_HEADING_ROWS))];
1062
+ }
1063
+ renderTranscript(width, height) {
1064
+ const target = targetLabel(this.state.target);
1065
+ const live = this.current?.live;
1066
+ const active = live?.generation !== undefined || live?.tools?.some((slot) => slot.status === "running") === true;
1067
+ const title = `${bold("TRANSCRIPT")} ${dim(target)}${active ? fg(" ● live", GREEN) : ""}${this.scroll > 0 ? dim(` ↑${this.scroll}`) : ""}`;
1068
+ const lines = [truncateToWidth(title, width, "", true), ""];
1069
+ const transcript = this.current;
1070
+ if (transcript === undefined) {
1071
+ lines.push(dim(" No conversation is available for this job yet."));
1072
+ return lines;
1073
+ }
1074
+ const contentHeight = Math.max(1, height - PANE_HEADING_ROWS);
1075
+ const all = this.transcriptLines(width);
1076
+ if (all.length === 0) {
1077
+ lines.push(dim(" No messages yet. Type below and press Enter."));
1078
+ return lines;
1079
+ }
1080
+ const offset = clampScroll(this.scroll, all.length, contentHeight);
1081
+ this.scroll = offset;
1082
+ const end = Math.max(contentHeight, all.length - offset);
1083
+ const start = Math.max(0, end - contentHeight);
1084
+ lines.push(...all.slice(start, end));
1085
+ return lines;
1086
+ }
1087
+ renderContext(width, height) {
1088
+ const content = this.contextLines(width);
1089
+ const viewport = Math.max(1, height - PANE_HEADING_ROWS);
1090
+ this.contextScroll = clampScroll(this.contextScroll, content.length, viewport);
1091
+ return [truncateToWidth(bold("CONTEXT"), width, "", true), "", ...content.slice(this.contextScroll, this.contextScroll + viewport)];
1092
+ }
1093
+ contextLines(width) {
1094
+ const target = this.state.target;
1095
+ const transcript = this.current;
1096
+ const usage = usageTotals(transcript?.usage);
1097
+ const live = transcript?.live;
1098
+ const rows = [];
1099
+ rows.push(["target", targetLabel(target)]);
1100
+ if (target.kind === "job") {
1101
+ const row = this.rowsAll.find((item) => item.id === target.id);
1102
+ rows.push(["status", row?.status ?? "unknown"]);
1103
+ const conversation = this.targetConversationId ?? row?.conversationId;
1104
+ rows.push(["conversation", conversation === undefined ? "…" : `#${conversation}`]);
1105
+ rows.push(["brief", row?.brief ?? "(unknown)"]);
1106
+ if (row?.tags?.length)
1107
+ rows.push(["tags", row.tags.join(", ")]);
1108
+ if (row?.fork !== undefined)
1109
+ rows.push(["fork from", `${row.fork.jobId === undefined ? "main" : `job #${row.fork.jobId}`} · entry #${row.fork.entryId}`]);
1110
+ if (row?.workspace !== undefined) {
1111
+ rows.push(["workspace", row.workspace.kind]);
1112
+ if (row.workspace.kind === "worktree")
1113
+ rows.push(["branch", truncateToWidth(row.workspace.branch, Math.max(1, width - 13), "…")], ["base commit", row.workspace.baseCommit.slice(0, 10)]);
1114
+ }
1115
+ if (row?.error !== undefined)
1116
+ rows.push(["error", row.error]);
1117
+ }
1118
+ else {
1119
+ rows.push(["status", live?.run === undefined ? "idle" : "busy"]);
1120
+ }
1121
+ rows.push(["turns", live?.run?.turns === undefined ? "—" : String(live.run.turns)]);
1122
+ const contextTokens = transcript?.contextTokens;
1123
+ const window = this.runtime.config.contextWindow;
1124
+ rows.push(["context", contextTokens === undefined
1125
+ ? "…"
1126
+ : `~${formatTokenCount(contextTokens)} / ${formatTokenCount(window)} (${contextPercent(contextTokens, window).toFixed(0)}%)`]);
1127
+ rows.push(["compact", `~${formatTokenCount(compactionLimit(window))}`]);
1128
+ rows.push(["spent", usage.tokens === 0 ? "—" : formatTokenCount(usage.tokens)]);
1129
+ if (usage.cost > 0)
1130
+ rows.push(["cost", `$${usage.cost.toFixed(3)}`]);
1131
+ rows.push(["queued", String(transcript?.inbox ?? 0)]);
1132
+ rows.push(["model", this.runtime.config.model ?? this.runtime.modelLabel]);
1133
+ rows.push(["thinking", this.runtime.config.thinkingLevel]);
1134
+ rows.push(["jobs", `${this.rowsAll.filter((row) => row.live).length} live`]);
1135
+ rows.push(["mcp", !this.runtime.mcpAttempted ? "off" : this.runtime.mcpConnected ? "connected" : "unavailable"]);
1136
+ rows.push(["config", shortenHome(this.runtime.config.configPath)]);
1137
+ rows.push(["store", shortenHome(this.runtime.storePath)]);
1138
+ const lines = [];
1139
+ for (const [label, value] of rows) {
1140
+ const prefix = `${label}:`.padEnd(13);
1141
+ const wrapped = wrapTextWithAnsi(value, Math.max(1, width - 13));
1142
+ wrapped.forEach((part, index) => {
1143
+ lines.push(index === 0 ? `${dim(prefix)}${part}` : `${" ".repeat(13)}${part}`);
1144
+ });
1145
+ }
1146
+ return lines;
1147
+ }
1148
+ renderStatus(width) {
1149
+ const target = targetLabel(this.state.target);
1150
+ const toast = this.toast;
1151
+ if (toast !== undefined && this.now() - toast.at < FLASH_MS) {
1152
+ return truncateToWidth(fg(` ${toast.kind === "error" ? "✗" : "·"} ${toast.text}`, toast.kind === "error" ? RED : YELLOW), width, "", true);
1153
+ }
1154
+ const activity = this.actionLabel === undefined ? "" : fg(` ⏳ ${this.actionLabel}`, YELLOW);
1155
+ const focus = dim(`focus ${this.state.focus}`);
1156
+ const contextTokens = this.current?.contextTokens;
1157
+ const window = this.runtime.config.contextWindow;
1158
+ const context = contextTokens === undefined
1159
+ ? "ctx …"
1160
+ : `ctx ~${formatTokenCount(contextTokens)}/${formatTokenCount(window)}`;
1161
+ const line = ` ${dim("target")} ${bold(target)} ${focus} ${dim(context)}${activity}`;
1162
+ return truncateToWidth(line, width, "", true);
1163
+ }
1164
+ composerPrefix() {
1165
+ switch (this.state.mode) {
1166
+ case "newJob": return "new job › ";
1167
+ case "compact": return `compact ${targetLabel(this.state.target)} focus › `;
1168
+ case "reset": return `reset ${targetLabel(this.state.target)} handoff › `;
1169
+ case "model": return "model filter › ";
1170
+ case "rollback": return "rollback file or number › ";
1171
+ case "filter": return "filter › ";
1172
+ case "help":
1173
+ case "inspector":
1174
+ case "confirmCancel":
1175
+ case "confirmReset":
1176
+ case "confirmQuit":
1177
+ case "confirmReboot":
1178
+ case "confirmRollback":
1179
+ case "confirmAbortMain":
1180
+ return "— › ";
1181
+ default: {
1182
+ const steer = this.state.steer ? " (steer)" : "";
1183
+ return `to ${targetLabel(this.state.target)}${steer} › `;
1184
+ }
1185
+ }
1186
+ }
1187
+ renderComposer(width) {
1188
+ const prefix = ` ${this.composerPrefix()}`;
1189
+ const active = this.state.focus === "composer"
1190
+ && this.state.mode !== "help"
1191
+ && this.state.mode !== "inspector"
1192
+ && !this.state.mode.startsWith("confirm");
1193
+ this.input.focused = active;
1194
+ const inner = Math.max(1, width - visibleWidth(prefix) - 1);
1195
+ const rendered = this.input.render(inner)[0] ?? "";
1196
+ const line = `${fg(prefix, active ? ACCENT : MUTED)}${rendered}`;
1197
+ const spacer = backgroundLine("", width, COMPOSER_BG);
1198
+ return [spacer, backgroundLine(line, width, COMPOSER_BG), spacer];
1199
+ }
1200
+ renderHint(width) {
1201
+ let hint;
1202
+ const separator = dim(" · ");
1203
+ if (this.quitArmedAt !== undefined && this.now() - this.quitArmedAt < QUIT_REPEAT_MS)
1204
+ hint = shortcut("CTRL-C", "again to quit");
1205
+ else if (this.state.mode === "help")
1206
+ hint = shortcut("ANY KEY", "closes help");
1207
+ else if (this.state.mode === "inspector")
1208
+ hint = [shortcut("E", "edit config"), shortcut("ESC", "closes"), fg("edits apply after restart", MUTED)].join(separator);
1209
+ else if (this.state.mode === "model")
1210
+ hint = [shortcut("↑ / ↓", "select"), shortcut("ENTER", "apply to all agents"), shortcut("ESC", "cancel")].join(separator);
1211
+ else if (this.state.mode === "rollback")
1212
+ hint = [shortcut("ENTER", "choose state file"), shortcut("ESC", "cancel")].join(separator);
1213
+ else if (this.state.mode === "confirmRollback")
1214
+ hint = [shortcut("Y", "restore"), shortcut("ENTER / N / ESC", "cancel")].join(separator);
1215
+ else if (this.state.mode === "confirmReboot")
1216
+ hint = [shortcut("Y", "reboot"), shortcut("ENTER / N / ESC", "cancel")].join(separator);
1217
+ else if (this.state.mode === "confirmCancel" || this.state.mode === "confirmReset" || this.state.mode === "confirmQuit" || this.state.mode === "confirmAbortMain")
1218
+ hint = [shortcut("Y / ENTER", "confirm"), shortcut("N / ESC", "cancel")].join(separator);
1219
+ else if (this.actionLabel !== undefined)
1220
+ hint = shortcut("CTRL-C", "stop waiting (work stays durable)");
1221
+ else if (this.state.focus === "composer")
1222
+ hint = [shortcut("ENTER", "send"), shortcut("CTRL-C ×2", "quit"), shortcut("TAB", "jobs"), shortcut("CTRL-T", "target"), shortcut("CTRL-N", "new job"), shortcut("CTRL-V", "paste image"), ...(this.attachments.length === 0 ? [] : [fg(`${this.attachments.length} attached`, YELLOW)])].join(separator);
1223
+ else if (this.state.focus === "jobs")
1224
+ hint = [shortcut("J/K", "select"), shortcut("ENTER", "open"), shortcut("N", "new"), shortcut("C", "cancel"), shortcut("M/SHIFT-R", "compact/reset"), shortcut("I", "info"), shortcut("TAB", "focus")].join(separator);
1225
+ else
1226
+ hint = [shortcut("J/K", "scroll"), shortcut("G/SHIFT-G", "oldest/newest"), shortcut("T", "tools"), shortcut("S", "send"), shortcut("C", "cancel"), shortcut("ESC", "main"), shortcut("TAB", "focus")].join(separator);
1227
+ if (this.scroll > 0 && this.state.focus === "transcript")
1228
+ hint += dim(` · ↑${this.scroll}`);
1229
+ return truncateToWidth(` ${hint}`, width, "", true);
1230
+ }
1231
+ renderHelp(width, height) {
1232
+ const bindings = [
1233
+ ["TAB / SHIFT-TAB", "cycle composer, jobs, transcript"],
1234
+ ["CTRL-T", "target main ↔ selected job"],
1235
+ ["CTRL-N", "new job brief"],
1236
+ ["ALT-S", "steer vs follow-up for the target"],
1237
+ ["CTRL-V", "paste an image into the composer (main only)"],
1238
+ ["ENTER", "send, open job, or confirm prompt"],
1239
+ ["[ / ]", "resize the jobs pane"],
1240
+ ["{ / }", "resize the context pane"],
1241
+ ["0", "reset pane widths"],
1242
+ ["J / K", "move job selection or scroll"],
1243
+ ["WHEEL", "scroll the pane under the pointer"],
1244
+ ["G / SHIFT-G", "jump to oldest / newest"],
1245
+ ["N / C / M / SHIFT-R", "new · cancel · compact · reset"],
1246
+ ["S / T / I / F / Y", "send-to · tools · inspector · finished · copy"],
1247
+ ["/", "filter jobs outside composer; commands inside"],
1248
+ ["CTRL-C", "stop waiting / clear prompt / close overlay"],
1249
+ ["CTRL-C ×2", "quit within 1.5s (confirms with live work)"],
1250
+ ];
1251
+ return this.panel("Help", [
1252
+ bold("Slash commands (composer)"),
1253
+ "/help · /info · /tasks · /task <id> · /log <id>",
1254
+ "/new [brief] · /send <id> <text> · /steer <id> <text>",
1255
+ "/cancel <id> · /compact [focus] · /reset [handoff]",
1256
+ "/model [id] · /provider [name] · /thinking [level] · /image <path> · /wait · /filter [query] · /rollback [path] · /reboot · /quit",
1257
+ "",
1258
+ ...bindings.map(([keys, description]) => shortcut(keys.padEnd(20), description)),
1259
+ "",
1260
+ "Jobs are background tasks; this TUI is the only store writer.",
1261
+ "Closing pauses jobs; the next run resumes them.",
1262
+ ], width, height);
1263
+ }
1264
+ renderModels(width, height) {
1265
+ const matches = this.matchingModels();
1266
+ const capacity = Math.max(1, height - 10);
1267
+ const start = Math.max(0, Math.min(this.modelIndex - Math.floor(capacity / 2), matches.length - capacity));
1268
+ const selected = matches[this.modelIndex];
1269
+ return this.panel(`Models — ${this.runtime.model.provider}`, [
1270
+ "Type to filter; Up/Down selects; Enter applies; Esc cancels.",
1271
+ "One model for main and all jobs. Session only; history is kept.", "",
1272
+ ...(this.modelLoading ? ["Loading models…"] : matches.length === 0 ? ["No matching models."] : matches.slice(start, start + capacity).map((model, index) => `${start + index === this.modelIndex ? "▸" : " "} ${this.runtime.config.providers.length > 1 ? model.lookup : model.id}${model.lookup === `${this.runtime.model.provider}/${this.runtime.model.modelId}` ? " (current)" : ""}`)),
1273
+ "",
1274
+ ...(selected === undefined ? [] : [`${selected.name} · context ${formatTokenCount(selected.contextWindow)} · output ${formatTokenCount(selected.maxTokens)}`]),
1275
+ ...(this.modelWarning === undefined ? [] : [this.modelWarning]),
1276
+ ], width, height);
1277
+ }
1278
+ renderInspector(width, height) {
1279
+ const usage = usageTotals(this.current?.usage);
1280
+ const lines = [
1281
+ ...(this.runtime.previousStateArchive === undefined ? [] : [`Previous state archive: ${this.runtime.previousStateArchive}`, ""]),
1282
+ ...(this.runtime.restoredFrom === undefined ? [] : [`Restored from: ${this.runtime.restoredFrom}`, ""]),
1283
+ ...describeConfig(this.runtime.config),
1284
+ "",
1285
+ `live jobs: ${this.rowsAll.filter((row) => row.live).length}`,
1286
+ `context: ~${formatTokenCount(this.current?.contextTokens ?? 0)} / ${formatTokenCount(this.runtime.config.contextWindow)} ` +
1287
+ `(compact at ~${formatTokenCount(compactionLimit(this.runtime.config.contextWindow))})`,
1288
+ `target spend: ${formatTokenCount(usage.tokens)} tokens${usage.cost > 0 ? `, $${usage.cost.toFixed(4)}` : ""}`,
1289
+ `job tools: ${this.runtime.jobExtensions.flatMap((extension) => extension.tools?.map((tool) => tool.name) ?? []).join(", ") || "(none)"}`,
1290
+ ...this.runtime.mcpNotes.slice(0, 8).map((note) => `mcp: ${note}`),
1291
+ "",
1292
+ "Edit the file with `durable-chat config edit`; restart to apply.",
1293
+ ];
1294
+ return this.panel("Inspector", lines, width, height);
1295
+ }
1296
+ renderConfirm(width, height) {
1297
+ const target = targetLabel(this.state.target);
1298
+ const lines = [];
1299
+ if (this.state.mode === "confirmCancel") {
1300
+ lines.push(`Cancel ${target}?`, "", "The job conversation and its transcript are retained.");
1301
+ }
1302
+ else if (this.state.mode === "confirmReset") {
1303
+ lines.push(`Reset ${target}?`, "", this.pendingResetHandoff === undefined ? "The next context starts empty." : `Handoff: ${this.pendingResetHandoff}`, "Raw history is retained.");
1304
+ }
1305
+ else if (this.state.mode === "confirmAbortMain") {
1306
+ lines.push("Abort the main run?", "", "Jobs are background tasks and are not cancelled by this.");
1307
+ }
1308
+ return this.panel("Confirm", lines, width, height);
1309
+ }
1310
+ panel(title, content, width, height) {
1311
+ const box = Math.max(30, Math.min(width - 2, 86));
1312
+ const inner = box - 4;
1313
+ const left = Math.max(0, Math.floor((width - box) / 2));
1314
+ const rows = [];
1315
+ rows.push(`${" ".repeat(left)}${dim("┌")} ${bold(title)} ${dim("─".repeat(Math.max(0, box - visibleWidth(title) - 3)))}${dim("┐")}`);
1316
+ for (const line of content.slice(0, Math.max(1, height - 2))) {
1317
+ const wrapped = wrapTextWithAnsi(line, inner);
1318
+ for (const part of wrapped) {
1319
+ rows.push(`${" ".repeat(left)}${dim("│")} ${truncateToWidth(part, inner, "", true)} ${dim("│")}`);
1320
+ }
1321
+ if (rows.length >= height - 1)
1322
+ break;
1323
+ }
1324
+ while (rows.length < height - 1) {
1325
+ rows.push(`${" ".repeat(left)}${dim("│")} ${" ".repeat(inner)} ${dim("│")}`);
1326
+ }
1327
+ rows.push(`${" ".repeat(left)}${dim("└")}${dim("─".repeat(Math.max(0, box - 2)))}${dim("┘")}`);
1328
+ return rows;
1329
+ }
1330
+ cycleFocus(backwards) {
1331
+ const order = this.lastWidth < 64 ? ["composer", "transcript"] : ["composer", "jobs", "transcript"];
1332
+ const index = Math.max(0, order.indexOf(this.state.focus));
1333
+ this.state.focus = order[(index + (backwards ? order.length - 1 : 1)) % order.length];
1334
+ this.input.focused = this.state.focus === "composer";
1335
+ if (this.state.focus === "jobs" && this.state.selectedJobId === undefined)
1336
+ this.state.selectedJobId = this.visible[0]?.id;
1337
+ this.renderSoon();
1338
+ }
1339
+ handleMouse(event) {
1340
+ if (event.type !== "wheel") {
1341
+ if (this.state.mode === "chat")
1342
+ this.selection.handle(event);
1343
+ // Never fall back to toolkit selection of the full, composited dashboard.
1344
+ return { handled: true, render: event.type !== "move" };
1345
+ }
1346
+ this.selection.reset();
1347
+ this.renderSoon();
1348
+ // Consume unused wheel events too, so the toolkit never scrolls the whole dashboard.
1349
+ const handled = { handled: true, render: false };
1350
+ const delta = Math.trunc(event.wheelDelta ?? 0);
1351
+ if (this.state.mode !== "chat" || !Number.isFinite(delta) || delta === 0
1352
+ || event.y < 2 + PANE_HEADING_ROWS || event.y >= 2 + this.bodyHeight()
1353
+ || event.x < 0 || event.x >= this.lastWidth)
1354
+ return handled;
1355
+ const { jobsWidth, transcriptWidth, contextWidth } = this.paneWidths(this.lastWidth);
1356
+ const transcriptStart = jobsWidth > 0 ? jobsWidth + 1 : 0;
1357
+ const contextStart = transcriptStart + transcriptWidth + 1;
1358
+ if (event.x < jobsWidth) {
1359
+ this.jobsScroll = clampScroll(this.jobsOffset(this.bodyHeight()) + delta, Math.max(0, this.visible.length * JOB_ROW_HEIGHT - 1), this.contentHeight());
1360
+ this.renderSoon();
1361
+ }
1362
+ else if (event.x >= transcriptStart && event.x < transcriptStart + transcriptWidth) {
1363
+ this.scrollBy(-delta);
1364
+ }
1365
+ else if (contextWidth > 0 && event.x >= contextStart) {
1366
+ this.contextScroll = clampScroll(this.contextScroll + delta, this.contextLines(contextWidth).length, this.contentHeight());
1367
+ this.renderSoon();
1368
+ }
1369
+ return handled;
1370
+ }
1371
+ handleInput(data) {
1372
+ this.selection.reset();
1373
+ this.renderSoon();
1374
+ if (matchesKey(data, "ctrl+c")) {
1375
+ this.interrupt();
1376
+ return;
1377
+ }
1378
+ this.disarmQuit();
1379
+ if (this.state.mode === "help") {
1380
+ this.state.mode = "chat";
1381
+ this.renderSoon();
1382
+ return;
1383
+ }
1384
+ if (this.state.mode === "inspector") {
1385
+ if (data === "e") {
1386
+ void this.editConfig();
1387
+ return;
1388
+ }
1389
+ if (matchesKey(data, "escape") || matchesKey(data, "enter") || data === "i") {
1390
+ this.state.mode = "chat";
1391
+ this.renderSoon();
1392
+ }
1393
+ return;
1394
+ }
1395
+ if (this.state.mode === "confirmReboot" || this.state.mode === "confirmRollback") {
1396
+ if (data === "y" || data === "Y")
1397
+ this.confirm();
1398
+ else if (data === "n" || data === "N" || matchesKey(data, "escape") || matchesKey(data, "enter"))
1399
+ this.cancelPrompt();
1400
+ return;
1401
+ }
1402
+ if (this.state.mode === "confirmCancel" || this.state.mode === "confirmReset" || this.state.mode === "confirmQuit" || this.state.mode === "confirmAbortMain") {
1403
+ if (data === "y" || data === "Y" || matchesKey(data, "enter"))
1404
+ this.confirm();
1405
+ else if (data === "n" || data === "N" || matchesKey(data, "escape"))
1406
+ this.cancelPrompt();
1407
+ return;
1408
+ }
1409
+ if (this.state.mode === "model") {
1410
+ if (matchesKey(data, "escape"))
1411
+ this.cancelPrompt();
1412
+ else if (matchesKey(data, "enter"))
1413
+ return this.submit();
1414
+ else if (matchesKey(data, "up"))
1415
+ this.modelIndex = Math.max(0, this.modelIndex - 1);
1416
+ else if (matchesKey(data, "down"))
1417
+ this.modelIndex = Math.min(Math.max(0, this.matchingModels().length - 1), this.modelIndex + 1);
1418
+ else {
1419
+ this.input.handleInput(data);
1420
+ this.modelIndex = 0;
1421
+ }
1422
+ this.renderSoon();
1423
+ return;
1424
+ }
1425
+ if (this.state.mode !== "chat") {
1426
+ if (matchesKey(data, "escape")) {
1427
+ this.cancelPrompt();
1428
+ return;
1429
+ }
1430
+ if (matchesKey(data, "enter"))
1431
+ return this.submit();
1432
+ this.input.handleInput(data);
1433
+ this.renderSoon();
1434
+ return;
1435
+ }
1436
+ if (matchesKey(data, "ctrl+t")) {
1437
+ void this.toggleTarget();
1438
+ return;
1439
+ }
1440
+ if (matchesKey(data, "ctrl+n")) {
1441
+ this.beginPrompt("newJob");
1442
+ return;
1443
+ }
1444
+ if (matchesKey(data, "alt+s")) {
1445
+ this.state.steer = !this.state.steer;
1446
+ this.flash(this.state.steer
1447
+ ? `${targetLabel(this.state.target)} input will steer the current run`
1448
+ : `${targetLabel(this.state.target)} input will queue as a follow-up`);
1449
+ return;
1450
+ }
1451
+ if (this.state.focus === "composer") {
1452
+ if (this.input.getValue().length === 0 && data === "?") {
1453
+ this.state.mode = "help";
1454
+ this.renderSoon();
1455
+ return;
1456
+ }
1457
+ if (matchesKey(data, "ctrl+v")) {
1458
+ return this.pasteAttachments();
1459
+ return;
1460
+ }
1461
+ if (matchesKey(data, "enter"))
1462
+ return this.submit();
1463
+ if (matchesKey(data, "tab")) {
1464
+ this.cycleFocus(false);
1465
+ return;
1466
+ }
1467
+ if (matchesKey(data, "shift+tab")) {
1468
+ this.cycleFocus(true);
1469
+ return;
1470
+ }
1471
+ if (matchesKey(data, "escape")) {
1472
+ if (this.input.getValue().length > 0)
1473
+ this.input.setValue("");
1474
+ else if (this.attachments.length > 0)
1475
+ this.attachments = [];
1476
+ else
1477
+ this.cycleFocus(false);
1478
+ this.renderSoon();
1479
+ return;
1480
+ }
1481
+ this.input.handleInput(data);
1482
+ this.renderSoon();
1483
+ return;
1484
+ }
1485
+ if (matchesKey(data, "tab")) {
1486
+ this.cycleFocus(false);
1487
+ return;
1488
+ }
1489
+ if (matchesKey(data, "shift+tab")) {
1490
+ this.cycleFocus(true);
1491
+ return;
1492
+ }
1493
+ if (matchesKey(data, "escape")) {
1494
+ if (this.state.target.kind === "job")
1495
+ void this.pinMain();
1496
+ this.state.focus = "composer";
1497
+ this.input.focused = true;
1498
+ this.renderSoon();
1499
+ return;
1500
+ }
1501
+ if (this.state.focus === "jobs") {
1502
+ this.jobsScroll = undefined;
1503
+ if (matchesKey(data, "down") || data === "j") {
1504
+ this.state.selectedJobId = moveSelection(this.visible, this.state.selectedJobId, 1);
1505
+ this.renderSoon();
1506
+ return;
1507
+ }
1508
+ if (matchesKey(data, "up") || data === "k") {
1509
+ this.state.selectedJobId = moveSelection(this.visible, this.state.selectedJobId, -1);
1510
+ this.renderSoon();
1511
+ return;
1512
+ }
1513
+ if (data === "g") {
1514
+ this.state.selectedJobId = this.visible[0]?.id;
1515
+ this.renderSoon();
1516
+ return;
1517
+ }
1518
+ if (data === "G") {
1519
+ this.state.selectedJobId = this.visible.at(-1)?.id;
1520
+ this.renderSoon();
1521
+ return;
1522
+ }
1523
+ if (matchesKey(data, "enter")) {
1524
+ void this.openSelected();
1525
+ return;
1526
+ }
1527
+ }
1528
+ else {
1529
+ if (matchesKey(data, "down") || data === "j") {
1530
+ this.scrollBy(-1);
1531
+ return;
1532
+ }
1533
+ if (matchesKey(data, "up") || data === "k") {
1534
+ this.scrollBy(1);
1535
+ return;
1536
+ }
1537
+ if (matchesKey(data, "pageDown")) {
1538
+ this.scrollBy(-this.contentHeight());
1539
+ return;
1540
+ }
1541
+ if (matchesKey(data, "pageUp")) {
1542
+ this.scrollBy(this.contentHeight());
1543
+ return;
1544
+ }
1545
+ if (data === "g") {
1546
+ this.scrollBy(Number.MAX_SAFE_INTEGER);
1547
+ return;
1548
+ }
1549
+ if (data === "G") {
1550
+ this.scroll = 0;
1551
+ this.renderSoon();
1552
+ return;
1553
+ }
1554
+ }
1555
+ if (data === "[") {
1556
+ this.resizeJobs(-2);
1557
+ return;
1558
+ }
1559
+ if (data === "]") {
1560
+ this.resizeJobs(2);
1561
+ return;
1562
+ }
1563
+ if (data === "{") {
1564
+ this.resizeContext(-2);
1565
+ return;
1566
+ }
1567
+ if (data === "}") {
1568
+ this.resizeContext(2);
1569
+ return;
1570
+ }
1571
+ if (data === "0") {
1572
+ this.state.jobsPane = undefined;
1573
+ this.state.contextPane = undefined;
1574
+ this.renderSoon();
1575
+ return;
1576
+ }
1577
+ if (data === "n") {
1578
+ this.beginPrompt("newJob");
1579
+ return;
1580
+ }
1581
+ if (data === "c") {
1582
+ this.requestCancel();
1583
+ return;
1584
+ }
1585
+ if (data === "m") {
1586
+ this.beginPrompt("compact");
1587
+ return;
1588
+ }
1589
+ if (data === "R") {
1590
+ this.requestReset();
1591
+ return;
1592
+ }
1593
+ if (data === "a") {
1594
+ this.requestAbortMain();
1595
+ return;
1596
+ }
1597
+ if (data === "s") {
1598
+ this.state.focus = "composer";
1599
+ this.input.focused = true;
1600
+ this.renderSoon();
1601
+ return;
1602
+ }
1603
+ if (data === "t") {
1604
+ this.state.toolsExpanded = !this.state.toolsExpanded;
1605
+ this.flash(this.state.toolsExpanded ? "tool output expanded" : "tool output collapsed");
1606
+ return;
1607
+ }
1608
+ if (data === "f") {
1609
+ this.state.showFinished = !this.state.showFinished;
1610
+ this.applyView();
1611
+ this.renderSoon();
1612
+ return;
1613
+ }
1614
+ if (data === "/") {
1615
+ this.beginPrompt("filter");
1616
+ this.input.setValue(this.state.filter);
1617
+ return;
1618
+ }
1619
+ if (data === "i") {
1620
+ this.state.mode = "inspector";
1621
+ this.renderSoon();
1622
+ return;
1623
+ }
1624
+ if (data === "?") {
1625
+ this.state.mode = "help";
1626
+ this.renderSoon();
1627
+ return;
1628
+ }
1629
+ if (data === "y") {
1630
+ this.copy();
1631
+ return;
1632
+ }
1633
+ if (data === "q") {
1634
+ this.requestQuit();
1635
+ }
1636
+ }
1637
+ }
1638
+ function contentText(content) {
1639
+ if (typeof content === "string")
1640
+ return content;
1641
+ if (!Array.isArray(content))
1642
+ return "";
1643
+ return content.flatMap((block) => {
1644
+ if (typeof block !== "object" || block === null)
1645
+ return [];
1646
+ const value = block;
1647
+ return value.type === "text" && typeof value.text === "string" ? [value.text] : [];
1648
+ }).join("\n");
1649
+ }
1650
+ function message(error) {
1651
+ return error instanceof Error ? error.message : String(error);
1652
+ }
1653
+ function compactDuration(ms) {
1654
+ if (!Number.isFinite(ms) || ms < 0)
1655
+ return "?";
1656
+ if (ms < 1000)
1657
+ return `${Math.round(ms)}ms`;
1658
+ const seconds = Math.round(ms / 1000);
1659
+ if (seconds < 60)
1660
+ return `${seconds}s`;
1661
+ const minutes = Math.floor(seconds / 60);
1662
+ if (minutes < 60)
1663
+ return `${minutes}m`;
1664
+ const hours = Math.floor(minutes / 60);
1665
+ if (hours < 24)
1666
+ return `${hours}h`;
1667
+ return `${Math.floor(hours / 24)}d`;
1668
+ }
1669
+ function compactJobStatus(status) {
1670
+ if (status.startsWith("handed off") || status.includes("handing off"))
1671
+ return "handoff";
1672
+ if (status.includes("completed"))
1673
+ return "done";
1674
+ if (status.includes("aborted"))
1675
+ return "aborted";
1676
+ if (status.includes("failed"))
1677
+ return "failed";
1678
+ if (status.includes("faulted"))
1679
+ return "faulted";
1680
+ if (status.includes("running"))
1681
+ return "running";
1682
+ if (status.includes("pending"))
1683
+ return "pending";
1684
+ if (status.includes("waiting"))
1685
+ return "wait";
1686
+ if (status.includes("sleeping"))
1687
+ return "sleep";
1688
+ if (status.includes("completing"))
1689
+ return "finish";
1690
+ if (status.includes("reporting"))
1691
+ return "report";
1692
+ if (status.includes("blocked"))
1693
+ return "blocked";
1694
+ return status;
1695
+ }