Compare commits

..
Author SHA1 Message Date
Ondra Pelechandcodex 9c53228bb8 fix(server): actionable error when creating a worktree in a commit-less repo
git worktree add cannot branch from an unborn HEAD, so starting a thread in New worktree mode inside a freshly-initialized repository (no commits yet) failed with a cryptic invalid-reference error.

Detect the missing base commit up front and fail with actionable guidance to make an initial commit or use the current checkout instead.

Co-authored-by: codex <[email protected]>
2026-07-20 17:39:18 +02:00
26 changed files with 72 additions and 1169 deletions

No files matched your search

+1 -10
View File
@@ -22,8 +22,6 @@ import {
PreviewSnapshotToolkit, PreviewSnapshotToolkit,
PreviewStandardToolkit, PreviewStandardToolkit,
} from "./toolkits/preview/tools.ts"; } from "./toolkits/preview/tools.ts";
import { ThreadReferenceToolkitHandlersLive } from "./toolkits/threadReference/handlers.ts";
import { ThreadReferenceToolkit } from "./toolkits/threadReference/tools.ts";
const unauthorized = HttpServerResponse.jsonUnsafe( const unauthorized = HttpServerResponse.jsonUnsafe(
{ {
@@ -210,17 +208,10 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive, PreviewSnapshotRegistrationLive,
); );
export const ThreadReferenceToolkitRegistrationLive = McpServer.toolkit(
ThreadReferenceToolkit,
).pipe(Layer.provide(ThreadReferenceToolkitHandlersLive));
const McpTransportLive = McpServer.layerHttp({ const McpTransportLive = McpServer.layerHttp({
name: "T3 Code", name: "T3 Code",
version: packageJson.version, version: packageJson.version,
path: "/mcp", path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive)); }).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = Layer.mergeAll( export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
PreviewToolkitRegistrationLive,
ThreadReferenceToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive));
+2 -2
View File
@@ -7,7 +7,7 @@ import {
import * as Context from "effect/Context"; import * as Context from "effect/Context";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
export type McpCapability = "preview" | "thread-reference"; export type McpCapability = "preview";
export interface McpInvocationScope { export interface McpInvocationScope {
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
@@ -25,7 +25,7 @@ export class McpInvocationContext extends Context.Service<
>()("t3/mcp/McpInvocationContext") {} >()("t3/mcp/McpInvocationContext") {}
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* ( export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
capability: "preview", capability: McpCapability,
) { ) {
const invocation = yield* McpInvocationContext; const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) { if (!invocation.capabilities.has(capability)) {
@@ -47,7 +47,6 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
const resolved = yield* registry.resolve(token); const resolved = yield* registry.resolve(token);
expect(resolved?.threadId).toBe(threadId); expect(resolved?.threadId).toBe(threadId);
expect(resolved?.capabilities).toEqual(new Set(["preview", "thread-reference"]));
yield* registry.revokeThread(threadId); yield* registry.revokeThread(threadId);
expect(yield* registry.resolve(token)).toBeUndefined(); expect(yield* registry.resolve(token)).toBeUndefined();
+1 -1
View File
@@ -114,7 +114,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
threadId: ThreadId.make(request.threadId), threadId: ThreadId.make(request.threadId),
providerSessionId, providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId), providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview", "thread-reference"]), capabilities: new Set(["preview"]),
issuedAt, issuedAt,
expiresAt, expiresAt,
}; };
@@ -1,301 +0,0 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationMessage,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { McpSchema, McpServer } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { PersistenceSqlError } from "../../../persistence/Errors.ts";
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import {
buildThreadReferencePage,
hasUserThreadReference,
normalizeThreadReferenceThreadId,
threadRead,
ThreadReferenceToolkitHandlersLive,
} from "./handlers.ts";
import { ThreadReferenceToolkit } from "./tools.ts";
const TestLayer = McpServer.toolkit(ThreadReferenceToolkit).pipe(
Layer.provide(ThreadReferenceToolkitHandlersLive),
Layer.provideMerge(McpServer.McpServer.layer),
);
const makeMessage = (
id: string,
text: string,
role: OrchestrationMessage["role"] = "user",
): OrchestrationMessage => ({
id: MessageId.make(id),
role,
text,
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
const currentThreadId = ThreadId.make("thread-current");
const environmentId = EnvironmentId.make("environment-1");
const thread = {
id: ThreadId.make("thread-referenced"),
projectId: ProjectId.make("project-1"),
title: "Referenced work",
messages: [makeMessage("message-1", "abcdef"), makeMessage("message-2", "ghijkl")],
} as unknown as OrchestrationThread;
const currentThread = {
...thread,
id: currentThreadId,
messages: [
makeMessage(
"message-reference",
`[Referenced work](t3-thread:///${environmentId}/${thread.id})`,
),
],
} as OrchestrationThread;
const invocation = {
environmentId,
threadId: currentThreadId,
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["thread-reference"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};
const mcpServerClient = {
clientId: 1,
initializePayload: {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "test", version: "1" },
},
getClient: Effect.die("unused"),
};
const projectionQueryFor = (sourceThread: OrchestrationThread) =>
({
getThreadDetailById: (threadId: ThreadId) =>
Effect.succeed(
threadId === sourceThread.id
? Option.some(sourceThread)
: threadId === thread.id
? Option.some(thread)
: Option.none(),
),
}) as never;
it("paginates within a message without losing transcript text", () => {
const first = buildThreadReferencePage(thread, {
threadId: thread.id,
maxChars: 1_000,
});
expect(first).toMatchObject({ nextCursor: null, totalMessages: 2 });
const longThread = {
...thread,
messages: [makeMessage("message-long", "a".repeat(1_100))],
};
const longFirst = buildThreadReferencePage(longThread, {
threadId: thread.id,
maxChars: 1_000,
});
expect(longFirst).toMatchObject({ nextCursor: "0:1000" });
if ("_tag" in longFirst) throw new Error("unexpected cursor error");
const longSecond = buildThreadReferencePage(longThread, {
threadId: thread.id,
cursor: longFirst.nextCursor!,
maxChars: 1_000,
});
if ("_tag" in longSecond) throw new Error("unexpected cursor error");
expect(longFirst.messages[0]?.text.length).toBe(1_000);
expect(longSecond.messages[0]?.text.length).toBe(100);
expect(longSecond.nextCursor).toBeNull();
});
it("continues pagination across an empty message at a page boundary", () => {
const emptyMessageThread = {
...thread,
messages: [
makeMessage("message-full", "a".repeat(1_000)),
makeMessage("message-empty", ""),
makeMessage("message-tail", "tail"),
],
};
const first = buildThreadReferencePage(emptyMessageThread, {
threadId: thread.id,
maxChars: 1_000,
});
if ("_tag" in first) throw new Error("unexpected cursor error");
expect(first.nextCursor).toBe("1:0");
const second = buildThreadReferencePage(emptyMessageThread, {
threadId: thread.id,
cursor: first.nextCursor!,
maxChars: 1_000,
});
if ("_tag" in second) throw new Error("unexpected cursor error");
expect(second.messages.map(({ text }) => text)).toEqual(["", "tail"]);
expect(second.nextCursor).toBeNull();
});
it.each([":", "0:", ":0", "0:0:garbage"])("rejects malformed cursor %s", (cursor) => {
expect(
buildThreadReferencePage(thread, {
threadId: thread.id,
cursor,
maxChars: 1_000,
} as never),
).toMatchObject({
_tag: "ThreadReferenceInvalidCursorError",
cursor,
});
});
it("only authorizes user-supplied references from the invoking environment", () => {
expect(hasUserThreadReference(currentThread, environmentId, thread.id)).toBe(true);
expect(
hasUserThreadReference(
{
...currentThread,
messages: [
makeMessage(
"message-punctuated-reference",
`Continue from [Referenced work](t3-thread:///${environmentId}/${thread.id}), please.`,
),
],
},
environmentId,
thread.id,
),
).toBe(true);
expect(
hasUserThreadReference(
{
...currentThread,
messages: [
makeMessage(
"message-assistant-reference",
`[Referenced work](t3-thread:///${environmentId}/${thread.id})`,
"assistant",
),
],
},
environmentId,
thread.id,
),
).toBe(false);
expect(
hasUserThreadReference(
{
...currentThread,
messages: [
makeMessage(
"message-other-environment",
`[Referenced work](t3-thread:///environment-2/${thread.id})`,
),
],
},
environmentId,
thread.id,
),
).toBe(false);
});
it("normalizes model-facing thread reference inputs", () => {
expect(normalizeThreadReferenceThreadId(thread.id, environmentId)).toBe(thread.id);
expect(
normalizeThreadReferenceThreadId(ThreadId.make(`${environmentId}/${thread.id}`), environmentId),
).toBe(thread.id);
expect(
normalizeThreadReferenceThreadId(
ThreadId.make(`t3-thread:///${environmentId}/${thread.id}`),
environmentId,
),
).toBe(thread.id);
expect(
normalizeThreadReferenceThreadId(
ThreadId.make(`t3-thread:///environment-2/${thread.id}`),
environmentId,
),
).toBe(`t3-thread:///environment-2/${thread.id}`);
});
it.effect("reads a referenced thread through the MCP toolkit", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
for (const threadId of [
thread.id,
`${environmentId}/${thread.id}`,
`t3-thread:///${environmentId}/${thread.id}`,
]) {
const result = yield* server.callTool({
name: "thread_read",
arguments: { threadId },
});
expect(result.isError).toBe(false);
expect(result.structuredContent).toMatchObject({
threadId: thread.id,
title: thread.title,
totalMessages: 2,
});
}
}).pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, mcpServerClient),
Effect.provideService(ProjectionSnapshotQuery, projectionQueryFor(currentThread)),
Effect.provide(TestLayer),
),
);
it.effect("rejects a thread that was not referenced by the invoking user", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const result = yield* server.callTool({
name: "thread_read",
arguments: { threadId: thread.id },
});
expect(result.isError).toBe(true);
}).pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, mcpServerClient),
Effect.provideService(
ProjectionSnapshotQuery,
projectionQueryFor({
...currentThread,
messages: [makeMessage("message-without-reference", "No thread reference here.")],
}),
),
Effect.provide(TestLayer),
),
);
it.effect("preserves projection failures when a referenced thread cannot be loaded", () => {
const repositoryError = new PersistenceSqlError({
operation: "getThreadDetailById",
detail: "database unavailable",
});
return Effect.gen(function* () {
const error = yield* Effect.flip(threadRead({ threadId: thread.id }));
expect(error).toMatchObject({
_tag: "ThreadReferenceUnavailableError",
threadId: thread.id,
});
expect(error.cause).toBe(repositoryError);
}).pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(ProjectionSnapshotQuery, {
getThreadDetailById: (threadId: ThreadId) =>
threadId === currentThread.id
? Effect.succeed(Option.some(currentThread))
: Effect.fail(repositoryError),
} as never),
);
});
@@ -1,178 +0,0 @@
import {
THREAD_REFERENCE_DEFAULT_MAX_CHARS,
ThreadReferenceInvalidCursorError,
ThreadReferenceNotFoundError,
type ThreadReferenceReadInput,
type ThreadReferenceReadResult,
type ThreadReferenceTranscriptMessage,
ThreadReferenceUnavailableError,
type EnvironmentId,
type OrchestrationThread,
ThreadId,
} from "@t3tools/contracts";
import { collectComposerThreadReferences } from "@t3tools/shared/composerInlineTokens";
import { parseComposerThreadLink } from "@t3tools/shared/composerTrigger";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ThreadReferenceToolkit } from "./tools.ts";
interface TranscriptPosition {
readonly messageIndex: number;
readonly textOffset: number;
}
function decodeCursor(
input: ThreadReferenceReadInput,
thread: OrchestrationThread,
): TranscriptPosition | null {
if (!input.cursor) return { messageIndex: 0, textOffset: 0 };
const cursorMatch = /^(\d+):(\d+)$/.exec(input.cursor);
if (!cursorMatch) return null;
const [, messageIndexText, textOffsetText] = cursorMatch;
const messageIndex = Number(messageIndexText);
const textOffset = Number(textOffsetText);
const message = thread.messages[messageIndex];
const validEndCursor = messageIndex === thread.messages.length && textOffset === 0;
if (
!Number.isSafeInteger(messageIndex) ||
!Number.isSafeInteger(textOffset) ||
messageIndex < 0 ||
textOffset < 0 ||
(!validEndCursor && (!message || textOffset > message.text.length))
) {
return null;
}
return { messageIndex, textOffset };
}
export function buildThreadReferencePage(
thread: OrchestrationThread,
input: ThreadReferenceReadInput,
): ThreadReferenceReadResult | ThreadReferenceInvalidCursorError {
const position = decodeCursor(input, thread);
if (!position) {
return new ThreadReferenceInvalidCursorError({
threadId: input.threadId,
cursor: input.cursor ?? "",
});
}
const maxChars = input.maxChars ?? THREAD_REFERENCE_DEFAULT_MAX_CHARS;
const messages: ThreadReferenceTranscriptMessage[] = [];
let messageIndex = position.messageIndex;
let textOffset = position.textOffset;
let includedChars = 0;
while (messageIndex < thread.messages.length && includedChars < maxChars) {
const message = thread.messages[messageIndex];
if (!message) break;
const remainingChars = maxChars - includedChars;
const text = message.text.slice(textOffset, textOffset + remainingChars);
const textEnd = textOffset + text.length;
const textComplete = textEnd >= message.text.length;
messages.push({
id: message.id,
role: message.role,
text,
textStart: textOffset,
textEnd,
textComplete,
attachments: [...(message.attachments ?? [])],
createdAt: message.createdAt,
});
includedChars += text.length;
if (!textComplete) {
textOffset = textEnd;
break;
}
messageIndex += 1;
textOffset = 0;
}
return {
threadId: thread.id,
projectId: thread.projectId,
title: thread.title,
messages,
totalMessages: thread.messages.length,
nextCursor: messageIndex < thread.messages.length ? `${messageIndex}:${textOffset}` : null,
};
}
export function hasUserThreadReference(
sourceThread: OrchestrationThread,
environmentId: EnvironmentId,
targetThreadId: ThreadId,
): boolean {
return sourceThread.messages.some(
(message) =>
message.role === "user" &&
collectComposerThreadReferences(message.text).some(
(reference) =>
reference.environmentId === environmentId && reference.threadId === targetThreadId,
),
);
}
export function normalizeThreadReferenceThreadId(
input: ThreadId,
environmentId: EnvironmentId,
): ThreadId {
const parsedLink = parseComposerThreadLink(input);
if (parsedLink?.environmentId === environmentId) {
return ThreadId.make(parsedLink.threadId);
}
const environmentPrefix = `${environmentId}/`;
if (input.startsWith(environmentPrefix)) {
const threadId = input.slice(environmentPrefix.length);
if (threadId && !threadId.includes("/")) {
try {
return ThreadId.make(decodeURIComponent(threadId));
} catch {
return input;
}
}
}
return input;
}
export const threadRead = Effect.fn("ThreadReferenceToolkit.threadRead")(function* (
input: ThreadReferenceReadInput,
) {
const invocation = yield* McpInvocationContext.McpInvocationContext;
const threadId = normalizeThreadReferenceThreadId(input.threadId, invocation.environmentId);
const normalizedInput = { ...input, threadId };
if (!invocation.capabilities.has("thread-reference")) {
return yield* new ThreadReferenceUnavailableError({ threadId });
}
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sourceThreadOption = yield* snapshotQuery
.getThreadDetailById(invocation.threadId)
.pipe(Effect.mapError((cause) => new ThreadReferenceUnavailableError({ threadId, cause })));
if (
Option.isNone(sourceThreadOption) ||
!hasUserThreadReference(sourceThreadOption.value, invocation.environmentId, threadId)
) {
return yield* new ThreadReferenceUnavailableError({ threadId });
}
const threadOption = yield* snapshotQuery
.getThreadDetailById(threadId)
.pipe(Effect.mapError((cause) => new ThreadReferenceUnavailableError({ threadId, cause })));
if (Option.isNone(threadOption)) {
return yield* new ThreadReferenceNotFoundError({ threadId });
}
const page = buildThreadReferencePage(threadOption.value, normalizedInput);
if ("_tag" in page) {
return yield* page;
}
return page;
});
export const ThreadReferenceToolkitHandlersLive = ThreadReferenceToolkit.toLayer({
thread_read: threadRead,
});
@@ -1,24 +0,0 @@
import {
ThreadReferenceReadError,
ThreadReferenceReadInput,
ThreadReferenceReadResult,
} from "@t3tools/contracts";
import { Tool, Toolkit } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
export const ThreadReadTool = Tool.make("thread_read", {
description:
"Read a T3 Code chat thread referenced by a t3-thread link in the user's message. For t3-thread:///ENVIRONMENT_ID/THREAD_ID, pass the final THREAD_ID as threadId. The full t3-thread link and ENVIRONMENT_ID/THREAD_ID are also accepted. The transcript is paginated; when nextCursor is non-null, call thread_read again with that cursor to continue. Do not call this for unrelated threads that the user did not reference.",
parameters: ThreadReferenceReadInput,
success: ThreadReferenceReadResult,
failure: ThreadReferenceReadError,
dependencies: [McpInvocationContext.McpInvocationContext, ProjectionSnapshotQuery],
})
.annotate(Tool.Title, "Read referenced chat thread")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const ThreadReferenceToolkit = Toolkit.make(ThreadReadTool);
@@ -11,13 +11,6 @@ For browser work, first call \`preview_status\`. If no automation-capable previe
Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable. Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.
`; `;
const T3_CODE_THREAD_REFERENCE_INSTRUCTIONS = `
## T3 Code thread references
The user may reference another chat with a \`t3-thread\` link. Do not treat the link as a web URL and do not assume its contents. Use the read-only \`thread_read\` tool from the \`t3-code\` MCP server. For \`t3-thread:///ENVIRONMENT_ID/THREAD_ID\`, pass the final \`THREAD_ID\` path segment as \`threadId\`; the tool also accepts the full link. Follow \`nextCursor\` until you have read as much of the transcript as the task requires.
`;
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational) export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -139,7 +132,6 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec. Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} ${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
${T3_CODE_THREAD_REFERENCE_INSTRUCTIONS}
</collaboration_mode>`; </collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
@@ -154,7 +146,6 @@ The \`request_user_input\` tool is unavailable in Default mode. If you call it w
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} ${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
${T3_CODE_THREAD_REFERENCE_INSTRUCTIONS}
</collaboration_mode>`; </collaboration_mode>`;
export interface CodexRuntimeInfo { export interface CodexRuntimeInfo {
@@ -274,8 +274,6 @@ describe("T3 browser developer instructions", () => {
NodeAssert.match(instructions, /t3-code/); NodeAssert.match(instructions, /t3-code/);
NodeAssert.match(instructions, /preview_status/); NodeAssert.match(instructions, /preview_status/);
NodeAssert.match(instructions, /preview_open/); NodeAssert.match(instructions, /preview_open/);
NodeAssert.match(instructions, /thread_read/);
NodeAssert.match(instructions, /t3-thread/);
NodeAssert.match(instructions, /Do not switch to global browser skills/); NodeAssert.match(instructions, /Do not switch to global browser skills/);
} }
}); });
@@ -668,6 +668,38 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
assert.equal(yield* fileSystem.exists(worktreePath), false); assert.equal(yield* fileSystem.exists(worktreePath), false);
}), }),
); );
it.effect("fails with an actionable error when the base ref has no commit yet", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* GitVcsDriver.GitVcsDriver;
// Initialize a repository but never commit: HEAD is unborn, so there
// is no commit to branch a worktree from.
yield* driver.initRepo({ cwd });
const baseBranch = yield* git(cwd, ["branch", "--show-current"]);
const pathService = yield* Path.Path;
const worktreePath = pathService.join(
yield* makeTmpDir("git-worktrees-"),
"feature-worktree",
);
const error = yield* driver
.createWorktree({
cwd,
path: worktreePath,
refName: baseBranch,
newRefName: "feature/worktree",
})
.pipe(Effect.flip);
assert.equal(error._tag, "GitCommandError");
assert.include(error.detail, "does not point at any commit");
assert.include(error.detail, baseBranch);
// The worktree must not have been created.
const fileSystem = yield* FileSystem.FileSystem;
assert.equal(yield* fileSystem.exists(worktreePath), false);
}),
);
}); });
describe("commit context", () => { describe("commit context", () => {
+18
View File
@@ -2268,6 +2268,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName] ? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
: ["worktree", "add", worktreePath, input.refName]; : ["worktree", "add", worktreePath, input.refName];
// A worktree can only be created from a ref that already points at a commit.
// A freshly-initialized repository (e.g. `git init` with nothing committed
// yet) has an unborn HEAD, so `git worktree add` fails with a cryptic
// "fatal: invalid reference: <ref>". Detect that up front and surface an
// actionable error instead of leaking the raw git failure to the caller.
const baseCommitStdout = yield* runGitStdout(
"GitVcsDriver.createWorktree.resolveBase",
input.cwd,
["rev-parse", "--verify", "--quiet", `${input.refName}^{commit}`],
true,
);
if (baseCommitStdout.trim().length === 0) {
return yield* new GitCommandError({
...gitCommandContext({ operation: "GitVcsDriver.createWorktree", cwd: input.cwd, args }),
detail: `Cannot create a worktree from '${input.refName}' because it does not point at any commit yet. Make an initial commit in this repository, or start the thread in the current checkout instead.`,
});
}
yield* executeGit("GitVcsDriver.createWorktree", input.cwd, args, { yield* executeGit("GitVcsDriver.createWorktree", input.cwd, args, {
fallbackErrorDetail: "git worktree add failed", fallbackErrorDetail: "git worktree add failed",
}); });
+2 -52
View File
@@ -7,18 +7,9 @@ import {
GlobeIcon, GlobeIcon,
Maximize2Icon, Maximize2Icon,
Minimize2Icon, Minimize2Icon,
MessagesSquareIcon,
WrapTextIcon, WrapTextIcon,
} from "lucide-react"; } from "lucide-react";
import { import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
EnvironmentId,
type ScopedThreadRef,
type ServerProviderSkill,
ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { parseComposerThreadLink } from "@t3tools/shared/composerTrigger";
import { useNavigate } from "@tanstack/react-router";
import { import {
isAtomCommandInterrupted, isAtomCommandInterrupted,
squashAtomCommandFailure, squashAtomCommandFailure,
@@ -92,7 +83,6 @@ import {
openUrlInPreview, openUrlInPreview,
BrowserPreviewUnavailableError, BrowserPreviewUnavailableError,
} from "../browser/openFileInPreview"; } from "../browser/openFileInPreview";
import { buildThreadRouteParams } from "../threadRoutes";
class CodeHighlightErrorBoundary extends React.Component< class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode }, { fallback: ReactNode; children: ReactNode },
@@ -171,7 +161,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
}, },
protocols: { protocols: {
...defaultSchema.protocols, ...defaultSchema.protocols,
href: [...(defaultSchema.protocols?.href ?? []), "file", "t3-thread"], href: [...(defaultSchema.protocols?.href ?? []), "file"],
}, },
} satisfies Parameters<typeof rehypeSanitize>[0]; } satisfies Parameters<typeof rehypeSanitize>[0];
@@ -1268,7 +1258,6 @@ function ChatMarkdown({
lineBreaks = false, lineBreaks = false,
}: ChatMarkdownProps) { }: ChatMarkdownProps) {
const { resolvedTheme } = useTheme(); const { resolvedTheme } = useTheme();
const navigate = useNavigate();
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false, reportFailure: false,
}); });
@@ -1303,7 +1292,6 @@ function ChatMarkdown({
return buildFileLinkParentSuffixByPath(filePaths); return buildFileLinkParentSuffixByPath(filePaths);
}, [markdownFileLinkMetaByHref]); }, [markdownFileLinkMetaByHref]);
const markdownUrlTransform = useCallback((href: string) => { const markdownUrlTransform = useCallback((href: string) => {
if (parseComposerThreadLink(href)) return href;
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []); }, []);
// Re-emit highlighted content as markdown so copying out of the rendered // Re-emit highlighted content as markdown so copying out of the rendered
@@ -1403,43 +1391,6 @@ function ChatMarkdown({
}, },
a({ node, href, children, ...props }) { a({ node, href, children, ...props }) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const threadReference = normalizedHref ? parseComposerThreadLink(normalizedHref) : null;
if (threadReference) {
const target = scopeThreadRef(
EnvironmentId.make(threadReference.environmentId),
ThreadId.make(threadReference.threadId),
);
const link = (
<a
{...props}
href={normalizedHref}
className={cn(
CHAT_FILE_TAG_CHIP_CLASS_NAME,
"cursor-pointer gap-1.5 transition-colors hover:bg-accent/70",
)}
data-markdown-copy={`[${plainHastText(node)}](${normalizedHref})`}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(target),
});
}}
>
<MessagesSquareIcon className="size-3.5 shrink-0" aria-hidden="true" />
<span>{children}</span>
</a>
);
return (
<Tooltip>
<TooltipTrigger render={link} />
<TooltipPopup side="top" className="max-w-120 whitespace-normal leading-tight">
Open referenced thread
</TooltipPopup>
</Tooltip>
);
}
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null; const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) { if (!fileLinkMeta) {
const faviconHost = resolveExternalLinkHost(href); const faviconHost = resolveExternalLinkHost(href);
@@ -1592,7 +1543,6 @@ function ChatMarkdown({
fileLinkParentSuffixByPath, fileLinkParentSuffixByPath,
isStreaming, isStreaming,
markdownFileLinkMetaByHref, markdownFileLinkMetaByHref,
navigate,
onTaskListChange, onTaskListChange,
openInPreferredEditor, openInPreferredEditor,
openExternalLinkInPreview, openExternalLinkInPreview,
@@ -6,11 +6,7 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin"; import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin"; import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
import { type ServerProviderSkill } from "@t3tools/contracts"; import { type ServerProviderSkill } from "@t3tools/contracts";
import { import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
serializeComposerFileLink,
serializeComposerThreadLink,
} from "@t3tools/shared/composerTrigger";
import { MessagesSquareIcon } from "lucide-react";
import { import {
$applyNodeReplacement, $applyNodeReplacement,
$createRangeSelectionFromDom, $createRangeSelectionFromDom,
@@ -123,17 +119,6 @@ type SerializedComposerSkillNode = Spread<
SerializedLexicalNode SerializedLexicalNode
>; >;
type SerializedComposerThreadNode = Spread<
{
environmentId: string;
threadId: string;
title: string;
type: "composer-thread";
version: 1;
},
SerializedLexicalNode
>;
type SerializedComposerTerminalContextNode = Spread< type SerializedComposerTerminalContextNode = Spread<
{ {
context: TerminalContextDraft; context: TerminalContextDraft;
@@ -375,103 +360,6 @@ function $createComposerSkillNode(
return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription)); return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription));
} }
function ComposerThreadDecorator(props: { title: string; threadId: string }) {
const chip = (
<span
className={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}
contentEditable={false}
spellCheck={false}
data-composer-thread-chip="true"
>
<MessagesSquareIcon className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} aria-hidden="true" />
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{props.title}</span>
</span>
);
return (
<Tooltip>
<TooltipTrigger render={chip} />
<TooltipPopup side="top" className="max-w-120 whitespace-normal leading-tight">
Thread reference · {props.threadId}
</TooltipPopup>
</Tooltip>
);
}
class ComposerThreadNode extends DecoratorNode<React.ReactElement> {
__environmentId: string;
__threadId: string;
__title: string;
static override getType(): string {
return "composer-thread";
}
static override clone(node: ComposerThreadNode): ComposerThreadNode {
return new ComposerThreadNode(node.__environmentId, node.__threadId, node.__title, node.__key);
}
static override importJSON(serializedNode: SerializedComposerThreadNode): ComposerThreadNode {
return $createComposerThreadNode(
serializedNode.environmentId,
serializedNode.threadId,
serializedNode.title,
).updateFromJSON(serializedNode);
}
constructor(environmentId: string, threadId: string, title: string, key?: NodeKey) {
super(key);
this.__environmentId = environmentId;
this.__threadId = threadId;
this.__title = title;
}
override exportJSON(): SerializedComposerThreadNode {
return {
...super.exportJSON(),
environmentId: this.__environmentId,
threadId: this.__threadId,
title: this.__title,
type: "composer-thread",
version: 1,
};
}
override createDOM(): HTMLElement {
const dom = document.createElement("span");
dom.className = "inline-flex align-middle leading-none";
return dom;
}
override updateDOM(): false {
return false;
}
override getTextContent(): string {
return serializeComposerThreadLink({
environmentId: this.__environmentId,
threadId: this.__threadId,
title: this.__title,
});
}
override isInline(): true {
return true;
}
override decorate(): React.ReactElement {
return <ComposerThreadDecorator title={this.__title} threadId={this.__threadId} />;
}
}
function $createComposerThreadNode(
environmentId: string,
threadId: string,
title: string,
): ComposerThreadNode {
return $applyNodeReplacement(new ComposerThreadNode(environmentId, threadId, title));
}
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) { function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
return <ComposerPendingTerminalContextChip context={props.context} />; return <ComposerPendingTerminalContextChip context={props.context} />;
} }
@@ -539,14 +427,12 @@ function $createComposerTerminalContextNode(
type ComposerInlineTokenNode = type ComposerInlineTokenNode =
| ComposerMentionNode | ComposerMentionNode
| ComposerSkillNode | ComposerSkillNode
| ComposerThreadNode
| ComposerTerminalContextNode; | ComposerTerminalContextNode;
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode { function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
return ( return (
candidate instanceof ComposerMentionNode || candidate instanceof ComposerMentionNode ||
candidate instanceof ComposerSkillNode || candidate instanceof ComposerSkillNode ||
candidate instanceof ComposerThreadNode ||
candidate instanceof ComposerTerminalContextNode candidate instanceof ComposerTerminalContextNode
); );
} }
@@ -958,12 +844,6 @@ function $setComposerEditorPrompt(
); );
continue; continue;
} }
if (segment.type === "thread") {
paragraph.append(
$createComposerThreadNode(segment.environmentId, segment.threadId, segment.title),
);
continue;
}
if (segment.type === "terminal-context") { if (segment.type === "terminal-context") {
if (segment.context) { if (segment.context) {
paragraph.append($createComposerTerminalContextNode(segment.context)); paragraph.append($createComposerTerminalContextNode(segment.context));
@@ -1926,12 +1806,7 @@ export function ComposerPromptEditor({
() => ({ () => ({
namespace: "t3tools-composer-editor", namespace: "t3tools-composer-editor",
editable: true, editable: true,
nodes: [ nodes: [ComposerMentionNode, ComposerSkillNode, ComposerTerminalContextNode],
ComposerMentionNode,
ComposerSkillNode,
ComposerThreadNode,
ComposerTerminalContextNode,
],
editorState: () => { editorState: () => {
$setComposerEditorPrompt( $setComposerEditorPrompt(
initialValueRef.current, initialValueRef.current,
+2 -55
View File
@@ -22,10 +22,7 @@ import {
connectionStatusText, connectionStatusText,
type EnvironmentConnectionPresentation, type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection"; } from "@t3tools/client-runtime/connection";
import { import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
serializeComposerFileLink,
serializeComposerThreadLink,
} from "@t3tools/shared/composerTrigger";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import { import {
memo, memo,
@@ -134,8 +131,6 @@ import { formatProviderSkillDisplayName } from "../../providerSkillPresentation"
import { searchProviderSkills } from "../../providerSkillSearch"; import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useMediaQuery } from "../../hooks/useMediaQuery";
import type { ReviewCommentContext } from "../../reviewCommentContext"; import type { ReviewCommentContext } from "../../reviewCommentContext";
import { useThreadShells } from "../../state/entities";
import { searchThreadReferences } from "../../threadReferenceSearch";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -644,7 +639,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerPreviewAnnotations = composerDraft.previewAnnotations; const composerPreviewAnnotations = composerDraft.previewAnnotations;
const composerReviewComments = composerDraft.reviewComments; const composerReviewComments = composerDraft.reviewComments;
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds; const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const threadShells = useThreadShells();
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage); const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
@@ -1030,30 +1024,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}), }),
); );
} }
if (composerTrigger.kind === "thread") {
const candidates = threadShells.filter(
(thread) => thread.environmentId === environmentId && thread.id !== routeThreadRef.threadId,
);
return searchThreadReferences(candidates, composerTrigger.query).map((thread) => ({
id: `thread:${thread.environmentId}:${thread.id}`,
type: "thread" as const,
environmentId: thread.environmentId,
threadId: thread.id,
title: thread.title,
label: thread.title,
description: thread.branch ?? `Thread ${thread.id}`,
}));
}
return []; return [];
}, [ }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]);
composerTrigger,
environmentId,
routeThreadRef.threadId,
selectedProvider,
selectedProviderStatus,
threadShells,
workspaceEntries.entries,
]);
const composerMenuOpen = Boolean(composerTrigger); const composerMenuOpen = Boolean(composerTrigger);
const composerMenuSearchKey = composerTrigger const composerMenuSearchKey = composerTrigger
@@ -1123,9 +1095,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (composerTriggerKind === "skill") { if (composerTriggerKind === "skill") {
return "No skills found. Try / to browse provider commands."; return "No skills found. Try / to browse provider commands.";
} }
if (composerTriggerKind === "thread") {
return "No matching threads in this environment.";
}
return composerTriggerKind === "path" return composerTriggerKind === "path"
? "No matching files or folders." ? "No matching files or folders."
: "No matching command."; : "No matching command.";
@@ -1627,28 +1596,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
} }
return; return;
} }
if (item.type === "thread") {
const replacement = `${serializeComposerThreadLink({
environmentId: item.environmentId,
threadId: item.threadId,
title: item.title,
})} `;
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
snapshot.value,
trigger.rangeEnd,
replacement,
);
const applied = applyPromptReplacement(
trigger.rangeStart,
replacementRangeEnd,
replacement,
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
);
if (applied) {
setComposerHighlightedItemId(null);
}
return;
}
if (item.type === "slash-command") { if (item.type === "slash-command") {
if (item.command === "model") { if (item.command === "model") {
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
@@ -1,12 +1,10 @@
import { import {
type EnvironmentId,
type ProjectEntry, type ProjectEntry,
type ProviderDriverKind, type ProviderDriverKind,
type ServerProviderSkill, type ServerProviderSkill,
type ServerProviderSlashCommand, type ServerProviderSlashCommand,
type ThreadId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { BotIcon, MessagesSquareIcon } from "lucide-react"; import { BotIcon } from "lucide-react";
import { memo, useLayoutEffect, useMemo, useRef } from "react"; import { memo, useLayoutEffect, useMemo, useRef } from "react";
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
@@ -53,15 +51,6 @@ export type ComposerCommandItem =
skill: ServerProviderSkill; skill: ServerProviderSkill;
label: string; label: string;
description: string; description: string;
}
| {
id: string;
type: "thread";
environmentId: EnvironmentId;
threadId: ThreadId;
title: string;
label: string;
description: string;
}; };
type ComposerCommandGroup = { type ComposerCommandGroup = {
@@ -97,9 +86,6 @@ function groupCommandItems(
if (triggerKind === "skill") { if (triggerKind === "skill") {
return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : []; return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : [];
} }
if (triggerKind === "thread") {
return items.length > 0 ? [{ id: "threads", label: "Threads", items }] : [];
}
if (triggerKind !== "slash-command" || !groupSlashCommandSections) { if (triggerKind !== "slash-command" || !groupSlashCommandSections) {
return [{ id: "default", label: null, items }]; return [{ id: "default", label: null, items }];
} }
@@ -184,20 +170,16 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
</CommandList> </CommandList>
) : ( ) : (
<div className="px-5 py-3.5"> <div className="px-5 py-3.5">
{props.triggerKind === "skill" || props.triggerKind === "thread" ? ( {props.triggerKind === "skill" ? (
<CommandGroup> <CommandGroup>
<CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55"> <CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
{props.triggerKind === "thread" ? "Threads" : "Skills"} Skills
</CommandGroupLabel> </CommandGroupLabel>
<p className="text-muted-foreground/70 text-xs"> <p className="text-muted-foreground/70 text-xs">
{props.isLoading {props.isLoading
? props.triggerKind === "thread" ? "Searching workspace skills..."
? "Searching threads..."
: "Searching workspace skills..."
: (props.emptyStateText ?? : (props.emptyStateText ??
(props.triggerKind === "thread" "No skills found. Try / to browse provider commands.")}
? "No matching threads."
: "No skills found. Try / to browse provider commands."))}
</p> </p>
</CommandGroup> </CommandGroup>
) : ( ) : (
@@ -265,9 +247,6 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
<SkillGlyph className="size-3.5" /> <SkillGlyph className="size-3.5" />
</span> </span>
) : null} ) : null}
{props.item.type === "thread" ? (
<MessagesSquareIcon className="size-4 shrink-0 text-muted-foreground/80" />
) : null}
<span className="flex min-w-0 flex-1 items-center gap-2"> <span className="flex min-w-0 flex-1 items-center gap-2">
<span className="shrink-0">{props.item.label}</span> <span className="shrink-0">{props.item.label}</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs"> <span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs">
@@ -71,24 +71,6 @@ describe("splitPromptIntoComposerSegments", () => {
).toEqual([{ type: "text", text: "Read [the docs](https://example.com/docs) first" }]); ).toEqual([{ type: "text", text: "Read [the docs](https://example.com/docs) first" }]);
}); });
it("splits T3 thread links into thread segments", () => {
expect(
splitPromptIntoComposerSegments(
"Continue from [Prior chat](t3-thread:///environment-1/thread-2) please",
),
).toEqual([
{ type: "text", text: "Continue from " },
{
type: "thread",
environmentId: "environment-1",
threadId: "thread-2",
title: "Prior chat",
source: "[Prior chat](t3-thread:///environment-1/thread-2)",
},
{ type: "text", text: " please" },
]);
});
it("decodes reserved path characters from generated links", () => { it("decodes reserved path characters from generated links", () => {
expect( expect(
splitPromptIntoComposerSegments( splitPromptIntoComposerSegments(
-15
View File
@@ -21,13 +21,6 @@ export type ComposerPromptSegment =
type: "skill"; type: "skill";
name: string; name: string;
} }
| {
type: "thread";
environmentId: string;
threadId: string;
title: string;
source: string;
}
| { | {
type: "terminal-context"; type: "terminal-context";
context: TerminalContextDraft | null; context: TerminalContextDraft | null;
@@ -154,14 +147,6 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen
path: match.value, path: match.value,
source: match.source, source: match.source,
}); });
} else if (match.type === "thread") {
segments.push({
type: "thread",
environmentId: match.environmentId,
threadId: match.threadId,
title: match.title,
source: match.source,
});
} else { } else {
segments.push({ type: "skill", name: match.value }); segments.push({ type: "skill", name: match.value });
} }
-11
View File
@@ -106,17 +106,6 @@ describe("detectComposerTrigger", () => {
}); });
}); });
it("detects #thread trigger at cursor", () => {
const text = "Continue from #auth";
expect(detectComposerTrigger(text, text.length)).toEqual({
kind: "thread",
query: "auth",
rangeStart: "Continue from ".length,
rangeEnd: text.length,
});
});
it("detects @path trigger in the middle of existing text", () => { it("detects @path trigger in the middle of existing text", () => {
// User typed @ between "inspect " and "in this sentence" // User typed @ between "inspect " and "in this sentence"
const text = "Please inspect @in this sentence"; const text = "Please inspect @in this sentence";
+3 -14
View File
@@ -1,7 +1,7 @@
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions"; import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
export type ComposerTriggerKind = "path" | "slash-command" | "skill" | "thread"; export type ComposerTriggerKind = "path" | "slash-command" | "skill";
export type ComposerSlashCommand = "model" | "plan" | "default"; export type ComposerSlashCommand = "model" | "plan" | "default";
export interface ComposerTrigger { export interface ComposerTrigger {
@@ -22,7 +22,6 @@ const isInlineTokenSegment = (
segment: segment:
| { type: "text"; text: string } | { type: "text"; text: string }
| { type: "mention" } | { type: "mention" }
| { type: "thread" }
| { type: "skill" } | { type: "skill" }
| { type: "terminal-context" }, | { type: "terminal-context" },
): boolean => segment.type !== "text"; ): boolean => segment.type !== "text";
@@ -61,7 +60,7 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
let expandedCursor = 0; let expandedCursor = 0;
for (const segment of segments) { for (const segment of segments) {
if (segment.type === "mention" || segment.type === "thread") { if (segment.type === "mention") {
const expandedLength = segment.source.length; const expandedLength = segment.source.length;
if (remaining <= 1) { if (remaining <= 1) {
return expandedCursor + (remaining === 0 ? 0 : expandedLength); return expandedCursor + (remaining === 0 ? 0 : expandedLength);
@@ -103,7 +102,6 @@ function collapsedSegmentLength(
segment: segment:
| { type: "text"; text: string } | { type: "text"; text: string }
| { type: "mention" } | { type: "mention" }
| { type: "thread" }
| { type: "skill" } | { type: "skill" }
| { type: "terminal-context" }, | { type: "terminal-context" },
): number { ): number {
@@ -117,7 +115,6 @@ function clampCollapsedComposerCursorForSegments(
segments: ReadonlyArray< segments: ReadonlyArray<
| { type: "text"; text: string } | { type: "text"; text: string }
| { type: "mention" } | { type: "mention" }
| { type: "thread" }
| { type: "skill" } | { type: "skill" }
| { type: "terminal-context" } | { type: "terminal-context" }
>, >,
@@ -151,7 +148,7 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
let collapsedCursor = 0; let collapsedCursor = 0;
for (const segment of segments) { for (const segment of segments) {
if (segment.type === "mention" || segment.type === "thread") { if (segment.type === "mention") {
const expandedLength = segment.source.length; const expandedLength = segment.source.length;
if (remaining === 0) { if (remaining === 0) {
return collapsedCursor; return collapsedCursor;
@@ -253,14 +250,6 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos
rangeEnd: cursor, rangeEnd: cursor,
}; };
} }
if (token.startsWith("#")) {
return {
kind: "thread",
query: token.slice(1),
rangeStart: tokenStart,
rangeEnd: cursor,
};
}
if (!token.startsWith("@")) { if (!token.startsWith("@")) {
return null; return null;
} }
@@ -1,32 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { searchThreadReferences } from "./threadReferenceSearch";
const thread = (id: string, title: string, updatedAt: string, branch: string | null = null) =>
({ id, title, updatedAt, branch }) as never;
describe("searchThreadReferences", () => {
it("shows recently updated threads when the query is empty", () => {
const result = searchThreadReferences(
[
thread("one", "Older", "2026-01-01T00:00:00.000Z"),
thread("two", "Newer", "2026-02-01T00:00:00.000Z"),
],
"",
);
expect(result.map(({ id }) => id)).toEqual(["two", "one"]);
});
it("ranks title, branch, and id matches", () => {
const threads = [
thread("thread-auth", "Authentication follow-up", "2026-01-01T00:00:00.000Z"),
thread("thread-two", "Unrelated", "2026-01-02T00:00:00.000Z", "feat/auth-flow"),
];
expect(searchThreadReferences(threads, "auth").map(({ id }) => id)).toEqual([
"thread-auth",
"thread-two",
]);
});
});
-53
View File
@@ -1,53 +0,0 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
compareRankedSearchResults,
normalizeSearchQuery,
scoreQueryMatch,
type RankedSearchResult,
} from "@t3tools/shared/searchRanking";
const DEFAULT_THREAD_REFERENCE_LIMIT = 20;
function scoreThread(thread: EnvironmentThreadShell, query: string): number | null {
const fields = [thread.title, thread.branch ?? "", thread.id];
let best: number | null = null;
for (const field of fields) {
const score = scoreQueryMatch({
value: field.toLowerCase(),
query,
exactBase: 0,
prefixBase: 10,
boundaryBase: 30,
includesBase: 50,
fuzzyBase: 100,
});
if (score !== null && (best === null || score < best)) {
best = score;
}
}
return best;
}
export function searchThreadReferences(
threads: ReadonlyArray<EnvironmentThreadShell>,
queryInput: string,
limit = DEFAULT_THREAD_REFERENCE_LIMIT,
): EnvironmentThreadShell[] {
const query = normalizeSearchQuery(queryInput, { trimLeadingPattern: /^#/ });
if (!query) {
return threads
.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt))
.slice(0, limit);
}
const ranked: RankedSearchResult<EnvironmentThreadShell>[] = [];
for (const thread of threads) {
const score = scoreThread(thread, query);
if (score === null) continue;
ranked.push({ item: thread, score, tieBreaker: `${thread.title}:${thread.id}` });
}
return ranked
.sort(compareRankedSearchResults)
.slice(0, limit)
.map(({ item }) => item);
}
-1
View File
@@ -25,5 +25,4 @@ export * from "./assets.ts";
export * from "./review.ts"; export * from "./review.ts";
export * from "./preview.ts"; export * from "./preview.ts";
export * from "./previewAutomation.ts"; export * from "./previewAutomation.ts";
export * from "./threadReference.ts";
export * from "./rpc.ts"; export * from "./rpc.ts";
-95
View File
@@ -1,95 +0,0 @@
import * as Schema from "effect/Schema";
import { ChatAttachment, OrchestrationMessageRole } from "./orchestration.ts";
import {
IsoDateTime,
MessageId,
NonNegativeInt,
ProjectId,
ThreadId,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
export const THREAD_REFERENCE_DEFAULT_MAX_CHARS = 40_000;
export const THREAD_REFERENCE_MAX_CHARS = 80_000;
export const ThreadReferenceCursor = Schema.String.check(
Schema.isPattern(/^\d+:\d+$/, {
description: "Opaque transcript cursor returned by a previous thread_read call.",
}),
);
export type ThreadReferenceCursor = typeof ThreadReferenceCursor.Type;
export const ThreadReferenceReadInput = Schema.Struct({
threadId: ThreadId.annotate({
description:
"Referenced thread id. Prefer the final THREAD_ID path segment; full t3-thread:///ENVIRONMENT_ID/THREAD_ID links and ENVIRONMENT_ID/THREAD_ID are also accepted.",
}),
cursor: Schema.optional(ThreadReferenceCursor).annotate({
description: "nextCursor from the previous page. Omit for the first page.",
}),
maxChars: Schema.optional(
Schema.Int.check(Schema.isGreaterThanOrEqualTo(1_000))
.check(Schema.isLessThanOrEqualTo(THREAD_REFERENCE_MAX_CHARS))
.annotate({
description: `Maximum message-text characters to return. Defaults to ${THREAD_REFERENCE_DEFAULT_MAX_CHARS}; maximum ${THREAD_REFERENCE_MAX_CHARS}.`,
}),
),
});
export type ThreadReferenceReadInput = typeof ThreadReferenceReadInput.Type;
export const ThreadReferenceTranscriptMessage = Schema.Struct({
id: MessageId,
role: OrchestrationMessageRole,
text: Schema.String,
textStart: NonNegativeInt,
textEnd: NonNegativeInt,
textComplete: Schema.Boolean,
attachments: Schema.Array(ChatAttachment),
createdAt: IsoDateTime,
});
export type ThreadReferenceTranscriptMessage = typeof ThreadReferenceTranscriptMessage.Type;
export const ThreadReferenceReadResult = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
messages: Schema.Array(ThreadReferenceTranscriptMessage),
totalMessages: NonNegativeInt,
nextCursor: Schema.NullOr(ThreadReferenceCursor),
});
export type ThreadReferenceReadResult = typeof ThreadReferenceReadResult.Type;
export class ThreadReferenceNotFoundError extends Schema.TaggedErrorClass<ThreadReferenceNotFoundError>()(
"ThreadReferenceNotFoundError",
{ threadId: ThreadId },
) {
override get message(): string {
return `Referenced thread '${this.threadId}' was not found.`;
}
}
export class ThreadReferenceInvalidCursorError extends Schema.TaggedErrorClass<ThreadReferenceInvalidCursorError>()(
"ThreadReferenceInvalidCursorError",
{ threadId: ThreadId, cursor: Schema.String },
) {
override get message(): string {
return `Cursor '${this.cursor}' is invalid for referenced thread '${this.threadId}'.`;
}
}
export class ThreadReferenceUnavailableError extends Schema.TaggedErrorClass<ThreadReferenceUnavailableError>()(
"ThreadReferenceUnavailableError",
{ threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
) {
override get message(): string {
return `Referenced thread '${this.threadId}' could not be read.`;
}
}
export const ThreadReferenceReadError = Schema.Union([
ThreadReferenceNotFoundError,
ThreadReferenceInvalidCursorError,
ThreadReferenceUnavailableError,
]);
export type ThreadReferenceReadError = typeof ThreadReferenceReadError.Type;
@@ -3,9 +3,8 @@ import { describe, expect, it } from "vite-plus/test";
import { collectComposerInlineTokens } from "./composerInlineTokens.ts"; import { collectComposerInlineTokens } from "./composerInlineTokens.ts";
describe("collectComposerInlineTokens", () => { describe("collectComposerInlineTokens", () => {
it("collects file links, mentions, skills, and thread references with source ranges", () => { it("collects file links, mentions, and skills with source ranges", () => {
const text = const text = "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md please";
"Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md then [Prior chat](t3-thread:///env-1/thread-2) please";
expect(collectComposerInlineTokens(text)).toEqual([ expect(collectComposerInlineTokens(text)).toEqual([
{ {
@@ -29,16 +28,6 @@ describe("collectComposerInlineTokens", () => {
start: 50, start: 50,
end: 60, end: 60,
}, },
{
type: "thread",
environmentId: "env-1",
threadId: "thread-2",
title: "Prior chat",
value: "Prior chat",
source: "[Prior chat](t3-thread:///env-1/thread-2)",
start: 66,
end: 107,
},
]); ]);
}); });
@@ -92,42 +81,4 @@ describe("collectComposerInlineTokens", () => {
it("ignores normal web links", () => { it("ignores normal web links", () => {
expect(collectComposerInlineTokens("Read [docs](https://example.com) first")).toEqual([]); expect(collectComposerInlineTokens("Read [docs](https://example.com) first")).toEqual([]);
}); });
it("ignores malformed thread links", () => {
expect(collectComposerInlineTokens("Read [chat](t3-thread:///missing) first")).toEqual([]);
});
it("collects a complete thread reference at the end of the prompt", () => {
expect(
collectComposerInlineTokens("Read [chat](t3-thread:///environment-1/thread-1)"),
).toMatchObject([
{
type: "thread",
environmentId: "environment-1",
threadId: "thread-1",
title: "chat",
},
]);
});
it.each([".", ",", ";", ":", "!", "?", ")", '"'])(
"collects a thread reference followed by %s without consuming the punctuation",
(punctuation) => {
const reference = "[chat](t3-thread:///environment-1/thread-1)";
const text = `Read ${reference}${punctuation}`;
const referenceEnd = 5 + reference.length;
expect(collectComposerInlineTokens(text)).toMatchObject([
{
type: "thread",
environmentId: "environment-1",
threadId: "thread-1",
source: reference,
start: 5,
end: referenceEnd,
},
]);
expect(text.slice(referenceEnd)).toBe(punctuation);
},
);
}); });
+1 -46
View File
@@ -1,5 +1,3 @@
import { parseComposerThreadLink } from "./composerTrigger.ts";
export type ComposerInlineToken = export type ComposerInlineToken =
| { | {
readonly type: "mention"; readonly type: "mention";
@@ -14,61 +12,18 @@ export type ComposerInlineToken =
readonly source: string; readonly source: string;
readonly start: number; readonly start: number;
readonly end: number; readonly end: number;
}
| {
readonly type: "thread";
readonly environmentId: string;
readonly threadId: string;
readonly title: string;
readonly value: string;
readonly source: string;
readonly start: number;
readonly end: number;
}; };
export interface CollectComposerInlineTokensOptions { export interface CollectComposerInlineTokensOptions {
readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>; readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
} }
type ComposerThreadInlineToken = Extract<ComposerInlineToken, { type: "thread" }>;
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g; const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g;
const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g; const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g; const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g;
const THREAD_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\((t3-thread:\/\/\/[^)\s]+)\)/g;
const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/; const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/; const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
export function collectComposerThreadReferences(
text: string,
): ReadonlyArray<ComposerThreadInlineToken> {
const matches: ComposerThreadInlineToken[] = [];
for (const match of text.matchAll(THREAD_LINK_TOKEN_REGEX)) {
const fullMatch = match[0];
const prefix = match[1] ?? "";
const title = (match[2] ?? "").replace(/\\(.)/g, "$1");
const destination = match[3] ?? "";
const reference = parseComposerThreadLink(destination);
if (reference && title) {
const start = (match.index ?? 0) + prefix.length;
const end = start + fullMatch.length - prefix.length;
matches.push({
type: "thread",
environmentId: reference.environmentId,
threadId: reference.threadId,
title,
value: title,
source: text.slice(start, end),
start,
end,
});
}
}
return matches;
}
function collectMentionTokens(text: string): ComposerInlineToken[] { function collectMentionTokens(text: string): ComposerInlineToken[] {
const matches: ComposerInlineToken[] = []; const matches: ComposerInlineToken[] = [];
@@ -126,7 +81,7 @@ export function collectComposerInlineTokens(
text: string, text: string,
options: CollectComposerInlineTokensOptions = {}, options: CollectComposerInlineTokensOptions = {},
): ReadonlyArray<ComposerInlineToken> { ): ReadonlyArray<ComposerInlineToken> {
const matches = [...collectMentionTokens(text), ...collectComposerThreadReferences(text)]; const matches = collectMentionTokens(text);
for (const match of text.matchAll(SKILL_TOKEN_REGEX)) { for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
const fullMatch = match[0]; const fullMatch = match[0];
+1 -45
View File
@@ -1,4 +1,4 @@
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill" | "thread"; export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill";
export type ComposerSlashCommand = "model" | "plan" | "default"; export type ComposerSlashCommand = "model" | "plan" | "default";
export interface ComposerTrigger { export interface ComposerTrigger {
@@ -35,42 +35,6 @@ function encodeMarkdownLinkDestination(path: string): string {
.replaceAll("\\", "%5C"); .replaceAll("\\", "%5C");
} }
export interface ComposerThreadReference {
readonly environmentId: string;
readonly threadId: string;
readonly title: string;
}
export const COMPOSER_THREAD_REFERENCE_SCHEME = "t3-thread:";
export function parseComposerThreadLink(
destination: string,
): Pick<ComposerThreadReference, "environmentId" | "threadId"> | null {
try {
const url = new URL(destination);
const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
const [environmentId, threadId] = segments;
if (
url.protocol !== COMPOSER_THREAD_REFERENCE_SCHEME ||
!environmentId ||
!threadId ||
segments.length !== 2
) {
return null;
}
return { environmentId, threadId };
} catch {
return null;
}
}
export function serializeComposerThreadLink(reference: ComposerThreadReference): string {
const label = escapeMarkdownLinkLabel(reference.title);
const environmentId = encodeURIComponent(reference.environmentId);
const threadId = encodeURIComponent(reference.threadId);
return `[${label}](${COMPOSER_THREAD_REFERENCE_SCHEME}///${environmentId}/${threadId})`;
}
export function serializeComposerFileLink(path: string): string { export function serializeComposerFileLink(path: string): string {
const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path)); const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path));
return `[${label}](${encodeMarkdownLinkDestination(path)})`; return `[${label}](${encodeMarkdownLinkDestination(path)})`;
@@ -148,14 +112,6 @@ export function detectComposerTrigger(
rangeEnd: cursor, rangeEnd: cursor,
}; };
} }
if (token.startsWith("#")) {
return {
kind: "thread",
query: token.slice(1),
rangeStart: tokenStart,
rangeEnd: cursor,
};
}
if (!token.startsWith("@")) { if (!token.startsWith("@")) {
return null; return null;
} }