Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e2309c1afc fix(terminal): address ghostty refresh review
Co-authored-by: codex <[email protected]>
2026-07-20 18:16:32 +02:00
Pixel Perfect 2bc4029e81 Keep scroll anchor stable at the scrollback cap and fix config order
- Once scrollback is full its length stops growing while writes keep
  evicting lines, so the preserved viewport drifted toward the tail;
  fall back to counting written newlines at the cap
- Parse config.ghostty before config so config wins conflicts, matching
  Ghostty's own load order
2026-07-20 18:05:01 +02:00
Pixel Perfect 4f4a2ede59 Address second-round review findings
- Preserve a scrolled-back viewport when session output arrives:
  ghostty-web snaps to the bottom on every write, so re-anchor the
  viewport by the number of lines the write pushed into scrollback
- Read both config and config.ghostty when they coexist in a Ghostty
  config directory instead of letting the first shadow the second
- Linkify mailto/ftp/ssh/git/tel/magnet/gemini/gopher/news URLs in the
  terminal and open non-http schemes with the OS handler, keeping the
  in-app preview flow for http(s)
2026-07-20 18:05:01 +02:00
Pixel Perfect 36d1cc6578 Re-run session sync after WASM init and merge Ghostty config files
- Bump a terminal epoch when the deferred WASM setup finishes so the
  session sync effect re-runs against the live terminal even when no
  session field changed during the load, completing the exited-at-mount
  handling
- Read config.ghostty as an alternate config file name and merge the
  XDG and macOS Application Support configs in Ghostty's load order
  instead of stopping at the first existing file
2026-07-20 18:05:01 +02:00
Pixel Perfect c1caaa3520 Handle init failure surfacing and empty XDG_CONFIG_HOME
- Attach a rejection handler to the terminal WASM init so a load
  failure logs, shows a message in the viewport, and clears on retry
  instead of leaving a blank pane and an unhandled rejection
- Treat an empty XDG_CONFIG_HOME as unset per the XDG spec instead of
  resolving the Ghostty config relative to the server cwd
2026-07-20 18:05:01 +02:00
Pixel Perfect 7266fafbf6 Address review findings on the ghostty-web terminal
- Retry WASM init on a later mount instead of caching a rejected
  promise until page reload
- Blur non-active terminals after open(): ghostty-web focuses
  unconditionally, letting the last-mounted split steal focus
- Seed the session snapshot with version 0 and a closed status at mount
  so an already-exited session still surfaces its exit and closes the
  viewport
- Keep CSS generic font keywords (monospace, system-ui, ...) unquoted
  when building the terminal font stack
- Resolve named Ghostty themes from the Linux system dirs
  (/usr/share/ghostty/themes, /usr/local/share/ghostty/themes) too
2026-07-20 18:05:01 +02:00
Pixel Perfect a6ff5725cc Allow WebAssembly in the desktop renderer CSP
The desktop protocol's Content-Security-Policy blocked the ghostty-web
terminal from initializing: script-src had no 'wasm-unsafe-eval', so
WebAssembly compilation was rejected, and connect-src had no data:, so
the library's embedded WASM payload fetch failed. Add both sources.
2026-07-20 18:05:01 +02:00
Pixel Perfect 87998f7c2a Replace xterm.js with ghostty-web in the web terminal
Swap the thread terminal drawer from @xterm/xterm to ghostty-web, the
libghostty-vt based drop-in. The server terminal protocol is unchanged;
the swap is contained to the client renderer:

- Gate terminal creation on the ghostty-web WASM init and replay the
  session buffer that arrives before it resolves
- Invert custom key handler returns (ghostty-web treats true as
  "consumed", the opposite of xterm.js)
- Convert link provider rows/ranges between the 1-based terminal-links
  helpers and ghostty-web's 0-based coordinates, and drop the built-in
  providers whose activate() bypasses the app's preview flow
- Guard zero-length writes: ghostty-web 0.4.0 alloc(0) returns an
  out-of-bounds pointer and crashes on status-only session updates
- Adapt at-bottom checks to ghostty-web's inverted viewportY semantics

Also style the terminal from the user's local Ghostty config when one
exists: the server parses font-family/font-size/theme (resolving named
themes from the user themes dir or the Ghostty.app bundle) into an
optional ServerConfig.terminalStyle field, and the drawer applies it
over the app-derived defaults. Nerd Font fallbacks cover powerline and
devicon glyphs, and the mount is painted with the theme background so
partial-cell fringes match the canvas.
2026-07-20 18:05:01 +02:00
47 changed files with 1175 additions and 1868 deletions

No files matched your search

