@devries-cameron20 / t3code Mirror · read-only / commits / 6fc9144a60
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 12:00 UTC

fix: image-only messages no longer leak the attachment placeholder (#27383)

maria committed Oct 30, 2026 at 17:25 UTC 6fc9144a60c4a5f45089316ddd5f7371bafd3bf2
24 files changed +647 -64
apps/mobile/src/state/queued-run-edit.test.ts
+28
@@ -1,5 +1,9 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2 import { Atom } from "effect/reactivity";
3 +import {
4 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
5 + restoreAttachmentOnlyBootstrapPrompt,
6 +} from "@t3tools/shared/composerContextReferences";
7 import {
8 ChatAttachmentId,
9 ComposerContextId,
@@ -112,6 +116,30 @@ describe("resolveQueuedEditPayload", () => {
116 });
117
118 describe("beginQueuedRunEdit", () => {
119 + it.each(["", "Ultrathink:\n"])(
120 + "opens attachment-only edits without the placeholder and treats them as untouched (%j)",
121 + (prefix) => {
122 + const threadKey = `env-exit:attachment-only-${prefix.length}`;
123 + const original = {
124 + ...edit([image("kept")]),
125 + originalText: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
126 + };
127 + const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>(
128 + [{ id: original.runId, status: "queued" }],
129 + );
130 + beginQueuedRunEdit(threadKey, original, runs);
131 + const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, original.runId));
132 + expect(draft.text).toBe(prefix.trimEnd());
133 + expect(
134 + restoreAttachmentOnlyBootstrapPrompt(draft.text, original.existingAttachments.length > 0),
135 + ).toBe(original.originalText);
136 + expect(getQueuedRunEdit(threadKey)).toEqual({ ...original, originalText: prefix.trimEnd() });
137 + appAtomRegistry.set(runs, [{ id: original.runId, status: "running" }]);
138 + expect(getQueuedRunEdit(threadKey)).toBeNull();
139 + expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
140 + },
141 + );
142 +
143 it("silently drops an untouched edit when its run starts", () => {
144 const threadKey = "env-exit:thread-untouched";
145 const runId = RunId.make("run-1");
apps/mobile/src/state/queued-run-edit.ts
+8 -2
@@ -6,6 +6,7 @@ import type {
6 UploadChatAttachment,
7 } from "@t3tools/contracts";
8 import { useAtomValue } from "@effect/atom-react";
9 +import { stripAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
10 import {
11 makeQueuedRunEditStore,
12 resolveQueuedEditExit,
@@ -118,10 +119,15 @@ export function beginQueuedRunEdit(
119 // The composer moves off the thread draft, so a paste or pick still running for it is dropped.
120 abortComposerDraftOperations(threadKey);
121 const draftKey = queuedEditDraftKey(threadKey, edit.runId);
122 + const originalText = stripAttachmentOnlyBootstrapPrompt(edit.originalText);
123 clearComposerDraft(draftKey);
122 - setComposerDraftText(draftKey, edit.originalText);
124 + setComposerDraftText(draftKey, originalText);
125 setComposerDraftContext(draftKey, edit.context);
124 - queuedRunEdits.begin(threadKey, edit, { runs, onRunLeftQueue: exitQueuedRunEdit });
126 + queuedRunEdits.begin(
127 + threadKey,
128 + { ...edit, originalText },
129 + { runs, onRunLeftQueue: exitQueuedRunEdit },
130 + );
131 }
132
133 export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {
apps/mobile/src/state/use-thread-composer-state.ts
+7 -2
@@ -34,6 +34,7 @@ import {
34 } from "@t3tools/client-runtime/state/threads";
35 import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
36 import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
37 +import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
38 import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
39 import { uuidv4 } from "../lib/uuid";
40
@@ -403,7 +404,11 @@ export function useThreadComposerState() {
404 if (edit === null) return;
405 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
406 const text = draft.text.trim();
406 - if (text.length === 0) {
407 + if (
408 + text.length === 0 &&
409 + edit.existingAttachments.length === 0 &&
410 + draft.attachments.length === 0
411 + ) {
412 Dialog.alert("Add a message", "A queued message cannot be left empty.");
413 return;
414 }
@@ -457,7 +462,7 @@ export function useThreadComposerState() {
462 input: {
463 threadId: thread.id,
464 runId: edit.runId,
460 - text,
465 + text: restoreAttachmentOnlyBootstrapPrompt(text, payload.attachments.length > 0),
466 edit: {
467 messageId: edit.messageId,
468 attachments: payload.attachments,
apps/server/src/orchestration-v2/ThreadSearch.test.ts
+123
@@ -18,6 +18,7 @@ import * as Fiber from "effect/Fiber";
18 import * as Layer from "effect/Layer";
19 import * as Path from "effect/Path";
20 import * as SqlClient from "effect/sql/SqlClient";
21 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
22
23 import * as SqlitePersistence from "../persistence/Sqlite.ts";
24 import * as ProjectionStore from "./ProjectionStore.ts";
@@ -141,6 +142,119 @@ const message = (
142 },
143 });
144
145 +it.effect.each([true, false])(
146 + "ThreadSearch excludes bootstrap text before the hit and candidate limits (indexed: %s)",
147 + (indexed) =>
148 + Effect.gen(function* () {
149 + const projections = yield* ProjectionStore.ProjectionStoreV2;
150 + const search = yield* ThreadSearch.ThreadSearch;
151 + const sql = yield* SqlClient.SqlClient;
152 + const project = ProjectId.make("project:attachments");
153 + const threadId = ThreadId.make("thread:attachments");
154 + yield* createProject(project);
155 + yield* Effect.forEach(
156 + [
157 + thread(threadId, project),
158 + message(threadId, "ordinary", "user", "Review the attached files in context", {
159 + minute: 1,
160 + }),
161 + message(threadId, "attachment", "user", ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, { minute: 2 }),
162 + message(
163 + threadId,
164 + "ultrathink",
165 + "user",
166 + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
167 + { minute: 3 },
168 + ),
169 + ],
170 + projections.apply,
171 + { discard: true },
172 + );
173 + if (!indexed) {
174 + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
175 + yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
176 + yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`;
177 + yield* sql`DROP TABLE orchestration_v2_message_search`;
178 + }
179 + assert.deepEqual((yield* search.search({ query: "conversation context" })).matches, []);
180 + assert.deepEqual((yield* search.search({ query: "ultrathink" })).matches, []);
181 + assert.deepEqual(
182 + (yield* search.search({ query: "attached files" })).matches.map((match) => [
183 + match.messageId,
184 + match.snippet,
185 + ]),
186 + [[MessageId.make("ordinary"), "Review the attached files in context"]],
187 + );
188 + for (const text of [
189 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
190 + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
191 + `uLtRaThInK:\r\n\t\u00a0${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
192 + ]) {
193 + yield* sql`
194 + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${indexed ? 10_000 : 2000})
195 + INSERT INTO orchestration_v2_projection_messages
196 + (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
197 + SELECT 'attachment-limit:' || i, ${threadId}, 'user', 0,
198 + ${DateTime.formatIso(at(5))}, ${DateTime.formatIso(at(5))}, json_object('text', ${text})
199 + FROM n
200 + `;
201 + assert.deepEqual(
202 + (yield* search.search({ query: "context" })).matches.map((match) => match.messageId),
203 + [MessageId.make("ordinary")],
204 + );
205 + yield* sql`
206 + DELETE FROM orchestration_v2_projection_messages WHERE message_id LIKE 'attachment-limit:%'
207 + `;
208 + }
209 + }).pipe(Effect.provide(layerTest)),
210 +);
211 +
212 +it.effect("ThreadSearch excludes legacy placeholders still in the index", () =>
213 + Effect.gen(function* () {
214 + const projections = yield* ProjectionStore.ProjectionStoreV2;
215 + const search = yield* ThreadSearch.ThreadSearch;
216 + const sql = yield* SqlClient.SqlClient;
217 + const project = ProjectId.make("project:legacy-attachments");
218 + const threadId = ThreadId.make("thread:legacy-attachments");
219 + yield* createProject(project);
220 + // Simulate the pre-upgrade trigger, which indexed attachment placeholders.
221 + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
222 + yield* sql`
223 + CREATE TRIGGER orchestration_v2_message_search_insert
224 + AFTER INSERT ON orchestration_v2_projection_messages
225 + BEGIN
226 + INSERT INTO orchestration_v2_message_search (rowid, text)
227 + VALUES (new.rowid, json_extract(new.payload_json, '$.text'));
228 + END
229 + `;
230 + yield* Effect.forEach(
231 + [
232 + thread(threadId, project),
233 + message(threadId, "ordinary", "user", "Review the attached files in context"),
234 + message(threadId, "attachment", "user", ATTACHMENT_ONLY_BOOTSTRAP_PROMPT),
235 + message(
236 + threadId,
237 + "ultrathink",
238 + "user",
239 + `uLtRaThInK:\r\n\t\u00a0${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
240 + ),
241 + ],
242 + projections.apply,
243 + { discard: true },
244 + );
245 + assert.lengthOf(
246 + yield* sql`SELECT rowid FROM orchestration_v2_message_search WHERE orchestration_v2_message_search MATCH '"context"'`,
247 + 3,
248 + );
249 + assert.deepEqual((yield* search.search({ query: "conversation context" })).matches, []);
250 + assert.deepEqual((yield* search.search({ query: "ultrathink" })).matches, []);
251 + assert.deepEqual(
252 + (yield* search.search({ query: "context" })).matches.map((match) => match.messageId),
253 + [MessageId.make("ordinary")],
254 + );
255 + }).pipe(Effect.provide(layerTest)),
256 +);
257 +
258 it.layer(layerTest)("ThreadSearch", (it) => {
259 it.effect("reads the newest hits without sorting all of them", () =>
260 Effect.gen(function* () {
@@ -153,6 +267,15 @@ it.layer(layerTest)("ThreadSearch", (it) => {
267 plan.some((row) => row.detail.includes("TEMP B-TREE")),
268 plan.map((row) => row.detail).join("\n"),
269 );
270 + if (match !== null) {
271 + assert.lengthOf(
272 + plan.filter((row) =>
273 + row.detail.startsWith("SEARCH messages USING INTEGER PRIMARY KEY"),
274 + ),
275 + 1,
276 + plan.map((row) => row.detail).join("\n"),
277 + );
278 + }
279 }
280 }),
281 );
apps/server/src/orchestration-v2/ThreadSearch.ts
+4 -3
@@ -33,7 +33,7 @@ import {
33 type ThreadSearchSubject,
34 } from "@t3tools/shared/paletteSearch";
35 import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
36 -import { indexedMessageCondition } from "./messageSearchIndex.ts";
36 +import { indexedMessageCondition, nonPlaceholderMessageCondition } from "./messageSearchIndex.ts";
37 import { loadOlderSettledThreadsPage } from "./ShellStream.ts";
38
39 // When the user last wrote in the thread aliased `threads`, as the clients
@@ -209,11 +209,12 @@ export const messageHitsQuery = (
209 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
210 WHERE orchestration_v2_message_search MATCH ${match}
211 AND orchestration_v2_message_search.rowid >= coalesce((
212 - SELECT rowid FROM orchestration_v2_message_search
212 + SELECT orchestration_v2_message_search.rowid FROM orchestration_v2_message_search
213 WHERE orchestration_v2_message_search MATCH ${match}
214 - ORDER BY rowid DESC
214 + ORDER BY orchestration_v2_message_search.rowid DESC
215 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
216 ), 0)
217 + AND ${nonPlaceholderMessageCondition(sql)}
218 `
219 }
220 -- Answers to an agent's question show inside its question card, where
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
+43 -1
@@ -1,6 +1,8 @@
1 import { assert, describe, it, vi } from "@effect/vitest";
2 import {
3 CommandId,
4 + ChatAttachmentId,
5 + type ChatAttachment,
6 EventId,
7 MessageId,
8 ProjectId,
@@ -14,6 +16,7 @@ import * as DateTime from "effect/DateTime";
16 import * as Effect from "effect/Effect";
17 import * as Layer from "effect/Layer";
18 import * as Option from "effect/Option";
19 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
20
21 import * as SqlitePersistence from "../persistence/Sqlite.ts";
22 import * as ProjectStore from "./ProjectStore.ts";
@@ -134,6 +137,7 @@ function dispatchUserMessage(input: {
137 readonly command: string;
138 readonly threadId: ThreadId;
139 readonly text: string;
140 + readonly attachments?: ReadonlyArray<ChatAttachment>;
141 }) {
142 return Effect.gen(function* () {
143 const threads = yield* ThreadManagement.ThreadManagementService;
@@ -143,7 +147,7 @@ function dispatchUserMessage(input: {
147 threadId: input.threadId,
148 messageId: MessageId.make(`${input.command}:message`),
149 text: input.text,
146 - attachments: [],
150 + attachments: input.attachments ?? [],
151 modelSelection,
152 dispatchMode: { type: "defer_start" },
153 createdBy: "user",
@@ -270,6 +274,44 @@ describe("formatThreadTitleContext", () => {
274 });
275
276 describe("ThreadTitleRegenerationService", () => {
277 + it.effect(
278 + "titles an image-only first message without sending bootstrap text to the title model",
279 + () =>
280 + Effect.gen(function* () {
281 + for (const prefix of ["", "Ultrathink:\n"]) {
282 + const harness = makeHarness();
283 + yield* Effect.gen(function* () {
284 + const threads = yield* ThreadManagement.ThreadManagementService;
285 + const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
286 + const threadId = yield* createThread({
287 + command: "image:create",
288 + thread: "image:thread",
289 + });
290 + const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
291 + const attachments = [
292 + {
293 + type: "image" as const,
294 + id: ChatAttachmentId.make("diagram"),
295 + name: "diagram.png",
296 + mimeType: "image/png",
297 + sizeBytes: 10,
298 + },
299 + ];
300 + yield* dispatchUserMessage({ command: "image:message", threadId, text, attachments });
301 + const requestId = yield* armRegeneration({ command: "image:title", threadId });
302 + const messageId = MessageId.make("image:message:message");
303 + yield* service.execute({ threadId, requestId, kind: { type: "initial", messageId } });
304 + const call = harness.generateThreadTitle.mock.calls[0]?.[0];
305 + assert.equal(call?.message, "");
306 + assert.deepEqual(call?.attachments, attachments);
307 + const projection = yield* threads.getThreadProjection(threadId);
308 + assert.equal(projection.messages[0]?.text, text);
309 + assert.equal(projection.thread.title, "Generated title");
310 + }).pipe(Effect.provide(harness.layer));
311 + }
312 + }),
313 + );
314 +
315 it.effect("arms and clears the regeneration marker through metadata commands", () =>
316 Effect.gen(function* () {
317 const harness = makeHarness();
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts
+5 -1
@@ -1,4 +1,5 @@
1 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2 +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
3 import {
4 CommandId,
5 type ChatAttachment,
@@ -138,7 +139,10 @@ const make = Effect.gen(function* () {
139 context =
140 message === undefined
141 ? { message: "", attachments: [] }
141 - : { message: message.text, attachments: message.attachments };
142 + : {
143 + message: isAttachmentOnlyBootstrapPrompt(message.text) ? "" : message.text,
144 + attachments: message.attachments,
145 + };
146 } else {
147 context = formatThreadTitleContext(
148 projection.messages.filter((message) => !message.streaming),
apps/server/src/orchestration-v2/messageSearchIndex.ts
+67 -4
@@ -1,13 +1,28 @@
1 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
2 import * as Effect from "effect/Effect";
3 import type * as SqlClient from "effect/sql/SqlClient";
4
5 +// SQLite's ltrim needs the characters matched by isAttachmentOnlyBootstrapPrompt's \s explicitly.
6 +const BOOTSTRAP_PREFIX_WHITESPACE =
7 + "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff";
8 +
9 +export const nonPlaceholderMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
10 + sql.literal(`
11 + CASE
12 + WHEN substr(json_extract(${row}.payload_json, '$.text'), 1, 11) = 'Ultrathink:' COLLATE NOCASE
13 + THEN ltrim(substr(json_extract(${row}.payload_json, '$.text'), 12), '${BOOTSTRAP_PREFIX_WHITESPACE}')
14 + ELSE json_extract(${row}.payload_json, '$.text')
15 + END COLLATE BINARY <> '${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.replaceAll("'", "''")}'
16 +`);
17 +
18 /**
5 - * Exclude generated notices and subagent threads: search hides them, and ACP subagents rewrite
6 - * their finished answer on every streamed chunk.
19 + * Exclude attachment placeholders, generated notices and subagent threads. ACP subagents
20 + * rewrite their finished answer on every streamed chunk.
21 * Migration triggers, backfill, rebuild and scans share this predicate; `row` may be `new`.
22 */
23 export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
10 - sql.literal(`
24 + sql`
25 + ${sql.literal(`
26 ${row}.streaming = 0
27 AND (
28 ${row}.role = 'assistant'
@@ -21,7 +36,9 @@ export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "message
36 WHERE subagent_threads.thread_id = ${row}.thread_id
37 AND json_extract(subagent_threads.payload_json, '$.lineage.relationshipToParent') = 'subagent'
38 )
24 -`);
39 +`)}
40 + AND ${nonPlaceholderMessageCondition(sql, row)}
41 +`;
42
43 /**
44 * What the index stores for a message: its text with curly apostrophes
@@ -32,6 +49,52 @@ export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "message
49 export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) =>
50 sql.literal(`replace(replace(json_extract(${payload}, '$.text'), '’', ''''), '‘', '''')`);
51
52 +export const createMessageSearchTriggers = Effect.fn("MessageSearchIndex.createTriggers")(
53 + function* (sql: SqlClient.SqlClient) {
54 + yield* sql`
55 + CREATE TRIGGER orchestration_v2_message_search_insert
56 + AFTER INSERT ON orchestration_v2_projection_messages
57 + WHEN ${indexedMessageCondition(sql, "new")}
58 + BEGIN
59 + INSERT INTO orchestration_v2_message_search (rowid, text)
60 + SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
61 + WHERE json_extract(new.payload_json, '$.text') IS NOT NULL;
62 + END
63 + `;
64 + // Streaming deltas rewrite the row many times a second; skip them until the
65 + // message settles. Upserts rewrite every column, so a finished message
66 + // re-indexes only when what the index reads changed. Deleting a rowid the
67 + // index never held is a no-op.
68 + yield* sql`
69 + CREATE TRIGGER orchestration_v2_message_search_update
70 + AFTER UPDATE OF payload_json, streaming, role ON orchestration_v2_projection_messages
71 + WHEN (old.streaming = 0 OR new.streaming = 0)
72 + AND (
73 + old.streaming IS NOT new.streaming
74 + OR old.role IS NOT new.role
75 + OR json_extract(old.payload_json, '$.text') IS NOT json_extract(new.payload_json, '$.text')
76 + OR json_extract(old.payload_json, '$.createdBy')
77 + IS NOT json_extract(new.payload_json, '$.createdBy')
78 + )
79 + BEGIN
80 + DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0;
81 + INSERT INTO orchestration_v2_message_search (rowid, text)
82 + SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
83 + WHERE ${indexedMessageCondition(sql, "new")}
84 + AND json_extract(new.payload_json, '$.text') IS NOT NULL;
85 + END
86 + `;
87 + yield* sql`
88 + CREATE TRIGGER orchestration_v2_message_search_delete
89 + AFTER DELETE ON orchestration_v2_projection_messages
90 + WHEN old.streaming = 0
91 + BEGIN
92 + DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
93 + END
94 + `;
95 + },
96 +);
97 +
98 /**
99 * Refills the search index from the messages table. The index is keyed by
100 * message rowid, so anything that may renumber or copy rows (VACUUM, a dev
apps/server/src/persistence/Migrations.ts
+2
@@ -76,6 +76,7 @@ import Migration0070 from "./Migrations/070_PeerLinks.ts";
76 import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
77 import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
78 import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
79 +import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
80
81 const migrationEntries = [
82 [1, "OrchestrationEvents", Migration0001],
@@ -152,6 +153,7 @@ const migrationEntries = [
153 [71, "PeerLinkFence", Migration0071],
154 [72, "WaitingLinkRequestIndex", Migration0072],
155 [73, "ActiveTurnItemIndexes", Migration0073],
156 + [74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
157 ] as const;
158
159 export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/069_ThreadMessageSearch.test.ts
+85
@@ -1,8 +1,10 @@
1 import { assert, it } from "@effect/vitest";
2 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
3 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
4 import * as Effect from "effect/Effect";
5 import * as SqlClient from "effect/sql/SqlClient";
6
7 +import { rebuildMessageSearch } from "../../orchestration-v2/messageSearchIndex.ts";
8 import { runMigrations } from "../Migrations.ts";
9
10 const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" }));
@@ -53,3 +55,86 @@ layer("069_ThreadMessageSearch", (it) => {
55 }),
56 );
57 });
58 +
59 +it.effect.each(["inserted", "updated", "backfilled", "rebuilt"])(
60 + "keeps normal messages indexed and excludes %s placeholders",
61 + (path) =>
62 + Effect.gen(function* () {
63 + const sql = yield* SqlClient.SqlClient;
64 + yield* runMigrations({ toMigrationInclusive: path === "backfilled" ? 68 : 73 });
65 + if (path !== "backfilled") {
66 + // Pre-upgrade triggers indexed user text even when it was an attachment placeholder.
67 + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
68 + yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
69 + yield* sql`
70 + CREATE TRIGGER orchestration_v2_message_search_insert
71 + AFTER INSERT ON orchestration_v2_projection_messages
72 + BEGIN
73 + INSERT INTO orchestration_v2_message_search (rowid, text)
74 + VALUES (new.rowid, json_extract(new.payload_json, '$.text'));
75 + END
76 + `;
77 + yield* sql`
78 + CREATE TRIGGER orchestration_v2_message_search_update
79 + AFTER UPDATE OF payload_json ON orchestration_v2_projection_messages
80 + BEGIN
81 + DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
82 + INSERT INTO orchestration_v2_message_search (rowid, text)
83 + VALUES (new.rowid, json_extract(new.payload_json, '$.text'));
84 + END
85 + `;
86 + if (path !== "rebuilt") yield* runMigrations();
87 + }
88 + const placeholders = [
89 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
90 + ...[
91 + "",
92 + " ",
93 + "\n",
94 + "\t\r\n",
95 + "\v\f",
96 + "\u00a0",
97 + "\u1680",
98 + "\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a",
99 + "\u2028\u2029\u202f\u205f\u3000\ufeff",
100 + ].map((whitespace) => `uLtRaThInK:${whitespace}${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`),
101 + ];
102 + const normal = [
103 + "normal context",
104 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.toLowerCase(),
105 + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.toLowerCase()}`,
106 + `quoted ${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
107 + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT} extra`,
108 + ` ${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
109 + `Ultrathink:\u0085${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
110 + ];
111 + for (const [index, text] of [...normal, ...placeholders].entries()) {
112 + const payload = JSON.stringify({ text, createdBy: "user" });
113 + yield* sql`
114 + INSERT INTO orchestration_v2_projection_messages
115 + (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
116 + VALUES (${String(index)}, 'thread-1', 'user', 0,
117 + '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z',
118 + ${path === "updated" ? JSON.stringify({ text: "normal context" }) : payload})
119 + `;
120 + if (path === "updated") {
121 + yield* sql`
122 + UPDATE orchestration_v2_projection_messages SET payload_json = ${payload}
123 + WHERE message_id = ${String(index)}
124 + `;
125 + }
126 + }
127 + yield* runMigrations({ toMigrationInclusive: path === "backfilled" ? 69 : undefined });
128 + if (path === "rebuilt") yield* rebuildMessageSearch(sql);
129 + const indexed = yield* sql<{ readonly messageId: string }>`
130 + SELECT messages.message_id AS "messageId"
131 + FROM orchestration_v2_message_search AS search
132 + INNER JOIN orchestration_v2_projection_messages AS messages ON messages.rowid = search.rowid
133 + ORDER BY messages.rowid
134 + `;
135 + assert.deepEqual(
136 + indexed.map((row) => row.messageId),
137 + normal.map((_, index) => String(index)),
138 + );
139 + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
140 +);
apps/server/src/persistence/Migrations/069_ThreadMessageSearch.ts
+2 -41
@@ -3,6 +3,7 @@ import * as Predicate from "effect/Predicate";
3 import * as SqlClient from "effect/sql/SqlClient";
4
5 import {
6 + createMessageSearchTriggers,
7 indexedMessageCondition,
8 indexedMessageText,
9 } from "../../orchestration-v2/messageSearchIndex.ts";
@@ -39,47 +40,7 @@ export default Effect.gen(function* () {
40 ),
41 );
42 if (!created) return;
42 - yield* sql`
43 - CREATE TRIGGER orchestration_v2_message_search_insert
44 - AFTER INSERT ON orchestration_v2_projection_messages
45 - WHEN ${indexedMessageCondition(sql, "new")}
46 - BEGIN
47 - INSERT INTO orchestration_v2_message_search (rowid, text)
48 - SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
49 - WHERE json_extract(new.payload_json, '$.text') IS NOT NULL;
50 - END
51 - `;
52 - // Streaming deltas rewrite the row many times a second; skip them until the
53 - // message settles. Upserts rewrite every column, so a finished message
54 - // re-indexes only when what the index reads changed. Deleting a rowid the
55 - // index never held is a no-op.
56 - yield* sql`
57 - CREATE TRIGGER orchestration_v2_message_search_update
58 - AFTER UPDATE OF payload_json, streaming, role ON orchestration_v2_projection_messages
59 - WHEN (old.streaming = 0 OR new.streaming = 0)
60 - AND (
61 - old.streaming IS NOT new.streaming
62 - OR old.role IS NOT new.role
63 - OR json_extract(old.payload_json, '$.text') IS NOT json_extract(new.payload_json, '$.text')
64 - OR json_extract(old.payload_json, '$.createdBy')
65 - IS NOT json_extract(new.payload_json, '$.createdBy')
66 - )
67 - BEGIN
68 - DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0;
69 - INSERT INTO orchestration_v2_message_search (rowid, text)
70 - SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
71 - WHERE ${indexedMessageCondition(sql, "new")}
72 - AND json_extract(new.payload_json, '$.text') IS NOT NULL;
73 - END
74 - `;
75 - yield* sql`
76 - CREATE TRIGGER orchestration_v2_message_search_delete
77 - AFTER DELETE ON orchestration_v2_projection_messages
78 - WHEN old.streaming = 0
79 - BEGIN
80 - DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
81 - END
82 - `;
43 + yield* createMessageSearchTriggers(sql);
44 yield* sql`
45 INSERT INTO orchestration_v2_message_search (rowid, text)
46 SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")}
apps/server/src/persistence/Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts new
+18
@@ -0,0 +1,18 @@
1 +import * as Effect from "effect/Effect";
2 +import * as SqlClient from "effect/sql/SqlClient";
3 +
4 +import { createMessageSearchTriggers } from "../../orchestration-v2/messageSearchIndex.ts";
5 +
6 +export default Effect.gen(function* () {
7 + const sql = yield* SqlClient.SqlClient;
8 + const index = yield* sql`
9 + SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
10 + `;
11 + if (index.length === 0) return;
12 +
13 + // Legacy placeholders stay indexed until rebuild; FTS deletes can overflow last_insert_rowid at commit.
14 + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
15 + yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
16 + yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`;
17 + yield* createMessageSearchTriggers(sql);
18 +});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -53,6 +53,7 @@ describe("V2 preview upgrade", () => {
53 [71, "PeerLinkFence"],
54 [72, "WaitingLinkRequestIndex"],
55 [73, "ActiveTurnItemIndexes"],
56 + [74, "ExcludeAttachmentPlaceholdersFromSearch"],
57 ]);
58 assert.deepStrictEqual(yield* runMigrations(), []);
59 assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -149,6 +150,7 @@ describe("V2 preview upgrade", () => {
150 [71, "PeerLinkFence"],
151 [72, "WaitingLinkRequestIndex"],
152 [73, "ActiveTurnItemIndexes"],
153 + [74, "ExcludeAttachmentPlaceholdersFromSearch"],
154 ]);
155 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
156 );
apps/web/src/components/ChatView.logic.ts
+2
@@ -748,6 +748,7 @@ export function cloneComposerImageForRetry(
748 export function deriveComposerSendState(options: {
749 prompt: string;
750 imageCount: number;
751 + existingAttachmentCount?: number;
752 terminalContexts: ReadonlyArray<TerminalContextDraft>;
753 elementContextCount?: number;
754 }): {
@@ -768,6 +769,7 @@ export function deriveComposerSendState(options: {
769 hasSendableContent:
770 trimmedPrompt.length > 0 ||
771 options.imageCount > 0 ||
772 + (options.existingAttachmentCount ?? 0) > 0 ||
773 sendableTerminalContexts.length > 0 ||
774 elementContextCount > 0,
775 };
apps/web/src/components/chat/ChatComposer.tsx
+1
@@ -1091,6 +1091,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1091 const composerSendState = deriveComposerSendState({
1092 prompt,
1093 imageCount: composerImages.length + composerFiles.length,
1094 + existingAttachmentCount: editingQueuedAttachments?.length ?? 0,
1095 terminalContexts: composerTerminalContexts,
1096 elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length,
1097 });
apps/web/src/components/chat/timelineMinimapItems.test.ts
+33 -1
@@ -1,6 +1,38 @@
1 import { describe, expect, it } from "vite-plus/test";
2 +import { MessageId } from "@t3tools/contracts";
3 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
4
3 -import { resolveTimelineMinimapPreview } from "./timelineMinimapItems";
5 +import { deriveTimelineMinimapItems, resolveTimelineMinimapPreview } from "./timelineMinimapItems";
6 +
7 +describe("deriveTimelineMinimapItems", () => {
8 + it.each(["", "Ultrathink:\n"])(
9 + "omits bootstrap text from the minimap label and tooltip (%j)",
10 + (prefix) => {
11 + const at = "2026-10-01T00:00:00Z";
12 + const items = deriveTimelineMinimapItems([
13 + {
14 + kind: "message",
15 + id: "image-only",
16 + createdAt: at,
17 + showAssistantMeta: false,
18 + showAssistantCopyButton: false,
19 + assistantCopyStreaming: false,
20 + message: {
21 + id: MessageId.make("image-only"),
22 + role: "user",
23 + text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
24 + runId: null,
25 + streaming: false,
26 + createdAt: at,
27 + updatedAt: at,
28 + },
29 + },
30 + ]);
31 + expect(items).toEqual([{ id: "image-only", rowIndex: 0, userText: "", assistantText: null }]);
32 + expect(resolveTimelineMinimapPreview(items[0]!)?.userText).toBeNull();
33 + },
34 + );
35 +});
36
37 describe("resolveTimelineMinimapPreview", () => {
38 it("previews a thread autolink as prose, not its URL", () => {
apps/web/src/components/chat/timelineMinimapItems.ts
+2 -1
@@ -1,4 +1,5 @@
1 import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
2 +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
3 import type { Nodes } from "mdast";
4 import remarkGfm from "remark-gfm";
5 import remarkParse from "remark-parse";
@@ -26,7 +27,7 @@ export function deriveTimelineMinimapItems(
27 items.push({
28 id: row.id,
29 rowIndex: index,
29 - userText: row.message.text,
30 + userText: isAttachmentOnlyBootstrapPrompt(row.message.text) ? "" : row.message.text,
31 assistantText: resolveFinalAssistantTextForTurn(rows, index),
32 });
33 }
apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx
+126 -2
@@ -1,6 +1,7 @@
1 import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2 import {
3 EnvironmentId,
4 + ChatAttachmentId,
5 MessageId,
6 RunId,
7 ThreadId,
@@ -8,9 +9,13 @@ import {
9 } from "@t3tools/contracts";
10 import { useImperativeHandle, type RefObject } from "react";
11 import { describe, expect, it, vi } from "vite-plus/test";
12 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
13 +import { toastManager } from "../ui/toast";
14
15 import { act, render } from "../../../test/render";
13 -import { useComposerDraftStore } from "../../composerDraftStore";
16 +import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
17 +import { deriveComposerSendState } from "../ChatView.logic";
18 +import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
19 import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
20 import { useQueuedRunEdit } from "./useQueuedRunEdit";
21
@@ -34,6 +39,10 @@ vi.mock("../../state/use-atom-command", () => ({
39 useAtomCommand: () => mocks.editQueuedRun,
40 }));
41
42 +vi.mock("../../hooks/useSettings", () => ({
43 + useEnvironmentIdentificationMode: () => "none",
44 +}));
45 +
46 const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
47
48 vi.mock("../../state/threads", async () => {
@@ -88,7 +97,34 @@ function Harness(props: {
97 composerRef: { current: null },
98 });
99 useImperativeHandle(props.hookRef, () => result);
91 - return null;
100 + const draft = useComposerThreadDraft(result.draftTarget);
101 + const sendState = deriveComposerSendState({
102 + prompt: draft.prompt,
103 + imageCount: draft.images.length + draft.files.length,
104 + existingAttachmentCount: result.editingAttachments?.length ?? 0,
105 + terminalContexts: draft.terminalContexts,
106 + });
107 + return result.isEditing ? (
108 + <ComposerPrimaryActions
109 + compact={false}
110 + canOperateThread
111 + pendingAction={null}
112 + isRunning={false}
113 + canInterrupt={false}
114 + showPlanFollowUpPrompt={false}
115 + promptHasText={draft.prompt.trim().length > 0}
116 + isSendBusy={result.isSaving}
117 + sendDisabledReason={null}
118 + isEnvironmentUnavailable={false}
119 + isPreparingWorktree={false}
120 + hasSendableContent={sendState.hasSendableContent}
121 + isEditingQueuedMessage
122 + onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})}
123 + onPreviousPendingQuestion={() => {}}
124 + onInterrupt={() => {}}
125 + onImplementPlanInNewThread={() => {}}
126 + />
127 + ) : null;
128 }
129
130 function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
@@ -141,6 +177,94 @@ const promptOf = (ref: ScopedThreadRef) =>
177 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
178
179 describe("useQueuedRunEdit", () => {
180 + it.each(["", "Ultrathink:\n"])(
181 + "opens attachment-only edits without the placeholder and preserves effort on save (%j)",
182 + async (prefix) => {
183 + const { hook } = setup();
184 + mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
185 + await using screen = await render(view(THREAD_A, "queued", hook));
186 + using toast = vi.spyOn(toastManager, "add");
187 + const attachments = [
188 + {
189 + type: "image" as const,
190 + id: ChatAttachmentId.make("kept"),
191 + name: "kept.png",
192 + mimeType: "image/png",
193 + sizeBytes: 10,
194 + },
195 + ];
196 + const request = {
197 + runId: RUN,
198 + messageId: MessageId.make("message-1"),
199 + text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
200 + attachments,
201 + };
202 + await act(() => requireHook(hook).beginEdit(request));
203 + expect(
204 + useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ??
205 + "",
206 + ).toBe(prefix.trimEnd());
207 + expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual(
208 + attachments,
209 + );
210 + await act(() =>
211 + useComposerDraftStore
212 + .getState()
213 + .setRuntimeMode(requireHook(hook).draftTarget, "full-access"),
214 + );
215 + await act(() => setRuns(THREAD_A, "running"));
216 + expect(toast).not.toHaveBeenCalled();
217 + expect(requireHook(hook).isEditing).toBe(false);
218 + await act(() => setRuns(THREAD_A, "queued"));
219 + await act(() => requireHook(hook).beginEdit(request));
220 + const update = screen.getByRole("button", { name: "Update queued message" });
221 + await expect.element(update).toBeEnabled();
222 + await update.click();
223 + await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
224 + expect(mocks.editQueuedRun).toHaveBeenCalledWith(
225 + expect.objectContaining({
226 + input: expect.objectContaining({
227 + text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
228 + edit: expect.objectContaining({ attachments }),
229 + }),
230 + }),
231 + );
232 + },
233 + );
234 +
235 + it("saves an effort-only prompt without claiming removed attachments remain", async () => {
236 + const { hook } = setup();
237 + mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
238 + await using screen = await render(view(THREAD_A, "queued", hook));
239 + await act(() =>
240 + requireHook(hook).beginEdit({
241 + runId: RUN,
242 + messageId: MessageId.make("message-1"),
243 + text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
244 + attachments: [
245 + {
246 + type: "image",
247 + id: ChatAttachmentId.make("removed"),
248 + name: "removed.png",
249 + mimeType: "image/png",
250 + sizeBytes: 10,
251 + },
252 + ],
253 + }),
254 + );
255 + await act(() => requireHook(hook).removeEditingAttachment("removed"));
256 + await screen.getByRole("button", { name: "Update queued message" }).click();
257 + await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
258 + expect(mocks.editQueuedRun).toHaveBeenCalledWith(
259 + expect.objectContaining({
260 + input: expect.objectContaining({
261 + text: "Ultrathink:",
262 + edit: expect.objectContaining({ attachments: [] }),
263 + }),
264 + }),
265 + );
266 + });
267 +
268 it("keeps an open edit when the user leaves the thread and comes back", async () => {
269 const { hook } = setup();
270 await using screen = await render(view(THREAD_A, "queued", hook));
apps/web/src/components/chat/useQueuedRunEdit.ts
+8 -4
@@ -18,7 +18,10 @@ import {
18 type ThreadId,
19 } from "@t3tools/contracts";
20 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
21 -import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
21 +import {
22 + restoreAttachmentOnlyBootstrapPrompt,
23 + stripAttachmentOnlyBootstrapPrompt,
24 +} from "@t3tools/shared/composerContextReferences";
25 import { Atom } from "effect/reactivity";
26 import type { RefObject } from "react";
27 import { useAssetUrls } from "../../assets/assetUrls";
@@ -146,7 +149,7 @@ async function submitQueuedRunEdit(input: {
149 input: {
150 threadId: editing.threadId,
151 runId: editing.runId,
149 - text: editText.length === 0 ? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT : editText,
152 + text: restoreAttachmentOnlyBootstrapPrompt(editText, uploads.length > 0),
153 edit: {
154 messageId: editing.messageId,
155 attachments: uploads,
@@ -227,9 +230,10 @@ export function useQueuedRunEdit(input: {
230 if (activeThreadId === null) return;
231 if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
232 const target = queuedEditDraftTarget(routeThreadRef, request.runId);
233 + const text = stripAttachmentOnlyBootstrapPrompt(request.text);
234 const store = useComposerDraftStore.getState();
235 store.clearComposerContent(target);
232 - store.setPrompt(target, request.text);
236 + store.setPrompt(target, text);
237 const threadRef = { environmentId, threadId: activeThreadId };
238 queuedRunEdits.begin(
239 editKey,
@@ -237,7 +241,7 @@ export function useQueuedRunEdit(input: {
241 threadId: activeThreadId,
242 runId: request.runId,
243 messageId: request.messageId,
240 - originalText: request.text,
244 + originalText: text,
245 existingAttachments: request.attachments,
246 context: serverProjection?.messages.find((message) => message.id === request.messageId)
247 ?.context,
apps/web/src/components/promptLinks/copyPromptLink.ts
+2 -1
@@ -1,4 +1,5 @@
1 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
2 +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
3 import {
4 type ModelSelection,
5 repositoryGroupingKeyOf,
@@ -26,7 +27,7 @@ export function promptLinkFor(
27 readonly model: string | null;
28 },
29 ): string | null {
29 - const trimmed = prompt.trim();
30 + const trimmed = isAttachmentOnlyBootstrapPrompt(prompt) ? "" : prompt.trim();
31 if (trimmed.length === 0 || trimmed.length > PROMPT_LINK_MAX_PROMPT_LENGTH) return null;
32 return buildNewThreadLink({ prompt: trimmed, ...context, origin: configuredHostedAppUrl() });
33 }
packages/provider-core/src/server/threadTitleContext.test.ts
+23
@@ -1,7 +1,30 @@
1 import { describe, expect, it } from "vite-plus/test";
2 +import { ChatAttachmentId } from "@t3tools/contracts";
3 +import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
4 import { formatThreadTitleContext } from "./threadTitleContext.ts";
5
6 describe("thread title context", () => {
7 + it.each(["", "Ultrathink:\n"])("keeps attachments without bootstrap text (%j)", (prefix) => {
8 + const attachments = [
9 + {
10 + type: "image" as const,
11 + id: ChatAttachmentId.make("diagram"),
12 + name: "diagram.png",
13 + mimeType: "image/png",
14 + sizeBytes: 10,
15 + },
16 + ];
17 + const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
18 + expect(formatThreadTitleContext([{ role: "user", text, attachments }])).toEqual({
19 + message: "USER:\n[Attachments: diagram.png]",
20 + attachments,
21 + });
22 + expect(formatThreadTitleContext([{ role: "user", text }])).toEqual({
23 + message: "",
24 + attachments: [],
25 + });
26 + });
27 +
28 it("keeps a user's scope change despite long assistant output", () => {
29 const result = formatThreadTitleContext([
30 { role: "user", text: "Review QR sharing" },
packages/provider-core/src/server/threadTitleContext.ts
+3 -1
@@ -1,5 +1,6 @@
1 import type { ChatAttachment } from "@t3tools/contracts";
2 import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
3 +import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
4
5 export type ThreadTitleMessage = {
6 readonly role: "user" | "assistant" | "system" | "reasoning";
@@ -22,7 +23,8 @@ export function limitTitleMessage(text: string, budget: number): string {
23 }
24
25 export function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>) {
25 - const sections = messages.flatMap((message, index) => {
26 + const sections = messages.flatMap((source, index) => {
27 + const message = isAttachmentOnlyBootstrapPrompt(source.text) ? { ...source, text: "" } : source;
28 // Thinking traces dwarf answers without identifying the thread subject.
29 if (
30 message.role === "system" ||
packages/shared/src/composerContextReferences.test.ts
+35
@@ -7,11 +7,14 @@ import {
7 import { describe, expect, it } from "vite-plus/test";
8
9 import {
10 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
11 collectComposerContextReferences,
12 formatComposerContextHref,
13 isImageReferencesOnly,
14 parseComposerContextHref,
15 projectComposerContextForProvider,
16 + restoreAttachmentOnlyBootstrapPrompt,
17 + stripAttachmentOnlyBootstrapPrompt,
18 threadContextRecord,
19 threadContextsOutsideEnvironment,
20 toComposerContextId,
@@ -84,6 +87,38 @@ describe("labels and reference links", () => {
87 });
88 });
89
90 +describe("attachment-only bootstrap prompts", () => {
91 + it.each(["", "Ultrathink:\n", "ultrathink: \n"])(
92 + "removes only the placeholder while keeping effort (%j)",
93 + (prefix) => {
94 + expect(stripAttachmentOnlyBootstrapPrompt(prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT)).toBe(
95 + prefix.trimEnd(),
96 + );
97 + const text = `${prefix}Explain ${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`;
98 + expect(stripAttachmentOnlyBootstrapPrompt(text)).toBe(text);
99 + },
100 + );
101 +
102 + it.each(["", " \n", "Ultrathink:", "Ultrathink: \n", "ultrathink:\n"])(
103 + "restores the placeholder and canonical effort prefix for sending (%j)",
104 + (text) => {
105 + expect(restoreAttachmentOnlyBootstrapPrompt(text, false)).toBe(text);
106 + expect(restoreAttachmentOnlyBootstrapPrompt(text, true)).toBe(
107 + (text.trim() ? "Ultrathink:\n" : "") + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
108 + );
109 + },
110 + );
111 +
112 + it.each([
113 + "Describe the file",
114 + " Ultrathink:\nDescribe the file ",
115 + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
116 + `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
117 + ])("keeps other text unchanged (%j)", (text) => {
118 + expect(restoreAttachmentOnlyBootstrapPrompt(text, true)).toBe(text);
119 + });
120 +});
121 +
122 describe("provider projection", () => {
123 const terminal: ComposerContextRecord = {
124 version: 1,
packages/shared/src/composerContextReferences.ts
+18
@@ -137,6 +137,24 @@ export function isAttachmentOnlyBootstrapPrompt(text: string): boolean {
137 return text.replace(/^Ultrathink:\s*/i, "") === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
138 }
139
140 +export function stripAttachmentOnlyBootstrapPrompt(text: string): string {
141 + return isAttachmentOnlyBootstrapPrompt(text)
142 + ? text.slice(0, -ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.length).trimEnd()
143 + : text;
144 +}
145 +
146 +export function restoreAttachmentOnlyBootstrapPrompt(
147 + text: string,
148 + hasAttachments: boolean,
149 +): string {
150 + if (!hasAttachments) return text;
151 + const trimmed = text.trim();
152 + if (trimmed.length === 0) return ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
153 + return /^Ultrathink:\s*$/i.test(trimmed)
154 + ? `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`
155 + : text;
156 +}
157 +
158 export function isImageReferencesOnly(text: string): boolean {
159 const references = collectComposerContextReferences(text);
160 return (