-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathtui-command-handlers.ts
More file actions
852 lines (832 loc) · 27 KB
/
Copy pathtui-command-handlers.ts
File metadata and controls
852 lines (832 loc) · 27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Implements TUI slash command handlers and backend action dispatch.
import { randomUUID } from "node:crypto";
import type { Component, SelectItem, TUI } from "@earendil-works/pi-tui";
import type { SessionsPatchResult } from "../../packages/gateway-protocol/src/index.js";
import { modelKey } from "../agents/model-ref-shared.js";
import { normalizeGroupActivation } from "../auto-reply/group-activation.js";
import {
formatGoalContinuationPrompt,
formatGoalResumeContinuationPrompt,
parseGoalCommand,
} from "../auto-reply/reply/commands-goal.js";
import {
formatThinkingLevels,
normalizeUsageDisplay,
resolveResponseUsageMode,
} from "../auto-reply/thinking.js";
import { isChatStopCommandText } from "../gateway/chat-abort.js";
import { formatRelativeTimestamp } from "../infra/format-time/format-relative.ts";
import { normalizeAgentId } from "../routing/session-key.js";
import { helpText, parseCommand } from "./commands.js";
import type { ChatLog } from "./components/chat-log.js";
import {
createFilterableSelectList,
createSearchableSelectList,
createSettingsList,
} from "./components/selectors.js";
import type { TuiBackend, TuiSessionMutationResult } from "./tui-backend.js";
import { sanitizeRenderableText } from "./tui-formatters.js";
import {
TUI_RECENT_SESSIONS_ACTIVE_MINUTES,
TUI_SESSION_PICKER_LIMIT,
} from "./tui-session-list-policy.js";
import { formatStatusSummary } from "./tui-status-summary.js";
import type {
AgentSummary,
GatewayStatusSummary,
TuiResult,
TuiOptions,
TuiStateAccess,
} from "./tui-types.js";
type CommandHandlerContext = {
client: TuiBackend;
chatLog: ChatLog;
tui: TUI;
opts: TuiOptions;
state: TuiStateAccess;
deliverDefault: boolean;
openOverlay: (component: Component) => void;
closeOverlay: () => void;
refreshSessionInfo: () => Promise<void>;
loadHistory: () => Promise<void>;
setSession: (key: string) => Promise<void>;
setEmptySession: (key: string) => Promise<void>;
refreshAgents: () => Promise<void>;
abortActive: (params?: { preferActive?: boolean }) => Promise<void>;
setActivityStatus: (text: string) => void;
formatSessionKey: (key: string) => string;
applySessionInfoFromPatch: (result: SessionsPatchResult) => void;
applySessionMutationResult: (result?: TuiSessionMutationResult | null) => boolean;
noteLocalRunId?: (runId: string) => void;
noteLocalBtwRunId?: (runId: string) => void;
forgetLocalRunId?: (runId: string) => void;
forgetLocalBtwRunId?: (runId: string) => void;
consumeCompletedRunForPendingSend?: (runId: string) => boolean;
isRunObserved?: (runId: string) => boolean;
flushPendingHistoryRefreshIfIdle?: () => void;
runAuthFlow?: (params: {
provider?: string;
}) => Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>;
requestExit: (result?: Partial<TuiResult>) => void;
};
function isBtwCommand(text: string): boolean {
return /^\/(?:btw|side)(?::|\s|$)/i.test(text.trim());
}
function isSlashStopCommand(text: string): boolean {
const trimmed = text.trim();
return trimmed.startsWith("/") && isChatStopCommandText(trimmed);
}
function goalContinuationPrompt(text: string): string | null {
const parsed = parseGoalCommand(text);
if (!parsed) {
return null;
}
const action = parsed.action;
if (action === "start" || action === "set" || action === "create") {
return formatGoalContinuationPrompt(parsed.text) || null;
}
if (action === "resume") {
return formatGoalResumeContinuationPrompt(parsed.text);
}
return null;
}
export function createCommandHandlers(context: CommandHandlerContext) {
const {
client,
chatLog,
tui,
opts,
state,
deliverDefault,
openOverlay,
closeOverlay,
refreshSessionInfo,
loadHistory,
setSession,
setEmptySession,
refreshAgents,
abortActive,
setActivityStatus,
formatSessionKey,
applySessionInfoFromPatch,
applySessionMutationResult,
noteLocalRunId,
noteLocalBtwRunId,
forgetLocalRunId,
forgetLocalBtwRunId,
consumeCompletedRunForPendingSend,
isRunObserved,
flushPendingHistoryRefreshIfIdle,
runAuthFlow,
requestExit,
} = context;
const setAgent = async (id: string) => {
state.currentAgentId = normalizeAgentId(id);
await setSession("");
chatLog.addSystem(`agent set to ${state.currentAgentId}; use /crestodian to return`);
};
const closeOverlayAndRender = () => {
closeOverlay();
tui.requestRender();
};
const hasTrackedAbortTarget = () =>
Boolean(state.activeChatRunId || state.pendingChatRunId || state.pendingOptimisticUserMessage);
const currentSessionPatchTarget = () => ({
key: state.currentSessionKey,
...(state.currentSessionKey === "global" ? { agentId: state.currentAgentId } : {}),
});
const openSelector = (
selector: {
onSelect?: (item: SelectItem) => void;
onCancel?: () => void;
},
onSelect: (value: string) => Promise<void>,
) => {
selector.onSelect = (item) => {
void (async () => {
await onSelect(item.value);
closeOverlayAndRender();
})();
};
selector.onCancel = closeOverlayAndRender;
openOverlay(selector as Component);
tui.requestRender();
};
const openModelSelector = async () => {
try {
chatLog.addSystem("loading models...");
tui.requestRender();
const models = await client.listModels();
if (models.length === 0) {
chatLog.addSystem("no models available");
tui.requestRender();
return;
}
const items = models.map((model) => {
const ref = modelKey(model.provider, model.id);
return {
value: ref,
label: ref,
description: model.name && model.name !== model.id ? model.name : "",
};
});
const selector = createSearchableSelectList(items, 9);
openSelector(selector, async (value) => {
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
model: value,
});
chatLog.addSystem(`model set to ${value}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`model set failed: ${String(err)}`);
}
});
} catch (err) {
chatLog.addSystem(`model list failed: ${String(err)}`);
tui.requestRender();
}
};
const openAgentSelector = async () => {
await refreshAgents();
if (state.agents.length === 0) {
chatLog.addSystem("no agents found");
tui.requestRender();
return;
}
const items = state.agents.map((agent: AgentSummary) => ({
value: agent.id,
label: agent.name ? `${agent.id} (${agent.name})` : agent.id,
description: agent.id === state.agentDefaultId ? "default" : "",
}));
const selector = createSearchableSelectList(items, 9);
openSelector(selector, async (value) => {
await setAgent(value);
});
};
const openContextModeSelector = () => {
const items = [
{
value: "list",
label: "list",
description: "Short context breakdown",
},
{
value: "detail",
label: "detail",
description: "Per-file, per-tool, per-skill, and system prompt size",
},
{
value: "json",
label: "json",
description: "Machine-readable context report",
},
];
const selector = createSearchableSelectList(items, 9);
openSelector(selector, async (value) => {
await sendMessage(`/context ${value}`);
});
};
const openSessionSelector = async () => {
try {
const result = await client.listSessions({
limit: TUI_SESSION_PICKER_LIMIT,
activeMinutes: TUI_RECENT_SESSIONS_ACTIVE_MINUTES,
includeGlobal: false,
includeUnknown: false,
includeDerivedTitles: true,
includeLastMessage: true,
agentId: state.currentAgentId,
});
const items = result.sessions.map((session) => {
const title = session.derivedTitle ?? session.displayName;
const formattedKey = formatSessionKey(session.key);
// Avoid redundant "title (key)" when title matches key
const label = title && title !== formattedKey ? `${title} (${formattedKey})` : formattedKey;
// Build description: time + message preview
const timePart = session.updatedAt
? formatRelativeTimestamp(session.updatedAt, { dateFallback: true, fallback: "" })
: "";
const preview = session.lastMessagePreview?.replace(/\s+/g, " ").trim();
const description =
timePart && preview ? `${timePart} · ${preview}` : (preview ?? timePart);
return {
value: session.key,
label,
description,
searchText: [
session.displayName,
session.label,
session.subject,
session.sessionId,
session.key,
session.lastMessagePreview,
]
.filter(Boolean)
.join(" "),
};
});
const selector = createFilterableSelectList(items, 9);
openSelector(selector, async (value) => {
await setSession(value);
});
} catch (err) {
chatLog.addSystem(`sessions list failed: ${String(err)}`);
tui.requestRender();
}
};
const openSettings = () => {
const items = [
{
id: "tools",
label: "Tool output",
currentValue: state.toolsExpanded ? "expanded" : "collapsed",
values: ["collapsed", "expanded"],
},
{
id: "thinking",
label: "Show thinking",
currentValue: state.showThinking ? "on" : "off",
values: ["off", "on"],
},
];
const settings = createSettingsList(
items,
(id, value) => {
if (id === "tools") {
state.toolsExpanded = value === "expanded";
chatLog.setToolsExpanded(state.toolsExpanded);
}
if (id === "thinking") {
state.showThinking = value === "on";
void loadHistory();
}
tui.requestRender();
},
() => {
closeOverlay();
tui.requestRender();
},
);
openOverlay(settings);
tui.requestRender();
};
const handleCommand = async (raw: string) => {
const { name, args } = parseCommand(raw);
if (!name) {
return;
}
switch (name) {
case "help":
chatLog.addSystem(
helpText({
local: opts.local,
provider: state.sessionInfo.modelProvider,
model: state.sessionInfo.model,
}),
);
break;
case "auth": {
if (!runAuthFlow) {
chatLog.addSystem("auth login is only available in local embedded mode");
break;
}
if (state.activeChatRunId || state.pendingOptimisticUserMessage) {
chatLog.addSystem("abort the current run before /auth");
break;
}
const provider = args.trim() || state.sessionInfo.modelProvider || undefined;
chatLog.addSystem(
provider
? `opening auth flow for ${provider}; TUI will resume when it exits`
: "opening auth flow; TUI will resume when it exits",
);
tui.requestRender();
setActivityStatus("auth");
try {
const result = await runAuthFlow({ provider });
await refreshSessionInfo();
if (result.exitCode === 0 && !result.signal) {
chatLog.addSystem(
provider ? `auth flow finished for ${provider}` : "auth flow finished",
);
setActivityStatus("idle");
} else {
const failureSuffix = result.signal
? ` (signal ${result.signal})`
: typeof result.exitCode === "number"
? ` (exit ${String(result.exitCode)})`
: "";
chatLog.addSystem(`auth flow failed${failureSuffix}`);
setActivityStatus("error");
}
} catch (err) {
chatLog.addSystem(`auth flow failed: ${sanitizeRenderableText(String(err))}`);
setActivityStatus("error");
}
break;
}
case "gateway-status":
try {
const status = await client.getGatewayStatus();
if (typeof status === "string") {
chatLog.addSystem(status);
break;
}
if (status && typeof status === "object") {
const lines = formatStatusSummary(status as GatewayStatusSummary);
for (const line of lines) {
chatLog.addSystem(line);
}
break;
}
chatLog.addSystem("status: unknown response");
} catch (err) {
chatLog.addSystem(`status failed: ${String(err)}`);
}
break;
case "agent":
if (!args) {
await openAgentSelector();
} else {
await setAgent(args);
}
break;
case "agents":
await openAgentSelector();
break;
case "context":
if (!args) {
openContextModeSelector();
} else {
await sendMessage(raw);
}
break;
case "goal":
if (opts.local === true && client.runGoalCommand) {
try {
const result = await client.runGoalCommand({
sessionKey: state.currentSessionKey,
agentId: state.currentAgentId,
command: raw,
});
chatLog.addSystem(result.text);
await refreshSessionInfo();
const continuation = goalContinuationPrompt(raw);
if (continuation) {
await sendMessage(continuation);
}
} catch (err) {
chatLog.addSystem(`goal failed: ${sanitizeRenderableText(String(err))}`);
}
} else {
await sendMessage(raw);
}
break;
case "crestodian":
chatLog.addSystem(
args ? `returning to Crestodian with request: ${args}` : "returning to Crestodian",
);
requestExit({
exitReason: "return-to-crestodian",
...(args ? { crestodianMessage: args } : {}),
});
break;
case "session":
if (!args) {
await openSessionSelector();
} else {
await setSession(args);
}
break;
case "sessions":
await openSessionSelector();
break;
case "model":
if (!args) {
await openModelSelector();
} else {
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
model: args,
});
const resolvedModel = result.resolved?.model;
const resolvedProvider = result.resolved?.modelProvider;
const resolvedModelRef = resolvedModel
? resolvedProvider
? modelKey(resolvedProvider, resolvedModel)
: resolvedModel
: args;
chatLog.addSystem(`model set to ${resolvedModelRef}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`model set failed: ${String(err)}`);
}
}
break;
case "models":
await openModelSelector();
break;
case "think":
if (!args) {
const levels =
state.sessionInfo.thinkingLevels?.map((level) => level.label).join("|") ||
formatThinkingLevels(state.sessionInfo.modelProvider, state.sessionInfo.model, "|");
chatLog.addSystem(`usage: /think <${levels}>`);
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
thinkingLevel: args,
});
chatLog.addSystem(`thinking set to ${args}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`think failed: ${String(err)}`);
}
break;
case "verbose":
if (!args) {
chatLog.addSystem("usage: /verbose <on|off>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
verboseLevel: args,
});
chatLog.addSystem(`verbose set to ${args}`);
applySessionInfoFromPatch(result);
if (args === "off") {
chatLog.clearTools();
await refreshSessionInfo();
} else {
await loadHistory();
}
} catch (err) {
chatLog.addSystem(`verbose failed: ${String(err)}`);
}
break;
case "trace":
if (!args) {
chatLog.addSystem("usage: /trace <on|off>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
traceLevel: args,
});
chatLog.addSystem(`trace set to ${args}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`trace failed: ${String(err)}`);
}
break;
case "fast":
if (!args || args === "status") {
chatLog.addSystem(`fast mode: ${state.sessionInfo.fastMode ? "on" : "off"}`);
break;
}
if (args !== "on" && args !== "off") {
chatLog.addSystem("usage: /fast <status|on|off>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
fastMode: args === "on",
});
chatLog.addSystem(`fast mode ${args === "on" ? "enabled" : "disabled"}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`fast failed: ${String(err)}`);
}
break;
case "reasoning":
if (!args) {
chatLog.addSystem("usage: /reasoning <on|off>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
reasoningLevel: args,
});
chatLog.addSystem(`reasoning set to ${args}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`reasoning failed: ${String(err)}`);
}
break;
case "usage": {
const normalized = args ? normalizeUsageDisplay(args) : undefined;
if (args && !normalized) {
chatLog.addSystem("usage: /usage <off|tokens|full>");
break;
}
const currentRaw = state.sessionInfo.responseUsage;
const current = resolveResponseUsageMode(currentRaw);
const next =
normalized ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
responseUsage: next === "off" ? null : next,
});
chatLog.addSystem(`usage footer: ${next}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`usage failed: ${String(err)}`);
}
break;
}
case "elevated":
if (!args) {
chatLog.addSystem("usage: /elevated <on|off|ask|full>");
break;
}
if (!["on", "off", "ask", "full"].includes(args)) {
chatLog.addSystem("usage: /elevated <on|off|ask|full>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
elevatedLevel: args,
});
chatLog.addSystem(`elevated set to ${args}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`elevated failed: ${String(err)}`);
}
break;
case "activation": {
if (!args) {
chatLog.addSystem("usage: /activation <mention|always>");
break;
}
const activation = normalizeGroupActivation(args);
if (!activation) {
chatLog.addSystem("usage: /activation <mention|always>");
break;
}
try {
const result = await client.patchSession({
...currentSessionPatchTarget(),
groupActivation: activation,
});
chatLog.addSystem(`activation set to ${activation}`);
applySessionInfoFromPatch(result);
await refreshSessionInfo();
} catch (err) {
chatLog.addSystem(`activation failed: ${String(err)}`);
}
break;
}
case "new":
try {
// Clear token counts immediately to avoid stale display (#1523)
state.sessionInfo.inputTokens = null;
state.sessionInfo.outputTokens = null;
state.sessionInfo.totalTokens = null;
tui.requestRender();
// Generate unique session key to isolate this TUI client (#39217)
// This ensures /new creates a fresh session that doesn't broadcast
// to other connected TUI clients sharing the original session key.
const uniqueKey = `tui-${randomUUID()}`;
await setEmptySession(uniqueKey);
chatLog.addSystem(`new session: ${uniqueKey}`);
} catch (err) {
chatLog.addSystem(`new session failed: ${sanitizeRenderableText(String(err))}`);
}
break;
case "reset":
try {
// Clear token counts immediately to avoid stale display (#1523)
state.sessionInfo.inputTokens = null;
state.sessionInfo.outputTokens = null;
state.sessionInfo.totalTokens = null;
tui.requestRender();
const result = await client.resetSession(
state.currentSessionKey,
name,
state.currentSessionKey === "global" ? { agentId: state.currentAgentId } : undefined,
);
if (applySessionMutationResult(result)) {
await refreshSessionInfo();
} else {
await loadHistory();
}
chatLog.addSystem(`session ${state.currentSessionKey} reset`);
} catch (err) {
chatLog.addSystem(`reset failed: ${sanitizeRenderableText(String(err))}`);
}
break;
case "abort":
await abortActive();
break;
case "stop":
if (hasTrackedAbortTarget()) {
await abortActive({ preferActive: true });
break;
}
await sendMessage(raw);
break;
case "settings":
openSettings();
break;
case "exit":
case "quit":
requestExit();
break;
default:
await sendMessage(raw);
break;
}
tui.requestRender();
};
const sendMessage = async (text: string) => {
if (!state.isConnected) {
chatLog.addSystem(
opts.local
? "local runtime not ready — message not sent"
: "not connected to gateway — message not sent",
);
setActivityStatus("disconnected");
tui.requestRender();
return;
}
const isBtw = isBtwCommand(text);
const busy = Boolean(
state.activeChatRunId || state.pendingChatRunId || state.pendingOptimisticUserMessage,
);
if (
hasTrackedAbortTarget() &&
(isSlashStopCommand(text) || (busy && isChatStopCommandText(text)))
) {
await abortActive({ preferActive: true });
return;
}
if (
!isBtw &&
(state.pendingChatRunId ||
state.pendingOptimisticUserMessage ||
(opts.local !== true && state.activeChatRunId))
) {
chatLog.addSystem("agent is busy — press Esc to abort before sending a new message");
tui.requestRender();
return;
}
const runId = randomUUID();
try {
if (!isBtw) {
if (
opts.local === true &&
state.activeChatRunId &&
!state.pendingChatRunId &&
!state.pendingOptimisticUserMessage
) {
chatLog.reserveAssistantSlot(state.activeChatRunId);
}
chatLog.addPendingUser(runId, text);
state.pendingSubmitDraft = { runId, text };
noteLocalRunId?.(runId);
state.pendingOptimisticUserMessage = true;
setActivityStatus("sending");
} else {
noteLocalBtwRunId?.(runId);
}
tui.requestRender();
const sendResult = await client.sendChat({
sessionKey: state.currentSessionKey,
...(state.currentSessionKey === "global" ? { agentId: state.currentAgentId } : {}),
sessionId: state.currentSessionId,
message: text,
thinking: opts.thinking,
deliver: deliverDefault,
timeoutMs: opts.timeoutMs,
runId,
});
if (!isBtw) {
const acceptedRunId = sendResult.runId || runId;
const acceptedRunAlreadyCompleted =
acceptedRunId !== runId && (consumeCompletedRunForPendingSend?.(acceptedRunId) ?? false);
if (acceptedRunId !== runId) {
forgetLocalRunId?.(runId);
if (!acceptedRunAlreadyCompleted) {
noteLocalRunId?.(acceptedRunId);
}
if (state.pendingSubmitDraft?.runId === runId) {
// If the accepted run already emitted events, it is registered;
// re-arming the draft would let a later abort drop a row whose
// reply already rendered.
state.pendingSubmitDraft = isRunObserved?.(acceptedRunId)
? null
: { runId: acceptedRunId, text };
}
chatLog.rekeyPendingUser(runId, acceptedRunId);
}
if (state.pendingOptimisticUserMessage) {
if (acceptedRunAlreadyCompleted) {
if (state.pendingSubmitDraft?.runId === acceptedRunId) {
state.pendingSubmitDraft = null;
}
state.pendingOptimisticUserMessage = false;
state.pendingChatRunId = null;
setActivityStatus("idle");
flushPendingHistoryRefreshIfIdle?.();
} else {
state.pendingChatRunId = acceptedRunId;
setActivityStatus("waiting");
}
tui.requestRender();
}
}
} catch (err) {
if (isBtw) {
forgetLocalBtwRunId?.(runId);
}
if (!isBtw && state.activeChatRunId) {
forgetLocalRunId?.(state.activeChatRunId);
}
if (!isBtw) {
forgetLocalRunId?.(runId);
}
if (!isBtw) {
state.pendingOptimisticUserMessage = false;
state.pendingChatRunId = null;
state.activeChatRunId = null;
if (state.pendingSubmitDraft?.runId === runId) {
state.pendingSubmitDraft = null;
}
chatLog.dropPendingUser(runId);
}
chatLog.addSystem(`${isBtw ? "btw failed" : "send failed"}: ${String(err)}`);
if (!isBtw) {
setActivityStatus("error");
}
tui.requestRender();
}
};
return {
handleCommand,
sendMessage,
openModelSelector,
openAgentSelector,
openSessionSelector,
openSettings,
setAgent,
};
}