Repository navigation
Expand file tree
/
Copy pathChatView.logic.ts
More file actions
1697 lines (1593 loc) · 60.1 KB
/
Copy pathChatView.logic.ts
File metadata and controls
1697 lines (1593 loc) · 60.1 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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts";
import {
deriveLatestThreadRun,
deriveThreadRuntime,
} from "@t3tools/client-runtime/state/thread-execution";
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import {
latestUnheldRun,
usageLimitRunPresentedAsLatest,
} from "@t3tools/shared/orchestrationV2ThreadError";
import * as Option from "effect/Option";
import type { SetStateAction } from "react";
import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model";
import { getProviderModelCapabilities } from "../providerModels";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import type {
EnvironmentThread,
ThreadStructure,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
ANTIGRAVITY_DEFAULT_MODEL,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
type AssetCreateUrlInput,
type AssetCreateUrlResult,
type ChatFileAttachment,
type CommandId,
type EnvironmentId,
isProviderDriverKind,
ProjectId,
type MessageId,
type ModelSelection,
type OrchestrationMessageContext,
type PreviewAnnotationPayload,
type ProviderInteractionMode,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
type ScopedProjectRef,
type ScopedThreadRef,
type ThreadContextRecord,
type ThreadId,
type ThreadLinkedPullRequest,
type RunId,
type WorktreeSetupSnapshot,
} from "@t3tools/contracts";
import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
import * as DateTime from "effect/DateTime";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { videoMimeType } from "@t3tools/shared/video";
import {
appendCodexArtifactTemplateUsePrompt,
codexArtifactTemplateUsePrompt,
type CodexArtifactTemplate,
} from "@t3tools/shared/codexArtifactTemplates";
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
type ChatMessage,
isImageAttachment,
type SessionPhase,
type Thread,
type TurnDiffSummary,
} from "../types";
import {
type ComposerFileAttachment,
type ComposerImageAttachment,
type DraftId,
type DraftThreadState,
} from "../composerDraftStore";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadShells, environmentThreadDetails } from "../state/threads";
import { waitForAtomValue } from "../state/waitForAtomValue";
import {
filterTerminalContextsWithText,
formatTerminalContextLabel,
type TerminalContextDraft,
} from "../lib/terminalContext";
import {
removeInlineContextReference,
stripInlineContextReferences,
} from "~/lib/composerContextReferences";
import {
previewAnnotationContextLabel,
reviewCommentContextLabel,
terminalContextReference,
} from "../lib/composerContextRecords";
import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";
import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
import type { DraftThreadEnvMode } from "../composerDraftStore";
import { collapseExpandedComposerCursor, type ComposerSubmissionIntent } from "../composer-logic";
import type { ReviewCommentContext } from "../reviewCommentContext";
import { derivePhase, type TimelineEntry } from "../session-logic";
import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";
import type { DesktopPreviewOverlay } from "../previewStateStore";
import type { RightPanelSurface } from "../rightPanelStore";
import {
NO_PROVIDER_MODEL_SELECTION,
resolveSelectableProviderInstanceEntry,
type ProviderInstanceEntry,
} from "../providerInstances";
type ThreadProjection = EnvironmentThread["projection"];
type ThreadStructureRow = ThreadStructure["visibleTurnItems"][number];
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
export function agentControlledBrowserCloseConfirmation(
surfaces: readonly RightPanelSurface[],
desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
): string | null {
const activeBrowserCount = surfaces.filter(
(surface) =>
surface.kind === "preview" &&
surface.resourceId !== null &&
desktopByTabId[surface.resourceId]?.controller === "agent",
).length;
if (activeBrowserCount === 0) return null;
if (activeBrowserCount === 1) {
return [
"Close browser while the agent is using it?",
"The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
].join("\n");
}
return [
`Close ${activeBrowserCount} browsers while the agent is using them?`,
"The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
].join("\n");
}
export function shouldRenderPreviewMiniPlayer(
source: PreviewMiniPlayerSource | null,
renderedRightPanelSurface: RightPanelSurface | null,
): boolean {
if (source === null) return false;
if (source.kind === "browser") {
return !(
renderedRightPanelSurface?.kind === "preview" &&
renderedRightPanelSurface.resourceId === source.tabId
);
}
return !(
renderedRightPanelSurface?.kind === "device" &&
renderedRightPanelSurface.target?.hostId === source.hostId &&
renderedRightPanelSurface.target.deviceId === source.deviceId
);
}
export function shouldOpenProactivePullRequest(
previousTargetKey: string | null | undefined,
targetKey: string | null,
): boolean {
return targetKey !== null && targetKey !== previousTargetKey;
}
interface ProactivePanelObservation {
threadKey: string;
runningTurnId: RunId | null | undefined;
targetKey: string | null | undefined;
userActionTurnId: RunId | null;
userActionRevision: number;
}
export function observeProactivePanelUserChoice(
previous: ProactivePanelObservation | null,
input: { threadKey: string; runningTurnId: RunId | null; userActionRevision: number },
): ProactivePanelObservation {
const sameThread = previous?.threadKey === input.threadKey;
const newTurn =
sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
return {
threadKey: input.threadKey,
runningTurnId: sameThread ? previous.runningTurnId : undefined,
targetKey: sameThread ? previous.targetKey : undefined,
userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
userActionRevision:
!sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
};
}
export function shouldRetargetThreadPullRequestPanel(
previous: ThreadLinkedPullRequest | null,
current: ThreadLinkedPullRequest | null,
surface: RightPanelSurface | null,
): boolean {
if (previous === null || current === null || surface?.kind !== "pull-request") return false;
const previousRepository = previous.repository.toLowerCase();
return (
(previous.projectId !== current.projectId ||
previousRepository !== current.repository.toLowerCase() ||
previous.number !== current.number) &&
surface.projectId === previous.projectId &&
surface.repository.toLowerCase() === previousRepository &&
surface.number === previous.number
);
}
export function shouldOpenProactiveTurnDiff(input: {
previousRunningTurnId: RunId | null | undefined;
runningTurnId: RunId | null;
settledTurnId: RunId | null;
turnCompleted: boolean;
}): boolean {
return (
input.runningTurnId === null &&
input.turnCompleted &&
input.settledTurnId !== null &&
(input.previousRunningTurnId === undefined ||
input.settledTurnId === input.previousRunningTurnId)
);
}
export function resolveProactiveTurnDiffAction(input: {
checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
isGitRepo: boolean | undefined;
}): "defer" | "ignore" | "open" {
if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
if (input.isGitRepo === undefined) return "defer";
if (
!input.isGitRepo ||
input.checkpoint.status !== "ready" ||
input.checkpoint.files.length === 0
) {
return "ignore";
}
const changedLines = input.checkpoint.files.reduce(
(total, file) => total + file.additions + file.deletions,
0,
);
return input.checkpoint.files.length >= 3 || changedLines >= 50 ? "open" : "ignore";
}
/** Mark reactivated Diff tabs to preserve review scope. Already-active tabs must not leave a marker for
* the next open. */
export function resolveExplicitDiffOpenOnActivate(input: {
readonly surfaceKind: RightPanelSurface["kind"];
readonly diffOpen: boolean;
readonly activeThreadRef: ScopedThreadRef;
}): ScopedThreadRef | null {
return input.surfaceKind === "diff" && !input.diffOpen ? input.activeThreadRef : null;
}
export function codexArtifactTemplatePromptToAppend(
currentDraft: string,
template: CodexArtifactTemplate,
): string | null {
return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
? null
: codexArtifactTemplateUsePrompt(template);
}
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function shouldDockDraftHeroForSubmission(input: {
isDraftHeroState: boolean;
activeThreadKey: string | null;
submissionIntent: ComposerSubmissionIntent;
}): boolean {
return (
input.submissionIntent === "foreground" &&
input.isDraftHeroState &&
input.activeThreadKey !== null
);
}
export function shouldReleaseTimelineAnchorForToolActivity(input: {
anchorMessageId: MessageId | null;
liveFollowEnabled: boolean;
runningTurnId: RunId | null;
timelineEntries: ReadonlyArray<TimelineEntry>;
}): boolean {
if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
return false;
}
return input.timelineEntries.some((timelineEntry) => {
if (timelineEntry.kind !== "work" || timelineEntry.entry.runId !== input.runningTurnId) {
return false;
}
const entry = timelineEntry.entry;
return (
entry.tone === "tool" ||
entry.itemType !== undefined ||
entry.requestKind !== undefined ||
(entry.command?.trim().length ?? 0) > 0
);
});
}
export {
findRecordedWorktreeSetup,
resolveVisibleWorktreeSetup,
} from "@t3tools/client-runtime/worktree-setup";
export function resolveWorktreeSetupProgress(input: {
threadId: ThreadId;
localPreparing: boolean;
runStatus: NonNullable<Thread["latestRun"]>["status"] | undefined;
latest: WorktreeSetupSnapshot | null | undefined;
held: WorktreeSetupSnapshot | null;
}) {
const latest = input.latest?.threadId === input.threadId ? input.latest : null;
const held = input.held?.threadId === input.threadId ? input.held : null;
const snapshot = latest && (!held || latest.sequence >= held.sequence) ? latest : held;
return {
snapshot,
isPreparingWorktree:
input.localPreparing ||
input.runStatus === "preparing" ||
(snapshot?.phase === "running" && !worktreeSetupAgentStarted(snapshot)),
};
}
export function resolveDraftHeroState(input: {
isLocalDraftThread: boolean;
hasTimelineEntries: boolean;
isWorking: boolean;
draftHeroDockRequested: boolean;
backgroundSubmissionPending: boolean;
hasWorktreeSetupCard?: boolean;
}): boolean {
if (input.hasWorktreeSetupCard) {
return false;
}
if (input.backgroundSubmissionPending) {
return true;
}
return (
input.isLocalDraftThread &&
!input.hasTimelineEntries &&
!input.isWorking &&
!input.draftHeroDockRequested
);
}
/** Remounting or initially emptying LegendList flashes the chat pane, even for cached threads. */
export type HeldThreadTimeline<T extends readonly unknown[]> = {
threadKey: string | null;
entries: T;
markdownCwd?: string | null;
workspaceRoot?: string | null;
};
const MAX_REMEMBERED_THREAD_TIMELINES = 16;
let rememberedThreadTimelines = new Map<string, HeldThreadTimeline<readonly unknown[]>>();
let rememberedThreadTimelineOrder: string[] = [];
let lastReadyThreadKey: string | null = null;
function rememberThreadTimelineEntries(held: HeldThreadTimeline<readonly unknown[]>): void {
if (held.threadKey === null) {
return;
}
rememberedThreadTimelines.set(held.threadKey, held);
rememberedThreadTimelineOrder = [
...rememberedThreadTimelineOrder.filter((key) => key !== held.threadKey),
held.threadKey,
];
while (rememberedThreadTimelineOrder.length > MAX_REMEMBERED_THREAD_TIMELINES) {
const evicted = rememberedThreadTimelineOrder.shift();
if (evicted !== undefined) {
rememberedThreadTimelines.delete(evicted);
}
}
lastReadyThreadKey = held.threadKey;
}
export function rememberReadyThreadTimeline<T extends readonly unknown[]>(
held: HeldThreadTimeline<T>,
): void {
if (held.threadKey === null || held.entries.length === 0) {
return;
}
rememberThreadTimelineEntries(held);
}
export function peekRememberedThreadTimeline<T extends readonly unknown[]>(
threadKey: string | null,
): T | null {
if (threadKey === null) {
return null;
}
return (rememberedThreadTimelines.get(threadKey)?.entries as T | undefined) ?? null;
}
export function peekHeldThreadTimeline<
T extends readonly unknown[],
>(): HeldThreadTimeline<T> | null {
if (lastReadyThreadKey === null) {
return null;
}
const held = rememberedThreadTimelines.get(lastReadyThreadKey);
if (held === undefined || held.entries.length === 0) {
return null;
}
return held as HeldThreadTimeline<T>;
}
export function resetHeldThreadTimeline(): void {
rememberedThreadTimelines = new Map();
rememberedThreadTimelineOrder = [];
lastReadyThreadKey = null;
}
export function threadKeysShareEnvironment(left: string | null, right: string | null): boolean {
if (left === null || right === null) {
return false;
}
const leftRef = parseScopedThreadKey(left);
const rightRef = parseScopedThreadKey(right);
return leftRef !== null && rightRef !== null && leftRef.environmentId === rightRef.environmentId;
}
export function isPaintOnlyThreadTimeline(
displayThreadKey: string | null,
activeThreadKey: string | null,
): boolean {
return (
displayThreadKey !== null && activeThreadKey !== null && displayThreadKey !== activeThreadKey
);
}
export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input: {
loading: boolean;
activeThreadKey: string | null;
nextEntries: T;
rememberedForActive?: T | null;
lastReady?: HeldThreadTimeline<T> | null;
}): { entries: T; displayThreadKey: string | null } {
if (input.nextEntries.length > 0) {
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
}
const rememberedForActive =
input.rememberedForActive ?? peekRememberedThreadTimeline<T>(input.activeThreadKey);
if (input.loading && rememberedForActive !== null && rememberedForActive.length > 0) {
return { entries: rememberedForActive, displayThreadKey: input.activeThreadKey };
}
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
}
export function startNewThreadForProject(
projectRef: ScopedProjectRef | null,
handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
): boolean {
if (projectRef === null) return false;
void handleNewThread(projectRef);
return true;
}
export function resolveThreadMetadataUpdateForNextTurn(input: {
currentModelSelection: ModelSelection;
nextModelSelection?: ModelSelection;
currentBranch: string | null;
nextBranch?: string;
}): {
modelSelection?: ModelSelection;
branch?: string;
worktreePath?: null;
} | null {
const nextModelSelection = input.nextModelSelection;
const modelSelectionChanged =
nextModelSelection !== undefined &&
(nextModelSelection.model !== input.currentModelSelection.model ||
nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
JSON.stringify(nextModelSelection.options ?? null) !==
JSON.stringify(input.currentModelSelection.options ?? null));
const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
if (!modelSelectionChanged && !branchChanged) {
return null;
}
return {
...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
};
}
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModelSelection: ModelSelection,
): Thread {
const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
return presentThreadShell(draftThread.environmentId, {
id: threadId,
projectId: draftThread.projectId,
title: "New thread",
providerInstanceId: fallbackModelSelection.instanceId,
modelSelection: fallbackModelSelection,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
activeProviderThreadId: null,
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
forkedFrom: null,
createdBy: "user",
creationSource: "web",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: null,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: timestamp,
updatedAt: timestamp,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
});
}
export function resolveComposerProviderSelection(input: {
entries: ReadonlyArray<ProviderInstanceEntry>;
candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
lockedProvider: ProviderDriverKind | null;
lockedInstanceId: ProviderInstanceId | null | undefined;
}) {
const requestedInstanceId = input.candidateInstanceIds.find(
(candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
);
const requestedDriverKind =
input.lockedProvider ??
input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
input.entries[0]?.driverKind ??
ProviderDriverKind.make("unconfigured");
const lockedContinuationGroupKey = input.lockedProvider
? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
?.continuationGroupKey ?? null)
: null;
// Missing metadata must not move Antigravity history into another Google profile.
const requiresExactInstance =
input.lockedProvider === "antigravity" &&
input.lockedInstanceId != null &&
lockedContinuationGroupKey === null;
const compatibleEntries = input.entries.filter(
(entry) =>
(!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
(!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
(!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
);
const selectedProviderEntry =
input.candidateInstanceIds
.map((candidate) =>
compatibleEntries.find(
(entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
),
)
.find((entry) => entry !== undefined) ??
resolveSelectableProviderInstanceEntry(
compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
undefined,
) ??
resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
const unavailableProviderInstanceId = selectedProviderEntry
? undefined
: input.lockedProvider
? (input.lockedInstanceId ?? requestedInstanceId)
: requestedInstanceId;
return {
selectedProviderEntry,
requestedDriverKind,
lockedContinuationGroupKey,
unavailableProviderInstanceId,
};
}
export function resolveComposerInteractionMode(input: {
planModeEnabled: boolean;
provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
interactionMode: ProviderInteractionMode;
}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
const enabled =
input.planModeEnabled &&
input.provider != null &&
input.provider.showInteractionModeToggle !== false;
return {
enabled,
interactionMode: enabled ? input.interactionMode : "default",
};
}
export function getAntigravitySendBlockReason(
provider:
| Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
| null
| undefined,
model: string,
): string | null {
if (provider?.driver !== "antigravity") return null;
if (!provider.installed) {
return "Install Antigravity in provider settings before sending.";
}
if (provider.auth.status === "unauthenticated") {
return "Sign in to Antigravity in provider settings before sending.";
}
const slug = model.trim();
if (slug.length === 0) return "Choose an Antigravity model before sending.";
if (provider.auth.status === "unknown") return null;
if (provider.models.length === 0) {
return "Refresh Antigravity models in provider settings before sending.";
}
if (
provider.status === "ready" &&
slug !== ANTIGRAVITY_DEFAULT_MODEL &&
!provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
) {
return "That Antigravity model is no longer available. Choose another model.";
}
return null;
}
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<string>;
openThreadIds: ReadonlyArray<string>;
activeThreadId: string | null;
activeThreadTerminalOpen: boolean;
maxHiddenThreadCount?: number;
}): string[] {
const openThreadIdSet = new Set(input.openThreadIds);
const hiddenThreadIds = input.currentThreadIds.filter(
(threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
);
const maxHiddenThreadCount = Math.max(
0,
input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
);
const nextThreadIds =
hiddenThreadIds.length > maxHiddenThreadCount
? hiddenThreadIds.slice(-maxHiddenThreadCount)
: hiddenThreadIds;
if (
input.activeThreadId &&
input.activeThreadTerminalOpen &&
!nextThreadIds.includes(input.activeThreadId)
) {
nextThreadIds.push(input.activeThreadId);
}
return nextThreadIds;
}
// Null identifies the project checkout when a launch or session is known.
export function resolveTerminalWorktreePath(input: {
launchContext: { readonly worktreePath: string | null } | null;
summary: { readonly worktreePath: string | null } | null;
threadWorktreePath: string | null;
}): string | null {
if (input.launchContext !== null) return input.launchContext.worktreePath;
if (input.summary !== null) return input.summary.worktreePath;
return input.threadWorktreePath;
}
export async function resolveFileAttachmentUrl(input: {
attachment: ChatFileAttachment;
environmentId: EnvironmentId;
httpBaseUrl: string;
createAssetUrl: (input: {
environmentId: EnvironmentId;
input: AssetCreateUrlInput;
}) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
}): Promise<string> {
const { attachment } = input;
const result = await input.createAssetUrl({
environmentId: input.environmentId,
input: {
resource: {
_tag: "attachment",
attachmentId: attachment.id,
fileName: attachment.name,
mimeType: videoMimeType(attachment) ?? attachment.mimeType,
},
},
});
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
if (url === null) throw new Error("The environment returned an invalid attachment URL.");
return url;
}
export async function prepareRevertedMessageAttachments(input: {
message: ChatMessage;
environmentId: EnvironmentId;
httpBaseUrl: string;
createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
}): Promise<File[]> {
return Promise.all(
(input.message.attachments ?? []).map(async (attachment) => {
if (attachment.type !== "image" && attachment.type !== "file") {
throw new Error("This message has an attachment that cannot be restored.");
}
const result = await input.createAssetUrl({
environmentId: input.environmentId,
input: {
resource: {
_tag: "attachment",
attachmentId: attachment.id,
fileName: attachment.name,
mimeType: attachment.mimeType,
},
},
});
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
if (url === null) throw new Error("The environment returned an invalid attachment URL.");
const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
}),
);
}
export function timelineHasEphemeralPreviewUrls(
entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
): boolean {
return entries.some(
(entry) =>
entry.kind === "message" &&
entry.message !== undefined &&
collectUserMessageBlobPreviewUrls(entry.message).length > 0,
);
}
export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
if (message.role !== "user" || !message.attachments) {
return [];
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (!isImageAttachment(attachment)) continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
export { readFileAsDataUrl } from "../lib/imageCompression";
export { resolveSendEnvMode } from "@t3tools/shared/projectSettings";
export function resolveBackgroundDraftWorkspaceOptions(input: {
envMode: DraftThreadEnvMode;
branch: string | null;
startFromOrigin: boolean;
}): {
envMode: DraftThreadEnvMode;
branch: string | null;
worktreePath: null;
startFromOrigin: boolean;
} {
return {
envMode: input.envMode,
branch: input.branch,
worktreePath: null,
startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
};
}
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
try {
return {
...image,
previewUrl: URL.createObjectURL(image.file),
};
} catch {
return image;
}
}
export function deriveComposerSendState(options: {
prompt: string;
imageCount: number;
terminalContexts: ReadonlyArray<TerminalContextDraft>;
elementContextCount?: number;
}): {
trimmedPrompt: string;
sendableTerminalContexts: TerminalContextDraft[];
expiredTerminalContextCount: number;
hasSendableContent: boolean;
} {
const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
const expiredTerminalContextCount =
options.terminalContexts.length - sendableTerminalContexts.length;
const elementContextCount = options.elementContextCount ?? 0;
return {
trimmedPrompt,
sendableTerminalContexts,
expiredTerminalContextCount,
hasSendableContent:
trimmedPrompt.length > 0 ||
options.imageCount > 0 ||
sendableTerminalContexts.length > 0 ||
elementContextCount > 0,
};
}
export function buildExpiredTerminalContextToastCopy(
expiredTerminalContextCount: number,
variant: "omitted" | "empty",
): { title: string; description: string } {
const count = Math.max(1, Math.floor(expiredTerminalContextCount));
const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
if (variant === "empty") {
return {
title: `${noun} won't be sent`,
description: "Remove it or re-add it to include terminal output.",
};
}
return {
title: `${noun} omitted from message`,
description: "Re-add it if you want that terminal output included.",
};
}
export function branchMismatchKey(
threadId: string | null,
mismatch: { threadBranch: string; currentBranch: string } | null,
): string | null {
if (!threadId || !mismatch) {
return null;
}
return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
}
// Composer autofocus makes focus unreliable as draft intent.
export function shouldShowBranchMismatchBanner(input: {
hasMismatch: boolean;
isDismissed: boolean;
composerHasContent: boolean;
wasShownForCurrentMismatch: boolean;
}): boolean {
if (!input.hasMismatch || input.isDismissed) {
return false;
}
return input.composerHasContent || input.wasShownForCurrentMismatch;
}
export function shouldShowPlanFollowUpPrompt(input: {
pendingUserInputCount: number;
interactionMode: ProviderInteractionMode;
latestTurnSettled: boolean;
hasActionableProposedPlan: boolean;
hasComposerAttachments: boolean;
}): boolean {
return (
input.pendingUserInputCount === 0 &&
input.interactionMode === "plan" &&
input.latestTurnSettled &&
input.hasActionableProposedPlan &&
!input.hasComposerAttachments
);
}
// A typed `/compact`, with or without instructions, is already the compaction. Queueing a
// bare one ahead of it would run an uninstructed compaction first and charge for two.
const COMPACT_COMMAND_PATTERN = /^\/compact(?:\s|$)/i;
const sessionDismissedBranchMismatchKeys = new Set<string>();
export function dismissBranchMismatchForSession(key: string): void {
sessionDismissedBranchMismatchKeys.add(key);
}
export function isBranchMismatchDismissedForSession(key: string | null): boolean {
return key !== null && sessionDismissedBranchMismatchKeys.has(key);
}
// Remember non-Git checkouts to avoid flashing the branch strip before delayed Git status arrives.
const sessionCheckoutIsRepo = new Map<string, boolean>();
function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
return JSON.stringify([environmentId, cwd]);
}
export function rememberCheckoutIsRepo(
environmentId: EnvironmentId,
cwd: string,
isRepo: boolean,
): void {
sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
}
export function recallCheckoutIsRepo(
environmentId: EnvironmentId,
cwd: string | null,
): boolean | undefined {
return cwd === null
? undefined
: sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
}
function threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
}
export function threadShellHasStarted(
shell:
| Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
| null
| undefined,
): boolean {
return Boolean(
shell &&
(shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
);
}
// Imported history lacks a session until its first prompt; resolve its instance before locking the driver.
export function deriveLockedProvider(input: {
thread: Thread | null | undefined;
selectedProvider: string | null;
threadProvider: string | null;
providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
}): ProviderDriverKind | null {
if (!threadHasStarted(input.thread)) {
return null;
}
const sessionProvider = input.thread?.runtime?.providerName ?? null;
if (sessionProvider && isProviderDriverKind(sessionProvider)) {
return sessionProvider;
}
// Missing catalog entries must not switch a started thread's driver.
const threadProvider =
input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
input.threadProvider;
const selectedProvider =
input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
input.selectedProvider;
const narrowedThreadProvider =
threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
const narrowedSelectedProvider =
selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
}
export function getStartedThreadModelChangeBlockReason(input: {
providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
hasStartedSession: boolean;
supportsProviderSwitchingViaHandoff?: boolean;
currentModelSelection: ModelSelection;
currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
nextModelSelection: ModelSelection;
}): { title: string; description: string } | null {
if (!input.hasStartedSession) {
return null;
}
const currentModelSelection = {
...input.currentModelSelection,
instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
};
if (
currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
currentModelSelection.model === input.nextModelSelection.model
) {
return null;
}
if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
if (input.supportsProviderSwitchingViaHandoff === true) {
return null;
}
return {
title: "Start a new chat to switch providers",
description: "This thread does not support switching providers after it has started.",
};
}
const currentProvider = input.providers.find(
(snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
);
const nextProvider = input.providers.find(
(snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
);
if (
currentProvider?.requiresNewThreadForModelChange !== true &&
nextProvider?.requiresNewThreadForModelChange !== true
) {
return null;
}
return {