@@ -57,11 +57,11 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
"connect-src 'self' data: http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,10 +212,18 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["connect-src"], [
"'self'",
"data:",
"http:",
"https:",
"ws:",
"wss:",
]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
@@ -71,6 +71,8 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
// Required to compile the ghostty-web terminal's WebAssembly module.
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -79,7 +81,8 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
// data: allows ghostty-web to fetch its embedded WebAssembly payload.
const connectSources = ["'self'", "data:", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
@@ -1,20 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
describe("buildAssetResponseHeaders", () => {
it("forces non-image assets to download without overriding the client filename", () => {
expect(buildAssetResponseHeaders({ download: true })).toEqual({
"Cache-Control": "private, max-age=3600",
"Content-Disposition": "attachment",
"X-Content-Type-Options": "nosniff",
});
});
it("does not force image assets to download", () => {
expect(buildAssetResponseHeaders({ download: false })).toEqual({
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
});
});
});
-7
View File
@@ -1,7 +0,0 @@
export function buildAssetResponseHeaders(input: { readonly download?: boolean }) {
return {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
...(input.download ? { "Content-Disposition": "attachment" } : {}),
};
}
@@ -198,32 +198,6 @@ describe("AssetAccess", () => {
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
kind: "file",
path: attachmentPath,
download: false,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("marks non-image attachment capabilities for download", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002";
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
const result = yield* issueAssetUrl({
resource: { _tag: "attachment", attachmentId },
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({
kind: "file",
path: attachmentPath,
download: true,
});
}).pipe(Effect.provide(testLayer)),
);
+4 -17
View File
@@ -36,7 +36,6 @@ import {
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import { SAFE_IMAGE_FILE_EXTENSIONS } from "../imageMime.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -92,11 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = {
readonly kind: "file";
readonly path: string;
readonly download?: boolean;
};
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -388,17 +383,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
),
Effect.orElseSucceed(() => Option.none()),
);
if (!Option.isSome(info) || info.value.type !== "File") {
return null;
}
// Non-image attachments are downloaded rather than rendered inline so the
// same-origin asset route never interprets uploaded content (e.g. HTML/XML).
const extension = attachmentPath.slice(attachmentPath.lastIndexOf(".")).toLowerCase();
return {
kind: "file",
path: attachmentPath,
download: !SAFE_IMAGE_FILE_EXTENSIONS.has(extension),
} satisfies ResolvedAsset;
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "project-favicon") {
-97
View File
@@ -1,97 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts";
const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt");
describe("attachmentPrompt", () => {
it("appends a prompt line for file attachments", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 2048,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000001.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`,
);
});
it("returns text unchanged when only image attachments are present", () => {
expect(
appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "image",
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
},
],
}),
).toBe("hello");
});
it("returns only the prompt lines when the text is empty", () => {
const result = appendFileAttachmentPromptText({
text: "",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000003",
name: "data.csv",
mimeType: "text/csv",
sizeBytes: 12,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.csv",
);
expect(result).toBe(
`[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`,
);
});
it("strips control characters, brackets, and parentheses from attachment names", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000004",
name: "a(b)\u0001[c].txt",
mimeType: "text/plain",
sizeBytes: 5,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000004.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`,
);
});
});
-55
View File
@@ -1,55 +0,0 @@
import type { ChatAttachment } from "@t3tools/contracts";
import { resolveAttachmentPath } from "./attachmentStore.ts";
const SIZE_LABEL_UNITS = ["B", "KB", "MB"] as const;
function formatSizeLabel(sizeBytes: number): string {
let value = sizeBytes;
let unitIndex = 0;
while (value >= 1024 && unitIndex < SIZE_LABEL_UNITS.length - 1) {
value /= 1024;
unitIndex += 1;
}
const rounded = unitIndex === 0 ? String(value) : value.toFixed(1);
return `${rounded} ${SIZE_LABEL_UNITS[unitIndex]}`;
}
function sanitizePromptFileName(name: string): string {
// eslint-disable-next-line no-control-regex
return name.replace(/[\u0000-\u001f\u007f()[\]]+/gu, " ").trim();
}
/**
* Non-image attachments are delivered by reference: the file already lives on
* the server's disk, so the provider agent reads it with its own tools. Images
* keep their native content-block path and are not mentioned here.
*/
export function appendFileAttachmentPromptText(input: {
readonly text: string;
readonly attachmentsDir: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
}): string {
const lines: Array<string> = [];
for (const attachment of input.attachments) {
if (attachment.type !== "file") {
continue;
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: input.attachmentsDir,
attachment,
});
if (!attachmentPath) {
continue;
}
const name = sanitizePromptFileName(attachment.name);
lines.push(
`[Attached file: ${attachmentPath} (${name}, ${attachment.mimeType}, ${formatSizeLabel(attachment.sizeBytes)}). Read it from disk when needed.]`,
);
}
if (lines.length === 0) {
return input.text;
}
const joined = lines.join("\n");
return input.text.trim().length > 0 ? `${input.text}\n\n${joined}` : joined;
}
-32
View File
@@ -6,7 +6,6 @@ import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import {
attachmentRelativePath,
createAttachmentId,
parseThreadSegmentFromAttachmentId,
resolveAttachmentPathById,
@@ -45,37 +44,6 @@ describe("attachmentStore", () => {
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
});
it("builds file attachment relative paths with the inferred file extension", () => {
expect(
attachmentRelativePath({
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
}),
).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf");
});
it("resolves attachment path by id for a written file attachment extension", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const attachmentId = "thread-1-attachment";
const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`);
NodeFS.writeFileSync(pdfPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId,
});
expect(resolved).toBe(pdfPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+2 -16
View File
@@ -8,16 +8,9 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import {
inferFileExtension,
inferImageExtension,
SAFE_FILE_EXTENSIONS,
SAFE_IMAGE_FILE_EXTENSIONS,
} from "./imageMime.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [
...new Set([...SAFE_IMAGE_FILE_EXTENSIONS, ...SAFE_FILE_EXTENSIONS, ".bin"]),
];
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -70,13 +63,6 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
});
return `${attachment.id}${extension}`;
}
case "file": {
const extension = inferFileExtension({
mimeType: attachment.mimeType,
fileName: attachment.name,
});
return `${attachment.id}${extension}`;
}
}
}
+4 -2
View File
@@ -25,7 +25,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -195,7 +194,10 @@ export const assetRouteLayer = HttpRouter.add(
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: buildAssetResponseHeaders(asset),
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
+1 -36
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
@@ -92,39 +92,4 @@ describe("imageMime", () => {
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
it("infers file extension from an allowlisted file name extension", () => {
expect(
inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }),
).toBe(".pdf");
});
it("infers file extension from the last segment of a multi-dot file name", () => {
expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe(
".csv",
);
});
it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => {
expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf");
});
it("falls back to an allowlisted mime extension when the file name has no extension", () => {
expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt");
});
it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe(
".bin",
);
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe(
".bin",
);
});
it("defaults dotfile names without an allowlisted mime to .bin", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe(
".bin",
);
});
});
-42
View File
@@ -112,48 +112,6 @@ export function parseBase64DataUrl(
return { mimeType, base64 };
}
export const SAFE_FILE_EXTENSIONS = new Set([
".csv",
".diff",
".docx",
".gz",
".json",
".jsonl",
".log",
".md",
".patch",
".pdf",
".pptx",
".tar",
".toml",
".tsv",
".txt",
".xlsx",
".xml",
".yaml",
".yml",
".zip",
]);
export function inferFileExtension(input: { mimeType: string; fileName?: string }): string {
const fileName = input.fileName?.trim() ?? "";
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
if (SAFE_FILE_EXTENSIONS.has(fileNameExtension)) {
return fileNameExtension;
}
// Mime.getExtension returns dot-less extensions ("pdf"), the sets hold
// dotted ones (".pdf").
const fromMimeExtension = Mime.getExtension(input.mimeType);
const dottedMimeExtension = fromMimeExtension ? `.${fromMimeExtension}` : null;
if (dottedMimeExtension && SAFE_FILE_EXTENSIONS.has(dottedMimeExtension)) {
return dottedMimeExtension;
}
return ".bin";
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -928,214 +928,6 @@ it.layer(
);
});
it.layer(
Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")),
)("OrchestrationProjectionPipeline", (it) => {
it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const { attachmentsDir } = yield* ServerConfig;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("Thread Revert.Docs");
const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001";
const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002";
const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003";
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-revert-docs-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-revert-docs"),
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-revert-docs"),
title: "Project Revert Docs",
workspaceRoot: "/tmp/project-revert-docs",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-revert-docs-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-revert-docs"),
title: "Thread Revert Docs",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-3"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-keep"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-keep"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-4"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-keep"),
role: "assistant",
text: "Keep",
attachments: [
{
type: "file",
id: keepAttachmentId,
name: "keep.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-5"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-5"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-remove"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-remove"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-6"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-6"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-remove"),
role: "assistant",
text: "Remove",
attachments: [
{
type: "file",
id: removeAttachmentId,
name: "remove.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`);
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`);
const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`);
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
yield* fileSystem.writeFileString(keepPath, "keep");
yield* fileSystem.writeFileString(removePath, "remove");
yield* fileSystem.writeFileString(orphanPath, "orphan");
assert.isTrue(yield* exists(keepPath));
assert.isTrue(yield* exists(removePath));
assert.isTrue(yield* exists(orphanPath));
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.make("evt-revert-docs-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-7"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-7"),
metadata: {},
payload: {
threadId,
turnCount: 1,
},
});
assert.isTrue(yield* exists(keepPath));
assert.isFalse(yield* exists(removePath));
assert.isFalse(yield* exists(orphanPath));
}),
);
});
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))(
"OrchestrationProjectionPipeline",
(it) => {
@@ -338,6 +338,9 @@ function collectThreadAttachmentRelativePaths(
const relativePaths = new Set<string>();
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
continue;
@@ -466,58 +466,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect(
"sends only image attachments to the provider and appends file attachment prompt text",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const imageAttachment = {
type: "image" as const,
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
};
const fileAttachment = {
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 5,
};
const attachmentsDir = NodePath.join(harness.stateDir, "attachments");
const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`);
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
NodeFS.writeFileSync(fileAttachmentPath, "notes");
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-file-attachments"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-file-attachments"),
role: "user",
text: "hello with attachments",
attachments: [imageAttachment, fileAttachment],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
const request = harness.sendTurn.mock.calls[0]?.[0] as {
readonly input?: string;
readonly attachments?: ReadonlyArray<unknown>;
};
expect(request.attachments).toEqual([imageAttachment]);
expect(request.input).toBe(
`hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`,
);
}),
);
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -25,9 +25,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { appendFileAttachmentPromptText } from "../../attachmentPrompt.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
@@ -198,7 +196,6 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const serverCommandId = (tag: string) =>
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
@@ -608,18 +605,8 @@ const make = Effect.gen(function* () {
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(
appendFileAttachmentPromptText({
text: input.messageText,
attachmentsDir: serverConfig.attachmentsDir,
attachments: input.attachments ?? [],
}),
);
// Only image attachments go to the provider as content blocks; file
// attachments are delivered by path in the prompt text above.
const normalizedAttachments = (input.attachments ?? []).filter(
(attachment) => attachment.type === "image",
);
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
.pipe(
@@ -1,53 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "vite-plus/test";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ClientOrchestrationCommand,
MessageId,
ProjectId,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProviderInstanceId,
ThreadId,
type ClientOrchestrationCommand,
type UploadChatAttachment,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }),
WorkspacePaths.layer,
).pipe(Layer.provideMerge(NodeServices.layer));
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
const now = "2026-01-01T00:00:00.000Z";
const turnStartCommand = (
attachments: ReadonlyArray<UploadChatAttachment>,
): ClientOrchestrationCommand => ({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("user-message-1"),
role: "user",
text: "hello normalizer",
attachments,
},
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
createdAt: now,
});
const asDataUrl = (mimeType: string, bytes: Buffer) =>
`data:${mimeType};base64,${bytes.toString("base64")}`;
describe("canonicalizeClientCommandTimestamps", () => {
it("replaces a client command timestamp with the server receipt timestamp", () => {
@@ -107,86 +71,3 @@ describe("canonicalizeClientCommandTimestamps", () => {
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
});
});
describe("Normalizer", () => {
it.effect("persists file attachments and writes their bytes to the attachments dir", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("hello world");
const normalized = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
);
expect(normalized.type).toBe("thread.turn.start");
if (normalized.type !== "thread.turn.start") {
return;
}
const attachment = normalized.message.attachments[0];
expect(attachment).toMatchObject({
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
});
expect(attachment?.id).toMatch(
/^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
if (!attachment) {
return;
}
const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`);
expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects image attachments with a non-image data URL mime type", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "image",
name: "fake.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: asDataUrl("text/plain", Buffer.from("hello")),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Invalid image attachment payload for 'fake.png'.");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects file attachments over the maximum attachment size", () =>
Effect.gen(function* () {
const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a");
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "big.txt",
mimeType: "text/plain",
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Attachment 'big.txt' is empty or too large.");
}).pipe(Effect.provide(testLayer)),
);
});
+4 -4
View File
@@ -109,16 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' is empty or too large.`,
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
@@ -130,7 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
}
const persistedAttachment = {
type: attachment.type,
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vite-plus/test";
import {
ghosttyThemeSearchPaths,
parseGhosttyConfig,
splitThemeSelection,
} from "./ghosttyStyle.ts";
const posixPath = {
isAbsolute: (value: string) => value.startsWith("/"),
join: (...segments: ReadonlyArray<string>) =>
segments
.map((segment, index) =>
index === 0 ? segment.replace(/\/$/, "") : segment.replace(/^\//, ""),
)
.join("/"),
};
const windowsPath = {
isAbsolute: (value: string) => /^[A-Za-z]:[\\/]/.test(value),
join: (...segments: ReadonlyArray<string>) => segments.join("\\"),
};
describe("parseGhosttyConfig", () => {
it("omits empty scalar color assignments", () => {
const config = parseGhosttyConfig(`
background =
foreground = ""
cursor-color = #c0ffee
`);
expect(config.colors.background).toBeUndefined();
expect(config.colors.foreground).toBeUndefined();
expect(config.colors.cursor).toBe("#c0ffee");
});
});
describe("splitThemeSelection", () => {
it("keeps a Windows absolute theme path as a bare selection", () => {
expect(splitThemeSelection("C:/Users/Alex/Ghostty Themes/t3code")).toEqual({
light: "C:/Users/Alex/Ghostty Themes/t3code",
dark: "C:/Users/Alex/Ghostty Themes/t3code",
});
});
it("still parses explicit light and dark theme selections", () => {
expect(splitThemeSelection("light:Day,dark:Night")).toEqual({
light: "Day",
dark: "Night",
});
});
});
describe("ghosttyThemeSearchPaths", () => {
it("searches beside the macOS Application Support config", () => {
const candidates = ghosttyThemeSearchPaths(posixPath, {
home: "/Users/alex",
xdgConfigHome: "/Users/alex/.config",
themeName: "t3code",
});
expect(candidates).toContain(
"/Users/alex/Library/Application Support/com.mitchellh.ghostty/themes/t3code",
);
});
it("tries an absolute theme file before named-theme directories", () => {
const candidates = ghosttyThemeSearchPaths(windowsPath, {
home: "C:\\Users\\alex",
xdgConfigHome: "C:\\Users\\alex\\.config",
themeName: "D:\\themes\\t3code",
});
expect(candidates[0]).toBe("D:\\themes\\t3code");
});
});
+289
View File
@@ -0,0 +1,289 @@
import * as NodeOS from "node:os";
import type { ServerTerminalStyle, ServerTerminalThemeColors } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
const PALETTE_SIZE = 16;
interface GhosttyConfigValues {
readonly fontFamily: ReadonlyArray<string>;
readonly fontSize: number | undefined;
readonly theme: string | undefined;
readonly colors: MutableThemeColors;
}
interface MutableThemeColors {
background?: string | undefined;
foreground?: string | undefined;
cursor?: string | undefined;
selectionBackground?: string | undefined;
selectionForeground?: string | undefined;
palette: Array<string>;
}
function emptyColors(): MutableThemeColors {
return { palette: Array.from({ length: PALETTE_SIZE }, () => "") };
}
function stripQuotes(value: string): string {
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, -1);
}
return value;
}
function applyColorEntry(colors: MutableThemeColors, key: string, value: string): void {
// Empty assignments are resets, not colors. Keeping an empty scalar here
// would later violate ServerConfig's TrimmedNonEmptyString schema and make
// the whole server.getConfig response fail to encode.
if (value.length === 0) return;
switch (key) {
case "background":
colors.background = value;
return;
case "foreground":
colors.foreground = value;
return;
case "cursor-color":
colors.cursor = value;
return;
case "selection-background":
colors.selectionBackground = value;
return;
case "selection-foreground":
colors.selectionForeground = value;
return;
case "palette": {
const match = value.match(/^(\d+)\s*=\s*(\S+)$/);
if (!match) return;
const index = Number(match[1]);
if (!Number.isInteger(index) || index < 0 || index >= PALETTE_SIZE) return;
colors.palette[index] = match[2] ?? "";
return;
}
default:
return;
}
}
/** Parse Ghostty's `key = value` config format, keeping only what the web terminal uses. */
export function parseGhosttyConfig(source: string): GhosttyConfigValues {
const fontFamily: Array<string> = [];
let fontSize: number | undefined;
let theme: string | undefined;
const colors = emptyColors();
for (const rawLine of source.split("\n")) {
const line = rawLine.trim();
if (line.length === 0 || line.startsWith("#")) continue;
const separatorIndex = line.indexOf("=");
if (separatorIndex <= 0) continue;
const key = line.slice(0, separatorIndex).trim();
const value = stripQuotes(line.slice(separatorIndex + 1).trim());
switch (key) {
case "font-family":
// Repeated entries build a fallback chain; an empty value resets it.
if (value.length === 0) {
fontFamily.length = 0;
} else {
fontFamily.push(value);
}
break;
case "font-size": {
const parsed = Number(value);
if (Number.isFinite(parsed) && parsed > 0) {
fontSize = parsed;
}
break;
}
case "theme":
theme = value.length > 0 ? value : undefined;
break;
default:
applyColorEntry(colors, key, value);
break;
}
}
return { fontFamily, fontSize, theme, colors };
}
/** Split `theme = light:A,dark:B` into per-mode names; a bare name applies to both. */
export function splitThemeSelection(theme: string): { light?: string; dark?: string } {
const result: { light?: string; dark?: string } = {};
let hasModeSelection = false;
for (const part of theme.split(",")) {
const match = /^\s*(light|dark):(.*)$/.exec(part);
if (!match) continue;
const mode = match[1];
const name = (match[2] ?? "").trim();
if (name.length === 0) continue;
hasModeSelection = true;
if (mode === "light") result.light = name;
if (mode === "dark") result.dark = name;
}
// A colon is also part of a Windows drive path (C:/theme), and may be part
// of another valid bare theme identifier. Only enter per-mode parsing when
// an explicit light: or dark: selection was recognized.
return hasModeSelection ? result : { light: theme, dark: theme };
}
function hasAnyColor(colors: MutableThemeColors): boolean {
return (
colors.background !== undefined ||
colors.foreground !== undefined ||
colors.cursor !== undefined ||
colors.selectionBackground !== undefined ||
colors.selectionForeground !== undefined ||
colors.palette.some((entry) => entry.length > 0)
);
}
function mergeColors(base: MutableThemeColors, override: MutableThemeColors): MutableThemeColors {
return {
background: override.background ?? base.background,
foreground: override.foreground ?? base.foreground,
cursor: override.cursor ?? base.cursor,
selectionBackground: override.selectionBackground ?? base.selectionBackground,
selectionForeground: override.selectionForeground ?? base.selectionForeground,
palette: base.palette.map((entry, index) => {
const overrideEntry = override.palette[index] ?? "";
return overrideEntry.length > 0 ? overrideEntry : entry;
}),
};
}
function toThemeColors(colors: MutableThemeColors): ServerTerminalThemeColors | undefined {
if (!hasAnyColor(colors)) return undefined;
return {
...(colors.background !== undefined ? { background: colors.background } : {}),
...(colors.foreground !== undefined ? { foreground: colors.foreground } : {}),
...(colors.cursor !== undefined ? { cursor: colors.cursor } : {}),
...(colors.selectionBackground !== undefined
? { selectionBackground: colors.selectionBackground }
: {}),
...(colors.selectionForeground !== undefined
? { selectionForeground: colors.selectionForeground }
: {}),
palette: colors.palette,
};
}
// Bundled theme locations by platform: the macOS app bundle and the
// Linux system resource dirs documented by Ghostty.
const GHOSTTY_SYSTEM_THEME_DIRS = [
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
];
export function ghosttyThemeSearchPaths(
path: Pick<Path.Path, "isAbsolute" | "join">,
input: { readonly home: string; readonly xdgConfigHome: string; readonly themeName: string },
): ReadonlyArray<string> {
return [
...(path.isAbsolute(input.themeName) ? [input.themeName] : []),
path.join(input.xdgConfigHome, "ghostty", "themes", input.themeName),
path.join(
input.home,
"Library",
"Application Support",
"com.mitchellh.ghostty",
"themes",
input.themeName,
),
...GHOSTTY_SYSTEM_THEME_DIRS.map((dir) => path.join(dir, input.themeName)),
];
}
/**
* Load terminal font and theme colors from the user's local Ghostty config.
* Best effort by design: any missing file or parse problem yields `undefined`
* so the client falls back to its built-in terminal appearance.
*/
export const loadGhosttyTerminalStyle: Effect.Effect<
ServerTerminalStyle | undefined,
never,
FileSystem.FileSystem | Path.Path
> = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = NodeOS.homedir();
// Per the XDG spec an empty XDG_CONFIG_HOME must be treated as unset.
const xdgConfigHomeEnv = process.env["XDG_CONFIG_HOME"];
const xdgConfigHome =
xdgConfigHomeEnv !== undefined && xdgConfigHomeEnv.length > 0
? xdgConfigHomeEnv
: path.join(home, ".config");
const readFirstExisting = (candidates: ReadonlyArray<string>) =>
Effect.gen(function* () {
for (const candidate of candidates) {
const exists = yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (!exists) continue;
const content = yield* fs
.readFileString(candidate)
.pipe(Effect.orElseSucceed(() => undefined));
if (content !== undefined) return content;
}
return undefined;
});
// Ghostty reads the XDG config first and the macOS Application Support
// config after it, so later files override earlier values. It also accepts
// config.ghostty as the file name. Merge every location that exists instead
// of stopping at the first match.
const configDirs = [
path.join(xdgConfigHome, "ghostty"),
path.join(home, "Library", "Application Support", "com.mitchellh.ghostty"),
];
const configSources: Array<string> = [];
for (const dir of configDirs) {
// Read both file names when they coexist so neither shadows the other;
// Ghostty loads config.ghostty before config, so config wins conflicts.
for (const candidate of [path.join(dir, "config.ghostty"), path.join(dir, "config")]) {
const source = yield* readFirstExisting([candidate]);
if (source !== undefined) configSources.push(source);
}
}
if (configSources.length === 0) return undefined;
const config = parseGhosttyConfig(configSources.join("\n"));
const loadThemeColors = (themeName: string) =>
Effect.gen(function* () {
const themeSource = yield* readFirstExisting(
ghosttyThemeSearchPaths(path, { home, xdgConfigHome, themeName }),
);
if (themeSource === undefined) return emptyColors();
return parseGhosttyConfig(themeSource).colors;
});
const themeSelection = config.theme ? splitThemeSelection(config.theme) : {};
const resolveModeColors = (themeName: string | undefined) =>
Effect.gen(function* () {
const themeColors = themeName ? yield* loadThemeColors(themeName) : emptyColors();
// Explicit colors in the user config override the selected theme.
return toThemeColors(mergeColors(themeColors, config.colors));
});
const light = yield* resolveModeColors(themeSelection.light);
const dark = yield* resolveModeColors(themeSelection.dark);
const style: ServerTerminalStyle = {
...(config.fontFamily.length > 0 ? { fontFamily: config.fontFamily } : {}),
...(config.fontSize !== undefined ? { fontSize: config.fontSize } : {}),
...(light !== undefined ? { light } : {}),
...(dark !== undefined ? { dark } : {}),
};
const hasAnyValue =
style.fontFamily !== undefined ||
style.fontSize !== undefined ||
style.light !== undefined ||
style.dark !== undefined;
return hasAnyValue ? style : undefined;
}).pipe(Effect.orElseSucceed(() => undefined));
+3
View File
@@ -81,6 +81,7 @@ import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
import { loadGhosttyTerminalStyle } from "./terminal/ghosttyStyle.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -1065,6 +1066,7 @@ const makeWsRpcLayer = (
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
const terminalStyle = yield* loadGhosttyTerminalStyle;
const providers = yield* providerRegistry.getProviders;
const settings = ServerSettings.redactServerSettingsForClient(
yield* serverSettings.getSettings,
@@ -1081,6 +1083,7 @@ const makeWsRpcLayer = (
issues: keybindingsConfig.issues,
providers,
availableEditors: yield* externalLauncher.resolveAvailableEditors(),
...(terminalStyle !== undefined ? { terminalStyle } : {}),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
+1 -2
View File
@@ -31,10 +31,9 @@
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"ghostty-web": "0.4.0",
"jose": "catalog:",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
+2 -81
View File
@@ -6,9 +6,9 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import type { ChatMessage, Thread } from "../types";
import type { Thread } from "../types";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -20,10 +20,6 @@ import {
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
collectUserMessageBlobPreviewUrls,
normalizeDataUrlMimeType,
resolveComposerAttachmentMimeType,
revokeUserMessagePreviewUrls,
resolveSendEnvMode,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -81,81 +77,6 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};
function makeAttachmentMessage(): ChatMessage {
return {
id: MessageId.make("message-with-attachments"),
role: "user",
text: "Inspect these files",
turnId: null,
createdAt: now,
updatedAt: now,
streaming: false,
attachments: [
{
type: "image",
id: "image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 10,
previewUrl: "blob:image-preview",
},
{
type: "file",
id: "file-1",
name: "debug.log",
mimeType: "text/plain",
sizeBytes: 20,
previewUrl: "blob:file-preview",
},
],
};
}
describe("attachment preview lifecycle", () => {
it("collects and revokes blob previews for images and files", () => {
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
const message = makeAttachmentMessage();
expect(collectUserMessageBlobPreviewUrls(message)).toEqual([
"blob:image-preview",
"blob:file-preview",
]);
revokeUserMessagePreviewUrls(message);
expect(revokeObjectURL).toHaveBeenCalledTimes(2);
expect(revokeObjectURL).toHaveBeenNthCalledWith(1, "blob:image-preview");
expect(revokeObjectURL).toHaveBeenNthCalledWith(2, "blob:file-preview");
revokeObjectURL.mockRestore();
});
});
describe("composer attachment MIME types", () => {
it("recovers image MIME types from names when the browser reports a generic type", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.PNG", type: "" })).toBe("image/png");
expect(
resolveComposerAttachmentMimeType({
name: "capture.webp",
type: "application/octet-stream",
}),
).toBe("image/webp");
});
it("preserves a specific browser MIME type and keeps unknown files generic", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.png", type: "text/plain" })).toBe(
"text/plain",
);
expect(resolveComposerAttachmentMimeType({ name: "payload.bin", type: "" })).toBe(
"application/octet-stream",
);
});
it("rewrites a FileReader data URL with the resolved attachment MIME type", () => {
expect(
normalizeDataUrlMimeType("data:application/octet-stream;base64,iVBORw0KGgo=", "image/png"),
).toBe("data:image/png;base64,iVBORw0KGgo=");
});
});
describe("buildThreadTurnInterruptInput", () => {
it("targets the session's active running turn", () => {
const activeTurnId = TurnId.make("turn-running");
+12 -55
View File
@@ -10,7 +10,7 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
@@ -144,6 +144,9 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
@@ -154,78 +157,30 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
const FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
".avif": "image/avif",
".bmp": "image/bmp",
".gif": "image/gif",
".heic": "image/heic",
".heif": "image/heif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".tif": "image/tiff",
".tiff": "image/tiff",
".webp": "image/webp",
};
const GENERIC_BINARY_MIME_TYPES = new Set([
"",
"application/octet-stream",
"application/unknown",
"application/x-unknown",
"binary/octet-stream",
]);
export function resolveComposerAttachmentMimeType(file: {
readonly name: string;
readonly type: string;
}): string {
const declaredMimeType = file.type.trim().toLowerCase();
if (!GENERIC_BINARY_MIME_TYPES.has(declaredMimeType)) {
return declaredMimeType;
}
const normalizedName = file.name.trim().toLowerCase();
const extensionIndex = normalizedName.lastIndexOf(".");
const extension = extensionIndex >= 0 ? normalizedName.slice(extensionIndex) : "";
return (
FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION[extension] ||
declaredMimeType ||
"application/octet-stream"
);
}
export function normalizeDataUrlMimeType(dataUrl: string, mimeType: string): string {
const separatorIndex = dataUrl.indexOf(",");
if (!dataUrl.startsWith("data:") || separatorIndex < 0) {
return dataUrl;
}
return `data:${mimeType};base64,${dataUrl.slice(separatorIndex + 1)}`;
}
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
export function readFileAsDataUrl(file: File, mimeType?: string): Promise<string> {
export function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(mimeType ? normalizeDataUrlMimeType(reader.result, mimeType) : reader.result);
resolve(reader.result);
return;
}
reject(new Error("Could not read attachment data."));
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read attachment."));
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
@@ -238,7 +193,9 @@ export function resolveSendEnvMode(input: {
return input.isGitRepo ? input.requestedEnvMode : "local";
}
export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment {
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
+9 -9
View File
@@ -162,7 +162,7 @@ import {
} from "../logicalProject";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerAttachment,
type ComposerImageAttachment,
type DraftThreadEnvMode,
useComposerDraftStore,
type DraftId,
@@ -261,8 +261,8 @@ import {
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -1190,7 +1190,7 @@ function ChatViewContent(props: ChatViewProps) {
: null,
);
const promptRef = useRef("");
const composerImagesRef = useRef<ComposerAttachment[]>([]);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
@@ -4179,19 +4179,19 @@ function ChatViewContent(props: ChatViewProps) {
model: ctxSelectedModel,
models: ctxSelectedProviderModels,
effort: ctxSelectedPromptEffort,
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
});
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => ({
type: image.type,
type: "image" as const,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file, image.mimeType),
dataUrl: await readFileAsDataUrl(image.file),
})),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: image.type,
type: "image" as const,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -4253,7 +4253,7 @@ function ChatViewContent(props: ChatViewProps) {
let titleSeed = trimmed;
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
titleSeed = `Image: ${firstComposerImageName}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
File diff suppressed because it is too large. Load diff
+24 -49
View File
@@ -43,17 +43,13 @@ import {
replaceTextRange,
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import {
deriveComposerSendState,
readFileAsDataUrl,
resolveComposerAttachmentMimeType,
} from "../ChatView.logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerAttachment,
type ComposerImageAttachment,
type DraftId,
type PersistedComposerImageAttachment,
useComposerDraftStore,
@@ -105,7 +101,6 @@ import {
BotIcon,
CheckIcon,
CircleAlertIcon,
FileTextIcon,
ListTodoIcon,
PencilRulerIcon,
type LucideIcon,
@@ -135,7 +130,6 @@ import {
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { formatAttachmentSizeLabel } from "../../lib/attachmentSize";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -431,7 +425,7 @@ export interface ChatComposerHandle {
/** Get the current prompt/effort/model state for use in send. */
getSendContext: () => {
prompt: string;
images: ComposerAttachment[];
images: ComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
@@ -522,7 +516,7 @@ export interface ChatComposerProps {
// Refs the parent needs kept in sync
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerAttachment[]>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
@@ -1181,14 +1175,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const addComposerImage = useCallback(
(image: ComposerAttachment) => {
(image: ComposerImageAttachment) => {
addComposerDraftImage(composerDraftTarget, image);
},
[composerDraftTarget, addComposerDraftImage],
);
const addComposerImagesToDraft = useCallback(
(images: ComposerAttachment[]) => {
(images: ComposerImageAttachment[]) => {
addComposerDraftImages(composerDraftTarget, images);
},
[composerDraftTarget, addComposerDraftImages],
@@ -1396,9 +1390,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
await Promise.all(
composerImages.map(async (image) => {
try {
const dataUrl = await readFileAsDataUrl(image.file, image.mimeType);
const dataUrl = await readFileAsDataUrl(image.file);
stagedAttachmentById.set(image.id, {
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -1799,30 +1792,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (pendingUserInputs.length > 0) {
toastManager.add({
type: "error",
title: "Attach files after answering plan questions.",
title: "Attach images after answering plan questions.",
});
return;
}
const nextImages: ComposerAttachment[] = [];
const nextImages: ComposerImageAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
continue;
}
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
}
const mimeType = resolveComposerAttachmentMimeType(file);
const isImage = mimeType.startsWith("image/");
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: isImage ? "image" : "file",
type: "image",
id: randomUUID(),
name: file.name || (isImage ? "image" : "file"),
mimeType,
name: file.name || "image",
mimeType: file.type,
sizeBytes: file.size,
previewUrl,
file,
@@ -1847,8 +1842,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) return;
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
if (imageFiles.length === 0) return;
event.preventDefault();
addComposerImages(files);
addComposerImages(imageFiles);
};
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
@@ -2355,10 +2352,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
imageId,
);
const preview = buildExpandedImagePreview(composerImages, imageId);
if (preview) onExpandImage(preview);
}}
className="mb-3"
@@ -2409,34 +2403,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
.map((image) => (
<div
key={image.id}
className={
image.type === "file"
? "relative flex h-16 w-40 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background px-2"
: "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.type === "file" ? (
<>
<FileTextIcon className="size-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 pr-5">
<div className="truncate text-xs" title={image.name}>
{image.name}
</div>
<div className="text-[10px] text-muted-foreground/70">
{formatAttachmentSizeLabel(image.sizeBytes)}
</div>
</div>
</>
) : image.previewUrl ? (
{image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
image.id,
);
const preview = buildExpandedImagePreview(composerImages, image.id);
if (!preview) return;
onExpandImage(preview);
}}
@@ -2,13 +2,13 @@ import type { PreviewAnnotationPayload } from "@t3tools/contracts";
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
import type { ReactNode } from "react";
import type { ComposerAttachment } from "~/composerDraftStore";
import type { ComposerImageAttachment } from "~/composerDraftStore";
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
import { cn } from "~/lib/utils";
interface ComposerPreviewAnnotationCardsProps {
annotations: ReadonlyArray<PreviewAnnotationPayload>;
images: ReadonlyArray<ComposerAttachment>;
images: ReadonlyArray<ComposerImageAttachment>;
onRemove: (annotationId: string) => void;
onExpandImage: (imageId: string) => void;
className?: string;
@@ -381,88 +381,6 @@ describe("MessagesTimeline", () => {
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders file attachments as chips with name and size instead of images", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Please review the attached report."),
message: {
...buildUserTimelineEntry("Please review the attached report.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain("report.pdf");
expect(markup).toContain("2.0 KB");
expect(markup).toContain("lucide-file-text");
expect(markup).not.toContain("<img");
});
it("renders downloadable file attachment chips when a preview URL is available", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Here is the file."),
message: {
...buildUserTimelineEntry("Here is the file.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-2",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 512,
previewUrl: "data:text/plain;base64,aGVsbG8=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('download="notes.txt"');
expect(markup).toContain('href="data:text/plain;base64,aGVsbG8="');
expect(markup).toContain("512 B");
});
it("renders image attachments in the image grid without file chips", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Take a look."),
message: {
...buildUserTimelineEntry("Take a look.").message,
attachments: [
{
type: "image" as const,
id: "attachment-image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1,
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('src="data:image/png;base64,iVBORw0KGgo="');
expect(markup).toContain('alt="screenshot.png"');
expect(markup).not.toContain("lucide-file-text");
expect(markup).not.toContain("download=");
});
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -49,7 +49,6 @@ import {
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
FileTextIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -65,7 +64,6 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { formatAttachmentSizeLabel } from "~/lib/attachmentSize";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
@@ -883,10 +881,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
...elementContextState.contexts,
];
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter(
(image) => image.type === "image" && !image.name.startsWith("preview-annotation-"),
);
const fileAttachments = userImages.filter((attachment) => attachment.type === "file");
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
@@ -925,38 +920,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
{fileAttachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1.5">
{fileAttachments.map((attachment) => {
const chipContent = (
<>
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="max-w-48 truncate">{attachment.name}</span>
<span className="text-muted-foreground/70">
{formatAttachmentSizeLabel(attachment.sizeBytes)}
</span>
</>
);
const chipClassName =
"inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-background/70 px-2 py-1 text-[11px]";
return attachment.previewUrl ? (
<a
key={attachment.id}
href={attachment.previewUrl}
download={attachment.name}
className={`${chipClassName} hover:bg-background`}
aria-label={`Download ${attachment.name}`}
>
{chipContent}
</a>
) : (
<span key={attachment.id} className={chipClassName}>
{chipContent}
</span>
);
})}
</div>
)}
{previewAnnotations.map((annotation, index) => (
<UserMessagePreviewAnnotationCard
key={annotation.id}
-145
View File
@@ -65,7 +65,6 @@ import {
markPromotedDraftThreadByRef,
markPromotedDraftThreads,
markPromotedDraftThreadsByRef,
type ComposerFileAttachment,
type ComposerImageAttachment,
useComposerDraftStore,
DraftId,
@@ -105,33 +104,6 @@ function makeImage(input: {
};
}
function makeFile(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerFileAttachment {
const name = input.name ?? "report.pdf";
const mimeType = input.mimeType ?? "application/pdf";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "file",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
function makeTerminalContext(input: {
id: string;
text?: string;
@@ -373,123 +345,6 @@ describe("composerDraftStore syncPersistedAttachments", () => {
});
});
describe("composerDraftStore file attachments", () => {
const threadId = ThreadId.make("thread-file-attachments");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
beforeEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
resetComposerDraftStore();
});
afterEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
});
function mergePersistedDraft(attachment: Record<string, unknown>) {
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
) => ReturnType<typeof useComposerDraftStore.getState>;
};
};
return persistApi.getOptions().merge(
{
draftsByThreadId: {
[threadId]: {
prompt: "",
attachments: [attachment],
},
},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectKey: {},
},
useComposerDraftStore.getInitialState(),
);
}
it("hydrates persisted attachments without a type as images (legacy drafts)", () => {
const mergedState = mergePersistedDraft({
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: "data:image/png;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "image",
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
previewUrl: "data:image/png;base64,aGVsbG8=",
},
]);
});
it("hydrates persisted attachments with type file as file attachments", () => {
const mergedState = mergePersistedDraft({
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
dataUrl: "data:application/pdf;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
previewUrl: "data:application/pdf;base64,aGVsbG8=",
},
]);
});
it("persists the file type for staged file attachments (round trip)", () => {
const attachment = makeFile({
id: "file-round-trip",
previewUrl: "data:application/pdf;base64,aGVsbG8=",
});
useComposerDraftStore.getState().addImage(threadRef, attachment);
useComposerDraftStore.getState().syncPersistedAttachments(threadRef, [
{
type: "file",
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: attachment.previewUrl,
},
]);
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
};
};
const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey?: Record<string, { attachments?: Array<Record<string, unknown>> }>;
};
expect(
persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.attachments?.[0],
).toMatchObject({
type: "file",
id: "file-round-trip",
name: "report.pdf",
mimeType: "application/pdf",
});
});
});
describe("composerDraftStore terminal contexts", () => {
const threadId = ThreadId.make("thread-dedupe");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
+10 -26
View File
@@ -33,12 +33,7 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
import { useMemo } from "react";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatFileAttachment,
type ChatImageAttachment,
} from "./types";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
@@ -84,8 +79,6 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
}
export const PersistedComposerImageAttachment = Schema.Struct({
// Missing on drafts persisted before file attachments existed → "image".
type: Schema.optionalKey(Schema.Literals(["image", "file"])),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
@@ -99,13 +92,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment;
const PersistedTerminalContextDraft = Schema.Struct({
id: Schema.String,
threadId: ThreadId,
@@ -263,7 +249,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
*/
export interface ComposerThreadDraftState {
prompt: string;
images: ComposerAttachment[];
images: ComposerImageAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
@@ -448,8 +434,8 @@ interface ComposerDraftStoreState {
threadRef: ComposerThreadTarget,
interactionMode: ProviderInteractionMode | null | undefined,
) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerAttachment[]) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
insertTerminalContext: (
threadRef: ComposerThreadTarget,
@@ -565,7 +551,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
stickyActiveProvider: null,
});
const EMPTY_IMAGES: ComposerAttachment[] = [];
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
@@ -623,7 +609,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
};
}
function composerImageDedupKey(image: ComposerAttachment): string {
function composerImageDedupKey(image: ComposerImageAttachment): string {
// Keep this independent from File.lastModified so dedupe is stable for hydrated
// images reconstructed from localStorage (which get a fresh lastModified value).
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
@@ -1073,9 +1059,7 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
) {
return null;
}
const type = candidate.type;
return {
...(type === "image" || type === "file" ? { type } : {}),
id,
name,
mimeType,
@@ -2100,21 +2084,21 @@ function hydratePersistedComposerImageAttachment(
function hydrateImagesFromPersisted(
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
): ComposerAttachment[] {
): ComposerImageAttachment[] {
return attachments.flatMap((attachment) => {
const file = hydratePersistedComposerImageAttachment(attachment);
if (!file) return [];
return [
{
type: attachment.type ?? ("image" as const),
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: attachment.dataUrl,
file,
} satisfies ComposerAttachment,
} satisfies ComposerImageAttachment,
];
});
}
@@ -2872,7 +2856,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
existing.images.map((image) => composerImageDedupKey(image)),
);
const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
const dedupedIncoming: ComposerAttachment[] = [];
const dedupedIncoming: ComposerImageAttachment[] = [];
for (const image of images) {
const dedupKey = composerImageDedupKey(image);
if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
-37
View File
@@ -136,41 +136,4 @@ describe("buildBootstrapInput", () => {
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
it("captures mixed image and file attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-mixed"),
role: "user",
text: "Compare the screenshot with the report.",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
{
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
turnId: null,
updatedAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What differs?",
1_500,
);
expect(result.text).toContain("[Attached image: screenshot.png]");
expect(result.text).toContain("[Attached file: report.pdf]");
});
});
+5 -17
View File
@@ -18,30 +18,18 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummaryOfType(
message: ChatMessage,
type: "image" | "file",
label: string,
): string | null {
const typedAttachments = message.attachments?.filter((attachment) => attachment.type === type);
const count = typedAttachments?.length ?? 0;
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = typedAttachments?.slice(0, 3).map((attachment) => attachment.name) ?? [];
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached ${label}${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function attachmentSummary(message: ChatMessage): string | null {
const summaries = [
attachmentSummaryOfType(message, "image", "image"),
attachmentSummaryOfType(message, "file", "file"),
].filter((summary) => summary !== null);
return summaries.length > 0 ? summaries.join("\n") : null;
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function buildMessageBlock(message: ChatMessage): string {
-22
View File
@@ -1,22 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { formatAttachmentSizeLabel } from "./attachmentSize";
describe("formatAttachmentSizeLabel", () => {
it("formats sub-kilobyte sizes in bytes", () => {
expect(formatAttachmentSizeLabel(0)).toBe("0 B");
expect(formatAttachmentSizeLabel(512)).toBe("512 B");
expect(formatAttachmentSizeLabel(1_023)).toBe("1023 B");
});
it("formats kilobyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024)).toBe("1.0 KB");
expect(formatAttachmentSizeLabel(2_048)).toBe("2.0 KB");
expect(formatAttachmentSizeLabel(1_024 * 1_024 - 1)).toBe("1024.0 KB");
});
it("formats megabyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024 * 1_024)).toBe("1.0 MB");
expect(formatAttachmentSizeLabel(2_202_010)).toBe("2.1 MB");
});
});
-9
View File
@@ -1,9 +0,0 @@
export function formatAttachmentSizeLabel(sizeBytes: number): string {
if (sizeBytes >= 1024 * 1024) {
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
}
if (sizeBytes >= 1024) {
return `${(sizeBytes / 1024).toFixed(1)} KB`;
}
return `${sizeBytes} B`;
}
-1
View File
@@ -8,7 +8,6 @@ import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"
import "@fontsource-variable/dm-sans/index.css";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { isElectron } from "./env";
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vite-plus/test";
import { shouldFocusTerminalAfterSetup } from "./terminal-focus";
describe("shouldFocusTerminalAfterSetup", () => {
it("focuses the active terminal on its first setup", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: false,
restorePreviousTerminalFocus: false,
}),
).toBe(true);
});
it("does not steal focus when terminal style causes a remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: true,
restorePreviousTerminalFocus: false,
}),
).toBe(false);
});
it("restores focus when the terminal itself was focused before remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: false,
hasMounted: true,
restorePreviousTerminalFocus: true,
}),
).toBe(true);
});
});
+7
View File
@@ -0,0 +1,7 @@
export function shouldFocusTerminalAfterSetup(input: {
readonly autoFocus: boolean;
readonly hasMounted: boolean;
readonly restorePreviousTerminalFocus: boolean;
}): boolean {
return input.restorePreviousTerminalFocus || (!input.hasMounted && input.autoFocus);
}
+18
View File
@@ -37,6 +37,24 @@ describe("extractTerminalLinks", () => {
]);
});
it("finds non-http scheme urls", () => {
const line = "email mailto:[email protected] or clone ssh://[email protected]/t3/t3code.git now";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "mailto:[email protected]",
start: 6,
end: 28,
},
{
kind: "url",
text: "ssh://[email protected]/t3/t3code.git",
start: 38,
end: 72,
},
]);
});
it("trims trailing punctuation from links", () => {
const line = "(https://example.com/docs), ./src/main.ts:12.";
expect(extractTerminalLinks(line)).toEqual([
+4 -1
View File
@@ -36,7 +36,10 @@ export interface WrappedTerminalLinkLine {
segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
}
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
// Also matches the non-http schemes ghostty and other terminals linkify;
// authority-style schemes require // while opaque ones take a bare payload.
const URL_PATTERN =
/(?:https?|ftp|ssh|git|gemini|gopher):\/\/[^\s"'`<>]+|(?:mailto|tel|news|magnet):[^\s"'`<>:][^\s"'`<>]*/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
+1 -6
View File
@@ -1,5 +1,4 @@
import type {
ChatFileAttachment as ContractChatFileAttachment,
ChatImageAttachment as ContractChatImageAttachment,
OrchestrationCheckpointFile,
OrchestrationCheckpointSummary,
@@ -36,11 +35,7 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
readonly previewUrl?: string;
}
export interface ChatFileAttachment extends ContractChatFileAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment;
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
@@ -3,9 +3,6 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
ChatAttachment,
ChatFileAttachment,
ChatImageAttachment,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
ModelSelection,
@@ -746,80 +743,3 @@ it.effect("ModelSelection rejects malformed instance ids", () =>
assert.strictEqual(result._tag, "Failure");
}),
);
// ── ChatAttachment: image/file union ──────────────────────────────────
const decodeChatAttachment = Schema.decodeUnknownEffect(ChatAttachment);
const decodeChatAttachmentArray = Schema.decodeUnknownEffect(Schema.Array(ChatAttachment));
const decodeChatImageAttachment = Schema.decodeUnknownEffect(ChatImageAttachment);
const decodeChatFileAttachment = Schema.decodeUnknownEffect(ChatFileAttachment);
it.effect("ChatAttachment decodes a file attachment with a non-image mime type", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachment({
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
});
assert.strictEqual(parsed.type, "file");
assert.strictEqual(parsed.name, "report.pdf");
assert.strictEqual(parsed.mimeType, "application/pdf");
assert.strictEqual(parsed.sizeBytes, 2_048);
}),
);
it.effect("ChatAttachment arrays still decode legacy image-only attachments", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachmentArray([
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1_024,
},
{
type: "image",
id: "img-2",
name: "diagram.jpeg",
mimeType: "image/jpeg",
sizeBytes: 4_096,
},
]);
assert.strictEqual(parsed.length, 2);
assert.strictEqual(parsed[0]?.type, "image");
assert.strictEqual(parsed[1]?.type, "image");
}),
);
it.effect("ChatImageAttachment rejects non-image mime types", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatImageAttachment({
type: "image",
id: "img-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
it.effect("ChatFileAttachment rejects sizeBytes over the 10MB limit", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatFileAttachment({
type: "file",
id: "file-1",
name: "big.bin",
mimeType: "application/octet-stream",
sizeBytes: 10 * 1024 * 1024 + 1,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+2 -22
View File
@@ -173,29 +173,9 @@ const UploadChatImageAttachment = Schema.Struct({
});
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
export const ChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
id: ChatAttachmentId,
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
});
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
const UploadChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
dataUrl: TrimmedNonEmptyString.check(
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
),
});
export type UploadChatFileAttachment = typeof UploadChatFileAttachment.Type;
export const ChatAttachment = Schema.Union([ChatImageAttachment, ChatFileAttachment]);
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
export type ChatAttachment = typeof ChatAttachment.Type;
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment, UploadChatFileAttachment]);
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
export const ProjectScriptIcon = Schema.Literals([
+24
View File
@@ -406,6 +406,28 @@ export const ServerSignalProcessResult = Schema.Struct({
});
export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
/** Terminal colors parsed from the user's Ghostty theme (hex strings like "#1e1e2e"). */
export const ServerTerminalThemeColors = Schema.Struct({
background: Schema.optional(TrimmedNonEmptyString),
foreground: Schema.optional(TrimmedNonEmptyString),
cursor: Schema.optional(TrimmedNonEmptyString),
selectionBackground: Schema.optional(TrimmedNonEmptyString),
selectionForeground: Schema.optional(TrimmedNonEmptyString),
/** ANSI palette slots 0-15; empty string for slots the theme does not define. */
palette: Schema.optional(Schema.Array(Schema.String)),
});
export type ServerTerminalThemeColors = typeof ServerTerminalThemeColors.Type;
/** Terminal appearance derived from the user's local Ghostty config, when present. */
export const ServerTerminalStyle = Schema.Struct({
/** font-family fallback chain in config order. */
fontFamily: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
fontSize: Schema.optional(Schema.Number),
light: Schema.optional(ServerTerminalThemeColors),
dark: Schema.optional(ServerTerminalThemeColors),
});
export type ServerTerminalStyle = typeof ServerTerminalStyle.Type;
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
auth: ServerAuthDescriptor,
@@ -421,6 +443,8 @@ export const ServerConfig = Schema.Struct({
shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/** Whether thread subscriptions can emit an opt-in catch-up completion marker. */
threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/** Absent when no Ghostty config exists or it cannot be read. */
terminalStyle: Schema.optional(ServerTerminalStyle),
});
export type ServerConfig = typeof ServerConfig.Type;
+8 -74
View File
@@ -6,30 +6,12 @@ settings:
catalogs:
default:
'@effect/openapi-generator':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78
'@effect/tsgo':
specifier: 0.13.2
version: 0.13.2
'@noble/curves':
specifier: 1.9.1
version: 1.9.1
'@noble/hashes':
specifier: 1.8.0
version: 1.8.0
'@pierre/diffs':
specifier: 1.3.0-beta.5
version: 1.3.0-beta.5
'@typescript/native-preview':
specifier: 7.0.0-dev.20260604.1
version: 7.0.0-dev.20260604.1
jose:
specifier: 6.2.2
version: 6.2.2
typescript:
specifier: ~6.0.3
version: 6.0.3
vite-plus:
specifier: 0.2.2
version: 0.2.2
@@ -562,18 +544,15 @@ importers:
'@tanstack/react-router':
specifier: ^1.160.2
version: 1.170.10([email protected]([email protected]))([email protected])
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
effect:
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
ghostty-web:
specifier: 0.4.0
version: 0.4.0
jose:
specifier: 'catalog:'
version: 6.2.2
@@ -3300,56 +3279,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-p4Y/+RYk9Bk5WO+zHSUXAClRmZ2fbJCejMuCAsU2HhyME4jqf6Ftt/mJYEwIah1wGCBDYOB7wEGV1x5bCEZ6hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-By6tRALAZsno0F4zedmtG+wdMvJiJmJoXM4d3+A9zHE4HRXLqXITwRH8mgrlcXc5yJM2g2W3riRPwTYdgemZLQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-skYeG+RgvyzspqVEBsEprL90OYYZfoVNqB3HcCNR6QDJyXKOzfDRT3zncnHmUaFluIlBHuY23mU1b5WGgR98hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-FFgACrZOXAXUh5KQh2mt1CDOVOZmn+QzHP71wM9QobNwyQvoFfyAeefVUltW83g3sm7LTiH3yfFqLLVUpA5ZFQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-Nm/BAOfQeFiiKd502mZn/GAVKJwtd0RdCg17G3Wz/WSOIQmDi3+7/SZH4BHn1Ye5KvTVH3ua8WvfwLLycNIuvA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BiSy5Ku3mQqyxS6YIqAJgd403wEUWvI7kerfzPxc2l/txZVmZM0pSj7oDM+4bGBExowxOi7o73jEam1W0EDTZg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BCRkJiotz5s9afLYD2LuMvzAoDYx9H17E/YbDyu4xK7l4zHDPeny9ErSXL//i/nJyaOwRk08x4b8cgJC00+JDg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-4Oaxe1qrGgXfpCJ1C/ERJ2iCtV2rN1R79ga9fsfyVHfSQRu/hVW780u2KDqZWFZ/iGTHODJji0JemxqFZ63eIQ==}
@@ -3452,56 +3423,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-JGHS9Mnr7iWyyLDxgCv1MhzVpAckgptg00F2gnxt/GD7lQ2SW1BRcxHqhSTaSdDpjWRrBkBxMMh4+Hn3aVtExg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-AOYgBZqxNshrg83P9v0RYv+m8s10Cqkj4/PxXFDhcS3k7FqsIG5+CxErshZCIN7G8iy4Y+VGfAsuEdar8AcbBg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-QMybPS5ij3/vrKG67mqzHwW++91sYxK/PPUVi6SBtNCEzW4niS52fVBdXbQ6nou0wWbUPEpx8Sl/ZjtgE3clXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-gOc3W7JV0PXRpIL7stUlLe3Wa9Gp0Kdlup87IT3gHDvPKck2xNgMIl/Gs2lldYY2lyXZDC4rWi3hmoLUobkgbQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-rpGxph+FjjHcYI5q6uxB3Az+tnfmEnDbSA8+PK9ZE/VzyUAkvBOMeuY7ZQMhu5mpZH7YQDsTdW6Cx4kV/msc6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-WND+uhf/Ko13SLqQMWQUgsZuLvYYEvL0ZKgg0tgGYfLqxG7l8Ju123fHDMJyYSDl5E3bUbpFUuii/OvMreFQzw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-SrpbrUL70nG9vh6zP4/oKHWgLuHquwsr7MW9XOn0olBVgh10Uqr8qscKhQoBGEn6olK/IUpn5GSKcdQ5AjUhGA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-qkrsEn6NmgFKr7U/QnezQMb+q/vzAy0Dd9Y95gQGQTyjzDLN+HRZMuM5u70iyH4nBLCfKBzhjMsYCehKay2jyg==}
@@ -4037,7 +4000,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==}
@@ -4051,14 +4013,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==}
@@ -4072,14 +4032,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==}
@@ -4093,14 +4051,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==}
@@ -4114,14 +4070,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==}
@@ -4135,14 +4089,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==}
@@ -4156,7 +4108,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==}
@@ -4616,7 +4567,6 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
@@ -4630,7 +4580,6 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
@@ -4644,7 +4593,6 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
@@ -4658,7 +4606,6 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -5125,28 +5072,24 @@ packages:
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-YGtvTHT7qP4c5pZmM4kLL78/d8hj2NS150R92cR2SVOW/l9Ilq5R5WrEiMA4k5Ea3B++IJWZT5MRFI0tW9qlcg==}
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-FvaMI/vsy4PVM+Qd73K+KM8blfCAfaoZaGaGWNrrlMryhyPThXPnHoB1AQcrKbEAWb+z2fc4zLS4sH+8uI65fw==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-ZsMochHqXqxj2sGTJNJzz3vabppbe4BFgZAjJfsnVzkwR7jv6c5p1BM71LFWxP4qd5LL0TJT7lbeRhALlI44RQ==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-noBNyJufux0cf18eDpQLOQUZ1Kybfx9zlr+yQ6gAnxMEsQXSvYqZgWymfRDesBE3G/0XB5bg+AUtWijp3TwVcw==}
@@ -5194,12 +5137,6 @@ packages:
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
'@xterm/[email protected]':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
'@yuuang/[email protected]':
resolution: {integrity: sha512-eDYLT0kVBkp7e2BwdRDmt6N1rkeDPUHDefk3ZX0/nok+GLsqfy1WBoSL3Yg7HVXN1EyW8OBVc2uK8Zq8HbmaSA==}
engines: {node: '>= 12'}
@@ -7046,6 +6983,9 @@ packages:
resolution: {integrity: sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-0puDBik2qapbD/QQBW9o5ZHfXnZBqZWx/ctBiVtKZ6ZLds4NYb+wZuw1cRLXZk9zYovIQ908z3rvFhexAvc5Hg==}
[email protected]:
resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
@@ -7672,7 +7612,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-jmUQVx4331m6LIX+0wUhBbmMX7TCfjF5FoOH6SD1CttzuYlGNVpA7QnrmLxrsub43ClTINfGSYyHe2HWeLl5CQ==}
@@ -7693,7 +7632,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==}
@@ -7714,7 +7652,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==}
@@ -7735,7 +7672,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-mSL4rqPi4iXq5YVqzSsJgMVFENoa4nGTT/GjO2c0Yl9OuQfPsIfncvLrEW6RbbB24WtZ3xP/2CCmI3tNkNV4oA==}
@@ -15198,10 +15134,6 @@ snapshots:
'@xmldom/[email protected]': {}
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
'@yuuang/[email protected]':
optional: true
@@ -17523,6 +17455,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: