-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathChatView.logic.ts
More file actions
265 lines (246 loc) · 7.93 KB
/
ChatView.logic.ts
File metadata and controls
265 lines (246 loc) · 7.93 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
import {
ProjectId,
ProviderInteractionMode,
RuntimeMode,
type ModelSelection,
type ThreadId,
} from "@t3tools/contracts";
import { type FollowUpBehavior } from "@t3tools/contracts/settings";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import {
type ComposerImageAttachment,
type DraftThreadState,
type PersistedComposerImageAttachment,
type QueuedFollowUpDraft,
} from "../composerDraftStore";
import { Schema } from "effect";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
type TerminalContextDraft,
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const WORKTREE_BRANCH_PREFIX = "t3code";
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModelSelection: ModelSelection,
error: string | null,
): Thread {
return {
id: threadId,
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
modelSelection: fallbackModelSelection,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
session: null,
messages: [],
error,
createdAt: draftThread.createdAt,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
activities: [],
proposedPlans: [],
};
}
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
}
URL.revokeObjectURL(previewUrl);
}
export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
if (message.role !== "user" || !message.attachments) {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
if (message.role !== "user" || !message.attachments) {
return [];
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
export function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(reader.result);
return;
}
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
}
export function buildTemporaryWorktreeBranchName(): string {
// Keep the 8-hex suffix shape for backend temporary-branch detection.
const token = randomUUID().slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
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>;
}): {
trimmedPrompt: string;
sendableTerminalContexts: TerminalContextDraft[];
expiredTerminalContextCount: number;
hasSendableContent: boolean;
} {
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
const expiredTerminalContextCount =
options.terminalContexts.length - sendableTerminalContexts.length;
return {
trimmedPrompt,
sendableTerminalContexts,
expiredTerminalContextCount,
hasSendableContent:
trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 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 resolveFollowUpBehavior(
followUpBehavior: FollowUpBehavior,
invert: boolean,
): FollowUpBehavior {
if (!invert) {
return followUpBehavior;
}
return followUpBehavior === "queue" ? "steer" : "queue";
}
export function shouldInvertFollowUpBehaviorFromKeyEvent(
event: Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "shiftKey">,
platform = navigator.platform,
): boolean {
if (!event.shiftKey || event.altKey) {
return false;
}
if (isMacPlatform(platform)) {
return event.metaKey && !event.ctrlKey;
}
return event.ctrlKey && !event.metaKey;
}
export function followUpBehaviorShortcutLabel(platform = navigator.platform): string {
return isMacPlatform(platform) ? "Cmd+Shift+Enter" : "Ctrl+Shift+Enter";
}
export function buildQueuedFollowUpDraft(input: {
prompt: string;
attachments: ReadonlyArray<PersistedComposerImageAttachment>;
terminalContexts: ReadonlyArray<TerminalContextDraft>;
modelSelection: ModelSelection;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
createdAt: string;
}): QueuedFollowUpDraft {
return {
id: randomUUID(),
createdAt: input.createdAt,
prompt: input.prompt,
attachments: [...input.attachments],
terminalContexts: input.terminalContexts.map((context) => ({ ...context })),
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
};
}
export function canAutoDispatchQueuedFollowUp(input: {
phase: "disconnected" | "connecting" | "ready" | "running";
queuedFollowUpCount: number;
isConnecting: boolean;
isSendBusy: boolean;
isRevertingCheckpoint: boolean;
hasThreadError: boolean;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
}): boolean {
return (
input.phase === "ready" &&
input.queuedFollowUpCount > 0 &&
!input.isConnecting &&
!input.isSendBusy &&
!input.isRevertingCheckpoint &&
!input.hasThreadError &&
!input.hasPendingApproval &&
!input.hasPendingUserInput
);
}
export function describeQueuedFollowUp(
followUp: Pick<QueuedFollowUpDraft, "attachments" | "prompt" | "terminalContexts">,
): string {
const trimmedPrompt = stripInlineTerminalContextPlaceholders(followUp.prompt).trim();
if (trimmedPrompt.length > 0) {
return trimmedPrompt;
}
if (followUp.attachments.length > 0) {
return followUp.attachments.length === 1
? "1 image attached"
: `${followUp.attachments.length} images attached`;
}
if (followUp.terminalContexts.length > 0) {
return followUp.terminalContexts.length === 1
? (followUp.terminalContexts[0]?.terminalLabel ?? "1 terminal context")
: `${followUp.terminalContexts.length} terminal contexts`;
}
return "Follow-up";
}