Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatView.logic.ts

162 lines4.9 KB

1import { ProjectId, type ThreadId } from "@t3tools/contracts";
2import { type ChatMessage, type Thread } from "../types";
3import { randomUUID } from "~/lib/utils";
4import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
5import { Schema } from "effect";
6import {
7 filterTerminalContextsWithText,
8 stripInlineTerminalContextPlaceholders,
9 type TerminalContextDraft,
10} from "../lib/terminalContext";
11​
12export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
13const WORKTREE_BRANCH_PREFIX = "t3code";
14​
15export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
16​
17export function buildLocalDraftThread(
18 threadId: ThreadId,
19 draftThread: DraftThreadState,
20 fallbackModel: string,
21 error: string | null,
22): Thread {
23 return {
24 id: threadId,
25 codexThreadId: null,
26 projectId: draftThread.projectId,
27 title: "New thread",
28 model: fallbackModel,
29 runtimeMode: draftThread.runtimeMode,
30 interactionMode: draftThread.interactionMode,
31 session: null,
32 messages: [],
33 error,
34 createdAt: draftThread.createdAt,
35 latestTurn: null,
36 lastVisitedAt: draftThread.createdAt,
37 branch: draftThread.branch,
38 worktreePath: draftThread.worktreePath,
39 turnDiffSummaries: [],
40 activities: [],
41 proposedPlans: [],
42 };
44​
45export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
46 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
47 return;
48 }
49 URL.revokeObjectURL(previewUrl);
51​
52export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
53 if (message.role !== "user" || !message.attachments) {
54 return;
55 }
56 for (const attachment of message.attachments) {
57 if (attachment.type !== "image") {
58 continue;
59 }
60 revokeBlobPreviewUrl(attachment.previewUrl);
61 }
63​
64export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
65 if (message.role !== "user" || !message.attachments) {
66 return [];
67 }
68 const previewUrls: string[] = [];
69 for (const attachment of message.attachments) {
70 if (attachment.type !== "image") continue;
71 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
72 previewUrls.push(attachment.previewUrl);
73 }
74 return previewUrls;
76​
77export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
78​
79export interface PullRequestDialogState {
80 initialReference: string | null;
81 key: number;
83​
84export function readFileAsDataUrl(file: File): Promise<string> {
85 return new Promise((resolve, reject) => {
86 const reader = new FileReader();
87 reader.addEventListener("load", () => {
88 if (typeof reader.result === "string") {
89 resolve(reader.result);
90 return;
91 }
92 reject(new Error("Could not read image data."));
93 });
94 reader.addEventListener("error", () => {
95 reject(reader.error ?? new Error("Failed to read image."));
96 });
97 reader.readAsDataURL(file);
98 });
100​
101export function buildTemporaryWorktreeBranchName(): string {
102 // Keep the 8-hex suffix shape for backend temporary-branch detection.
103 const token = randomUUID().slice(0, 8).toLowerCase();
104 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
106​
107export function cloneComposerImageForRetry(
108 image: ComposerImageAttachment,
109): ComposerImageAttachment {
110 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
111 return image;
112 }
113 try {
114 return {
115 ...image,
116 previewUrl: URL.createObjectURL(image.file),
117 };
118 } catch {
119 return image;
120 }
122​
123export function deriveComposerSendState(options: {
124 prompt: string;
125 imageCount: number;
126 terminalContexts: ReadonlyArray<TerminalContextDraft>;
127}): {
128 trimmedPrompt: string;
129 sendableTerminalContexts: TerminalContextDraft[];
130 expiredTerminalContextCount: number;
131 hasSendableContent: boolean;
132} {
133 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
134 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
135 const expiredTerminalContextCount =
136 options.terminalContexts.length - sendableTerminalContexts.length;
137 return {
138 trimmedPrompt,
139 sendableTerminalContexts,
140 expiredTerminalContextCount,
141 hasSendableContent:
142 trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
143 };
145​
146export function buildExpiredTerminalContextToastCopy(
147 expiredTerminalContextCount: number,
148 variant: "omitted" | "empty",
149): { title: string; description: string } {
150 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
151 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
152 if (variant === "empty") {
153 return {
154 title: `${noun} won't be sent`,
155 description: "Remove it or re-add it to include terminal output.",
156 };
157 }
158 return {
159 title: `${noun} omitted from message`,
160 description: "Re-add it if you want that terminal output included.",
161 };