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

ChatView.logic.ts

163 lines5.0 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 titleSummaryState: "missing",
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 deriveComposerSendState(options: {
125 prompt: string;
126 imageCount: number;
127 terminalContexts: ReadonlyArray<TerminalContextDraft>;
128}): {
129 trimmedPrompt: string;
130 sendableTerminalContexts: TerminalContextDraft[];
131 expiredTerminalContextCount: number;
132 hasSendableContent: boolean;
133} {
134 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
135 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
136 const expiredTerminalContextCount =
137 options.terminalContexts.length - sendableTerminalContexts.length;
138 return {
139 trimmedPrompt,
140 sendableTerminalContexts,
141 expiredTerminalContextCount,
142 hasSendableContent:
143 trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
144 };
146​
147export function buildExpiredTerminalContextToastCopy(
148 expiredTerminalContextCount: number,
149 variant: "omitted" | "empty",
150): { title: string; description: string } {
151 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
152 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
153 if (variant === "empty") {
154 return {
155 title: `${noun} won't be sent`,
156 description: "Remove it or re-add it to include terminal output.",
157 };
158 }
159 return {
160 title: `${noun} omitted from message`,
161 description: "Re-add it if you want that terminal output included.",
162 };