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

ChatView.logic.ts

173 lines5.4 KB

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