forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatView.logic.ts
More file actions
463 lines (421 loc) · 13.6 KB
/
ChatView.logic.ts
File metadata and controls
463 lines (421 loc) · 13.6 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
import {
type EnvironmentId,
type MessageId,
ProjectId,
type ModelSelection,
type ProviderKind,
type ScopedThreadRef,
type ThreadId,
type TurnId,
} from "@marcode/contracts";
import {
type ChatImageAttachment,
type ChatMessage,
type SessionPhase,
type Thread,
} from "../types";
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { selectThreadByRef, selectThreadsAcrossEnvironments, useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
type TerminalContextDraft,
} from "../lib/terminalContext";
import { INLINE_JIRA_CONTEXT_PLACEHOLDER, type JiraTaskDraft } from "../lib/jiraContext";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "marcode:last-invoked-script-by-project";
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
const WORKTREE_BRANCH_PREFIX = "marcode";
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModelSelection: ModelSelection,
error: string | null,
additionalDirectories: readonly string[] = [],
): Thread {
return {
id: threadId,
environmentId: draftThread.environmentId,
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
modelSelection: fallbackModelSelection,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
session: null,
messages: [],
error,
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
additionalDirectories: [...additionalDirectories],
turnDiffSummaries: [],
activities: [],
proposedPlans: [],
hydrated: true,
};
}
export function shouldWriteThreadErrorToCurrentServerThread(input: {
serverThread:
| {
environmentId: EnvironmentId;
id: ThreadId;
}
| null
| undefined;
routeThreadRef: ScopedThreadRef;
targetThreadId: ThreadId;
}): boolean {
return Boolean(
input.serverThread &&
input.targetThreadId === input.routeThreadRef.threadId &&
input.serverThread.environmentId === input.routeThreadRef.environmentId &&
input.serverThread.id === input.targetThreadId,
);
}
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;
}
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 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;
}
}
function stripInlineJiraContextPlaceholders(prompt: string): string {
return prompt.replaceAll(INLINE_JIRA_CONTEXT_PLACEHOLDER, "");
}
export function deriveComposerSendState(options: {
prompt: string;
imageCount: number;
terminalContexts: ReadonlyArray<TerminalContextDraft>;
jiraTaskContexts?: ReadonlyArray<JiraTaskDraft>;
quotedContextCount?: number;
}): {
trimmedPrompt: string;
sendableTerminalContexts: TerminalContextDraft[];
expiredTerminalContextCount: number;
hasSendableContent: boolean;
} {
const trimmedPrompt = stripInlineJiraContextPlaceholders(
stripInlineTerminalContextPlaceholders(options.prompt),
).trim();
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
const expiredTerminalContextCount =
options.terminalContexts.length - sendableTerminalContexts.length;
const jiraTaskContexts = options.jiraTaskContexts ?? [];
const quotedContextCount = options.quotedContextCount ?? 0;
return {
trimmedPrompt,
sendableTerminalContexts,
expiredTerminalContextCount,
hasSendableContent:
trimmedPrompt.length > 0 ||
options.imageCount > 0 ||
sendableTerminalContexts.length > 0 ||
jiraTaskContexts.length > 0 ||
quotedContextCount > 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 threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
);
}
export function deriveLockedProvider(input: {
thread: Thread | null | undefined;
selectedProvider: ProviderKind | null;
threadProvider: ProviderKind | null;
}): ProviderKind | null {
if (!threadHasStarted(input.thread)) {
return null;
}
return input.thread?.session?.provider ?? input.threadProvider ?? input.selectedProvider ?? null;
}
export async function waitForStartedServerThread(
threadRef: ScopedThreadRef,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => selectThreadByRef(useStore.getState(), threadRef);
const thread = getThread();
if (threadHasStarted(thread)) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
unsubscribe();
resolve(result);
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(selectThreadByRef(state, threadRef))) {
return;
}
finish(true);
});
if (threadHasStarted(getThread())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, timeoutMs);
});
}
export interface LocalDispatchSnapshot {
startedAt: string;
preparingWorktree: boolean;
latestTurnTurnId: TurnId | null;
latestTurnRequestedAt: string | null;
latestTurnStartedAt: string | null;
latestTurnCompletedAt: string | null;
}
export function createLocalDispatchSnapshot(
activeThread: Thread | undefined,
options?: { preparingWorktree?: boolean },
): LocalDispatchSnapshot {
const latestTurn = activeThread?.latestTurn ?? null;
return {
startedAt: new Date().toISOString(),
preparingWorktree: Boolean(options?.preparingWorktree),
latestTurnTurnId: latestTurn?.turnId ?? null,
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
latestTurnStartedAt: latestTurn?.startedAt ?? null,
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
};
}
export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
latestTurn: Thread["latestTurn"] | null;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
threadError: string | null | undefined;
}): boolean {
if (!input.localDispatch) {
return false;
}
if (
input.phase === "running" ||
input.hasPendingApproval ||
input.hasPendingUserInput ||
Boolean(input.threadError)
) {
return true;
}
const latestTurn = input.latestTurn ?? null;
return (
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null)
);
}
export const EDIT_REVERT_SYNC_TIMEOUT_MS = 15_000;
export type RevertOutcome =
| { ok: true }
| { ok: false; reason: "timeout" }
| { ok: false; reason: "revert-failed"; detail: string };
export async function waitForRevertOutcome(
threadId: ThreadId,
messageId: MessageId,
timeoutMs = EDIT_REVERT_SYNC_TIMEOUT_MS,
): Promise<RevertOutcome> {
const getThread = () =>
selectThreadsAcrossEnvironments(useStore.getState()).find((thread) => thread.id === threadId);
const initialActivityCount = getThread()?.activities.length ?? 0;
const threadContainsMessage = () => {
const thread = getThread();
return thread
? thread.messages.some((m: Thread["messages"][number]) => m.id === messageId)
: false;
};
const detectRevertFailure = (): string | null => {
const thread = getThread();
if (!thread) return null;
const newActivities = thread.activities.slice(initialActivityCount);
const failure = newActivities.find(
(a: Thread["activities"][number]) => a.kind === "checkpoint.revert.failed",
);
if (!failure) return null;
const payload = failure.payload as Record<string, unknown> | null;
return (typeof payload?.detail === "string" ? payload.detail : null) ?? failure.summary;
};
if (!threadContainsMessage()) {
return { ok: true };
}
return await new Promise<RevertOutcome>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: RevertOutcome) => {
if (settled) return;
settled = true;
if (timeoutId !== null) globalThis.clearTimeout(timeoutId);
unsubscribe();
resolve(result);
};
const unsubscribe = useStore.subscribe(() => {
if (!threadContainsMessage()) {
finish({ ok: true });
return;
}
const failureDetail = detectRevertFailure();
if (failureDetail !== null) {
finish({ ok: false, reason: "revert-failed", detail: failureDetail });
}
});
if (!threadContainsMessage()) {
finish({ ok: true });
return;
}
const immediateFailure = detectRevertFailure();
if (immediateFailure !== null) {
finish({ ok: false, reason: "revert-failed", detail: immediateFailure });
return;
}
timeoutId = globalThis.setTimeout(() => {
finish({ ok: false, reason: "timeout" });
}, timeoutMs);
});
}
export async function materializeMessageImageAttachmentForEdit(
attachment: ChatImageAttachment,
): Promise<ComposerImageAttachment | null> {
if (!attachment.previewUrl) {
return null;
}
try {
const response = await fetch(attachment.previewUrl);
const blob = await response.blob();
const file = new File([blob], attachment.name, { type: attachment.mimeType });
const previewUrl = URL.createObjectURL(file);
return {
type: "image" as const,
id: attachment.id,
file,
name: attachment.name,
previewUrl,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
};
} catch {
return null;
}
}