Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a30a50807 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
d48b42c017 | ||
|
|
fb45896588 | ||
|
|
b52518f85f | ||
|
|
3e99019af8 | ||
|
|
7d4b02689e | ||
|
|
9962f57ad0 | ||
|
|
8b538e2802 | ||
|
|
a6c57e169a | ||
|
|
6f92f0a668 | ||
|
|
35817601ff | ||
|
|
2b154db938 | ||
|
|
b9ff7aa5cd | ||
|
|
b5188e8cea | ||
|
|
992db16586 | ||
|
|
2aad749e24 | ||
|
|
aa267ebb05 | ||
|
|
1a33f25970 | ||
|
|
e8dfc42f44 | ||
|
|
21c823ecdc | ||
|
|
80498f1709 | ||
|
|
37e17e9207 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -41,31 +41,3 @@ Docs:
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
## Cursor Cloud specific instructions
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Bun >= 1.3.9** (package manager; see `packageManager` in root `package.json`).
|
||||
- **Node.js >= 24.13.1** (required for `node:sqlite`; see `engines` in root `package.json`).
|
||||
- **Codex CLI** on PATH is needed for full E2E agent sessions but is NOT required for dev server startup, lint, typecheck, or tests.
|
||||
|
||||
### Key commands
|
||||
|
||||
All commands are documented in the root `README.md`. Quick reference:
|
||||
|
||||
- `bun install` — install dependencies.
|
||||
- `bun run lint` — runs `oxlint` (not ESLint).
|
||||
- `bun run typecheck` — Turbo-orchestrated `tsc --noEmit` across all packages.
|
||||
- `bun run test` — Turbo-orchestrated Vitest across all packages.
|
||||
- `bun run dev` — starts contracts watch-build + server (port 3773) + Vite web (port 5733) via Turbo. Pass `T3CODE_NO_BROWSER=1` to suppress auto-opening a browser.
|
||||
- `bun run build` — production build of all packages.
|
||||
|
||||
### Gotchas
|
||||
|
||||
- The server uses `node:sqlite` (experimental in Node 24). You will see `ExperimentalWarning: SQLite is an experimental feature` in test/server output — this is expected.
|
||||
- Dev state is isolated to `~/.t3/dev` by default (set via `T3CODE_STATE_DIR`).
|
||||
- `bun run dev` spawns `turbo` under the hood via `scripts/dev-runner.mjs`; the runner resolves dev ports (server 3773, web 5733) and environment variables automatically.
|
||||
- `packages/contracts` must be built before `apps/server` or `apps/web` can start. Turbo handles this dependency, but if running individual packages manually, build contracts first: `bun run build:contracts`.
|
||||
- Lint uses `oxlint` (config: `.oxlintrc.json`), not ESLint. Formatting uses `oxfmt` (config: `.oxfmtrc.json`).
|
||||
- **Desktop dev mode** (`bun run dev:desktop`): The desktop Electron app requires `apps/server/dist/index.mjs` to exist (it spawns the server backend itself). Run `bun run build:desktop` first to build both server and desktop bundles, then `bun run dev:desktop`. The `tsdown --watch` (dev:bundle) may clean `dist-electron/` and not immediately rebuild; if `wait-on` hangs, manually run `bun run build` in `apps/desktop/` to unblock.
|
||||
@@ -215,14 +215,13 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
|
||||
@@ -393,7 +393,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
})),
|
||||
);
|
||||
|
||||
|
||||
@@ -297,7 +297,7 @@ function makeManager(input?: {
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -324,17 +324,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
expect(status.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-merged-pr",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-30T10:00:00Z",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 45,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-31T10:00:00Z",
|
||||
updatedAt: "2026-02-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -354,7 +440,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,6 +16,62 @@ interface OpenPrInfo {
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
@@ -79,12 +135,13 @@ function extractBranchFromRef(ref: string): string {
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
function toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
@@ -92,6 +149,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,10 +181,56 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
url: first.url,
|
||||
baseRefName: first.baseRefName,
|
||||
headRefName: first.headRefName,
|
||||
} satisfies OpenPrInfo;
|
||||
state: "open",
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const findLatestPr = (cwd: string, branch: string) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
return latestOpenPr;
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
@@ -258,10 +362,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||
const details = yield* gitCore.statusDetails(input.cwd);
|
||||
|
||||
const openPr =
|
||||
details.branch && details.hasUpstream
|
||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null;
|
||||
@@ -273,7 +377,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
pr,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -233,11 +233,12 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
@@ -437,7 +438,9 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
harness.provider.emit({
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,11 @@
|
||||
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
@@ -27,10 +33,16 @@ import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OrchestrationProjectionPipeline,
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
IMAGE_EXTENSION_BY_MIME_TYPE,
|
||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||
} from "../../projectFaviconRoute.ts";
|
||||
|
||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
@@ -48,9 +60,122 @@ type ProjectorName =
|
||||
|
||||
interface ProjectorDefinition {
|
||||
readonly name: ProjectorName;
|
||||
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly apply: (
|
||||
event: OrchestrationEvent,
|
||||
attachmentSideEffects: AttachmentSideEffects,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
interface PendingAttachmentWrite {
|
||||
readonly absolutePath: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
|
||||
interface AttachmentSideEffects {
|
||||
readonly writes: Array<PendingAttachmentWrite>;
|
||||
readonly deletedThreadIds: Set<string>;
|
||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||
}
|
||||
|
||||
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = encodeURIComponent(threadId);
|
||||
if (
|
||||
segment.length === 0 ||
|
||||
segment === "." ||
|
||||
segment === ".." ||
|
||||
segment.includes("/") ||
|
||||
segment.includes("\\") ||
|
||||
segment.includes("\0")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const mimeType = match[1]?.trim().toLowerCase();
|
||||
const base64 = match[2]?.replace(/\s+/g, "");
|
||||
if (!mimeType || !base64) return null;
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
function inferImageExtension(attachment: Extract<ChatAttachment, { type: "image" }>): string {
|
||||
const normalizedMimeType = attachment.mimeType.toLowerCase();
|
||||
if (normalizedMimeType.startsWith("image/")) {
|
||||
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[normalizedMimeType];
|
||||
if (fromMime) return fromMime;
|
||||
}
|
||||
const ext = Mime.getExtension(attachment.mimeType);
|
||||
if (ext && SAFE_IMAGE_FILE_EXTENSIONS.has(ext)) return ext;
|
||||
return ".bin";
|
||||
}
|
||||
|
||||
const materializeAttachmentsForProjection = Effect.fn(function* (input: {
|
||||
readonly threadId: string;
|
||||
readonly messageId: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
readonly stageFileWrite: (pendingWrite: PendingAttachmentWrite) => void;
|
||||
}) {
|
||||
if (input.attachments.length === 0) return [];
|
||||
|
||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(serverConfig)) return input.attachments;
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const attachmentsRootDir = path.join(serverConfig.value.stateDir, "attachments");
|
||||
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment materialization for unsafe thread id", {
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
});
|
||||
return input.attachments;
|
||||
}
|
||||
const messageSegment = encodeURIComponent(input.messageId);
|
||||
|
||||
return yield* Effect.forEach(
|
||||
input.attachments,
|
||||
(attachment, index) =>
|
||||
Effect.sync(() => {
|
||||
if (attachment.type !== "image" || !attachment.dataUrl.startsWith("data:")) {
|
||||
return attachment;
|
||||
}
|
||||
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed) {
|
||||
return attachment;
|
||||
}
|
||||
if (!parsed.mimeType.startsWith("image/")) {
|
||||
return attachment;
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0) return attachment;
|
||||
|
||||
const fileName = `${index}${inferImageExtension({
|
||||
...attachment,
|
||||
mimeType: parsed.mimeType,
|
||||
})}`;
|
||||
const uniqueFileName = `${messageSegment}-${fileName}`;
|
||||
const relativePath = `${threadSegment}/${uniqueFileName}`;
|
||||
const absolutePath = path.join(attachmentsRootDir, threadSegment, uniqueFileName);
|
||||
input.stageFileWrite({ absolutePath, bytes });
|
||||
|
||||
return {
|
||||
...attachment,
|
||||
dataUrl: `${ATTACHMENTS_ROUTE_PREFIX}/${relativePath}`,
|
||||
} satisfies ChatAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return null;
|
||||
@@ -163,6 +288,138 @@ function retainProjectionActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function toAttachmentRelativePath(dataUrl: string): string | null {
|
||||
const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
|
||||
if (!dataUrl.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const relativePath = dataUrl.slice(prefix.length).replace(/^[/\\]+/, "");
|
||||
if (relativePath.length === 0 || relativePath.startsWith("..")) {
|
||||
return null;
|
||||
}
|
||||
return relativePath.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
): Set<string> {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
return new Set();
|
||||
}
|
||||
const threadPrefix = `${threadSegment}/`;
|
||||
const relativePaths = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
||||
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
||||
continue;
|
||||
}
|
||||
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
continue;
|
||||
}
|
||||
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
||||
}
|
||||
}
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||
readonly sideEffects: AttachmentSideEffects;
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(serverConfig)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.deletedThreadIds,
|
||||
(threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.prunedThreadRelativePaths.entries(),
|
||||
([threadId, keptThreadRelativePaths]) => {
|
||||
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
const entries = yield* input.fileSystem
|
||||
.readDirectory(threadDir, { recursive: true })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
||||
const fileInfo = yield* input.fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
||||
yield* input.fileSystem.remove(absolutePath, { force: true });
|
||||
}
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
const writesByPath = new Map<string, Uint8Array>();
|
||||
for (const pendingWrite of input.sideEffects.writes) {
|
||||
// Last write wins for a path so updated attachment contents replace stale bytes.
|
||||
writesByPath.set(pendingWrite.absolutePath, pendingWrite.bytes);
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
writesByPath.entries(),
|
||||
([absolutePath, bytes]) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.fileSystem.makeDirectory(input.path.dirname(absolutePath), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* input.fileSystem.writeFile(absolutePath, bytes);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
@@ -175,7 +432,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
@@ -233,7 +493,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
@@ -272,6 +532,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -351,7 +612,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
@@ -367,12 +631,24 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
: existingMessage && event.payload.text.length === 0
|
||||
? existingMessage.text
|
||||
: event.payload.text;
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
attachments: event.payload.attachments,
|
||||
stageFileWrite: (pendingWrite) => {
|
||||
attachmentSideEffects.writes.push(pendingWrite);
|
||||
},
|
||||
}).pipe(Effect.provideService(Path.Path, path))
|
||||
: existingMessage?.attachments;
|
||||
yield* projectionThreadMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: nextText,
|
||||
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||
isStreaming: event.payload.streaming,
|
||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -406,6 +682,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||
event.payload.threadId,
|
||||
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -414,7 +694,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended":
|
||||
@@ -462,7 +745,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.type !== "thread.session-set") {
|
||||
return;
|
||||
@@ -481,7 +767,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested": {
|
||||
@@ -714,7 +1003,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended": {
|
||||
@@ -837,17 +1129,40 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
];
|
||||
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
sql.withTransaction(
|
||||
projector.apply(event).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
Effect.gen(function* () {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
writes: [],
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
};
|
||||
|
||||
yield* sql.withTransaction(
|
||||
projector.apply(event, attachmentSideEffects).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* runAttachmentSideEffects({
|
||||
sideEffects: attachmentSideEffects,
|
||||
fileSystem,
|
||||
path,
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
sequence: event.sequence,
|
||||
eventType: event.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
projectionStateRepository
|
||||
@@ -901,6 +1216,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline,
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
OrchestrationCheckpointFile,
|
||||
@@ -42,12 +43,13 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -171,6 +173,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -376,6 +379,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
|
||||
const layer = it.layer(
|
||||
ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
);
|
||||
|
||||
layer("ProjectionThreadMessageRepository", (it) => {
|
||||
it.effect("preserves existing attachments when upsert omits attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
|
||||
const createdAt = "2026-02-28T19:00:00.000Z";
|
||||
const updatedAt = "2026-02-28T19:00:01.000Z";
|
||||
const persistedAttachments = [
|
||||
{
|
||||
type: "image" as const,
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
||||
},
|
||||
];
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "user",
|
||||
text: "initial",
|
||||
attachments: persistedAttachments,
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "user",
|
||||
text: "updated",
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:00:02.000Z",
|
||||
});
|
||||
|
||||
const rows = yield* repository.listByThreadId({ threadId });
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]?.text, "updated");
|
||||
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-clear-attachments");
|
||||
const createdAt = "2026-02-28T19:10:00.000Z";
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "with attachment",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
||||
},
|
||||
],
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:10:01.000Z",
|
||||
});
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "cleared",
|
||||
attachments: [],
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:10:02.000Z",
|
||||
});
|
||||
|
||||
const rows = yield* repository.listByThreadId({ threadId });
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]?.text, "cleared");
|
||||
assert.deepEqual(rows[0]?.attachments, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -22,14 +24,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
|
||||
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
||||
Request: ProjectionThreadMessage,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
execute: (row) => {
|
||||
const nextAttachmentsJson =
|
||||
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||
return sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
@@ -40,6 +45,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
${row.turnId},
|
||||
${row.role},
|
||||
${row.text},
|
||||
COALESCE(
|
||||
${nextAttachmentsJson},
|
||||
(
|
||||
SELECT attachments_json
|
||||
FROM projection_thread_messages
|
||||
WHERE message_id = ${row.messageId}
|
||||
)
|
||||
),
|
||||
${row.isStreaming ? 1 : 0},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
@@ -50,10 +63,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
turn_id = excluded.turn_id,
|
||||
role = excluded.role,
|
||||
text = excluded.text,
|
||||
attachments_json = COALESCE(
|
||||
excluded.attachments_json,
|
||||
projection_thread_messages.attachments_json
|
||||
),
|
||||
is_streaming = excluded.is_streaming,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
`;
|
||||
},
|
||||
});
|
||||
|
||||
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
||||
@@ -67,6 +85,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -97,8 +116,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
...row,
|
||||
messageId: row.messageId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
isStreaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -18,6 +18,7 @@ import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
||||
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -36,6 +37,7 @@ const loader = Migrator.fromRecord({
|
||||
"4_ProviderSessionRuntime": Migration0004,
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_messages
|
||||
ADD COLUMN attachments_json TEXT
|
||||
`;
|
||||
});
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module ProjectionThreadMessageRepository
|
||||
*/
|
||||
import {
|
||||
ChatAttachment,
|
||||
OrchestrationMessageRole,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
@@ -24,6 +25,7 @@ export const ProjectionThreadMessage = Schema.Struct({
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
role: OrchestrationMessageRole,
|
||||
text: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||
isStreaming: Schema.Boolean,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -2,6 +2,32 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
"image/svg+xml": ".svg",
|
||||
"image/bmp": ".bmp",
|
||||
"image/tiff": ".tiff",
|
||||
"image/heic": ".heic",
|
||||
};
|
||||
|
||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".webp",
|
||||
".bmp",
|
||||
".tiff",
|
||||
".svg",
|
||||
".ico",
|
||||
]);
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
|
||||
@@ -378,6 +378,7 @@ it.effect(
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: startedSession.threadId,
|
||||
},
|
||||
],
|
||||
@@ -465,6 +466,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
@@ -475,6 +477,38 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
sessionId: initial.sessionId,
|
||||
input: "resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops all sessions and clears adapter runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
@@ -93,6 +93,18 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderSessionBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
|
||||
if (typeof rawCwd !== "string") return undefined;
|
||||
const trimmed = rawCwd.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const canonicalEventLogger =
|
||||
@@ -266,8 +278,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
return Layer.mergeAll(
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -223,5 +224,5 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)));
|
||||
}));
|
||||
});
|
||||
@@ -61,16 +61,16 @@ export function makeServerRuntimeServicesLayer() {
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
checkpointStoreLayer,
|
||||
CheckpointStoreLive,
|
||||
checkpointDiffQueryLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
|
||||
@@ -394,6 +394,21 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("ignores trailing writes after terminal exit", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitExit({ exitCode: 0, signal: 0 });
|
||||
|
||||
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
|
||||
expect(process.writes).toEqual([]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits subprocess activity events when child-process state changes", async () => {
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager } = makeManager(5, {
|
||||
|
||||
@@ -438,6 +438,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
const input = decodeTerminalWriteInput(raw);
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
if (!session.process || session.status !== "running") {
|
||||
if (session.status === "exited") {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||
);
|
||||
|
||||
@@ -4,7 +4,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -40,13 +40,14 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||
import { SqlClient } from "effect/unstable/sql";
|
||||
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -296,6 +297,36 @@ async function waitForPush(
|
||||
return take(maxMessages);
|
||||
}
|
||||
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
||||
for (const binding of bindings) {
|
||||
@@ -324,13 +355,17 @@ describe("WebSocket Server", () => {
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
|
||||
persistenceLayer?: Layer.Layer<
|
||||
SqlClient.SqlClient,
|
||||
SqlError.SqlError | MigrationError | PlatformError.PlatformError
|
||||
>;
|
||||
cwd?: string;
|
||||
autoBootstrapProjectFromCwd?: boolean;
|
||||
logWebSocketEvents?: boolean;
|
||||
devUrl?: string;
|
||||
authToken?: string;
|
||||
stateDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
@@ -354,7 +389,7 @@ describe("WebSocket Server", () => {
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
stateDir,
|
||||
staticDir: undefined,
|
||||
staticDir: options.staticDir,
|
||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||
noBrowser: true,
|
||||
authToken: options.authToken,
|
||||
@@ -438,6 +473,80 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("serves persisted attachments from stateDir", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-");
|
||||
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("image/png");
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
expect(bytes).toEqual(Buffer.from("hello-attachment"));
|
||||
});
|
||||
|
||||
it("serves persisted attachments for URL-encoded paths", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||
const attachmentPath = path.join(
|
||||
stateDir,
|
||||
"attachments",
|
||||
"thread%20folder",
|
||||
"message%20folder",
|
||||
"file%20name.png",
|
||||
);
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`,
|
||||
);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("image/png");
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
expect(bytes).toEqual(Buffer.from("hello-encoded-attachment"));
|
||||
});
|
||||
|
||||
it("serves static index for root path", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-root-");
|
||||
const staticDir = makeTempDir("t3code-static-root-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toContain("static-root");
|
||||
});
|
||||
|
||||
it("rejects static path traversal attempts", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-traversal-");
|
||||
const staticDir = makeTempDir("t3code-static-traversal-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await requestPath(port, "/..%2f..%2fetc/passwd");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toBe("Invalid static file path");
|
||||
});
|
||||
|
||||
it("bootstraps the cwd project on startup when enabled", async () => {
|
||||
server = await createTestServer({
|
||||
cwd: "/test/bootstrap-workspace",
|
||||
@@ -509,9 +618,9 @@ describe("WebSocket Server", () => {
|
||||
|
||||
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(
|
||||
path.join(stateDir, "state.sqlite"),
|
||||
).pipe(Layer.provide(NodeServices.layer)) as unknown as Layer.Layer<SqlClient.SqlClient, never>;
|
||||
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const cwd = "/test/bootstrap-existing";
|
||||
|
||||
server = await createTestServer({
|
||||
@@ -1412,7 +1521,7 @@ describe("WebSocket Server", () => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||
|
||||
+168
-74
@@ -6,11 +6,10 @@
|
||||
*
|
||||
* @module Server
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
CommandId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
@@ -25,7 +24,20 @@ import {
|
||||
WsResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
|
||||
import {
|
||||
Cause,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
Struct,
|
||||
} from "effect";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
@@ -42,22 +54,7 @@ import { clamp } from "effect/Number";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
".woff": "font/woff",
|
||||
".woff2": "font/woff2",
|
||||
".ttf": "font/ttf",
|
||||
".map": "application/json",
|
||||
};
|
||||
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -69,7 +66,7 @@ export interface ServerShape {
|
||||
readonly start: Effect.Effect<
|
||||
http.Server,
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>;
|
||||
|
||||
/**
|
||||
@@ -168,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
|
||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
http.Server,
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const {
|
||||
@@ -187,6 +184,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -233,62 +232,157 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
res.writeHead(302, { Location: devUrl.href });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
res.writeHead(503, { "Content-Type": "text/plain" });
|
||||
res.end("No static directory configured and no dev URL set.");
|
||||
return;
|
||||
}
|
||||
|
||||
let filePath = path.join(staticDir, url.pathname);
|
||||
|
||||
// SPA fallback: if no file extension and not found, serve index.html
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.join(filePath, "index.html");
|
||||
}
|
||||
|
||||
fs.stat(filePath, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
// SPA fallback
|
||||
const indexPath = path.join(staticDir, "index.html");
|
||||
fs.readFile(indexPath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(data);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const fileExt = path.extname(filePath);
|
||||
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
|
||||
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
void Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": contentType });
|
||||
res.end(data);
|
||||
});
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const attachmentsRoot = path.resolve(path.join(serverConfig.stateDir, "attachments"));
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
|
||||
if (
|
||||
normalizedRelativePath.length === 0 ||
|
||||
normalizedRelativePath.startsWith("..") ||
|
||||
normalizedRelativePath.includes("\0")
|
||||
) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
});
|
||||
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (!res.destroyed) {
|
||||
res.write(chunk);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.exit);
|
||||
if (streamExit._tag === "Failure") {
|
||||
if (!res.destroyed) {
|
||||
res.destroy();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
respond(302, { Location: devUrl.href });
|
||||
return;
|
||||
}
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
respond(
|
||||
503,
|
||||
{ "Content-Type": "text/plain" },
|
||||
"No static directory configured and no dev URL set.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const staticRoot = path.resolve(staticDir);
|
||||
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||
if (
|
||||
staticRelativePath.length === 0 ||
|
||||
hasRawLeadingParentSegment ||
|
||||
hasPathTraversalSegment ||
|
||||
staticRelativePath.includes("\0")
|
||||
) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const isWithinStaticRoot = (candidate: string) =>
|
||||
candidate === staticRoot ||
|
||||
candidate.startsWith(
|
||||
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
|
||||
);
|
||||
|
||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.resolve(filePath, "index.html");
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!indexData) {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": contentType }, data);
|
||||
}),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -22,12 +22,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
@@ -14,8 +18,16 @@ const AppSettingsSchema = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
|
||||
@@ -23,6 +35,76 @@ let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
): AppSettings["customCodexModels"] {
|
||||
const normalizedModels: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const candidate of models) {
|
||||
const normalized = normalizeModelSlug(candidate);
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||
seen.has(normalized)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(normalized);
|
||||
normalizedModels.push(normalized);
|
||||
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(slug);
|
||||
options.push({
|
||||
slug,
|
||||
name: slug,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
@@ -35,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
||||
}
|
||||
|
||||
try {
|
||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
@@ -96,10 +178,12 @@ export function useAppSettings() {
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -1,18 +1,207 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||
const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
return match?.[1] ?? "text";
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.map((child) => nodeToPlainText(child)).join("");
|
||||
}
|
||||
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||
return nodeToPlainText(node.props.children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractCodeBlock(
|
||||
children: ReactNode,
|
||||
): { className: string | undefined; code: string } | null {
|
||||
const childNodes = Children.toArray(children);
|
||||
if (childNodes.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
code: nodeToPlainText(onlyChild.props.children),
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(code)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [code]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd],
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,10 +7,13 @@ import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "luci
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -18,10 +21,62 @@ import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-diffs-header],
|
||||
[data-diff],
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
var(--background) 80%,
|
||||
var(--destructive)
|
||||
);
|
||||
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
[data-title] {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 120ms ease,
|
||||
text-decoration-color 120ms ease;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
[data-title]:hover {
|
||||
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
@@ -106,6 +161,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -226,6 +283,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const openDiffFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
@@ -425,7 +494,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
@@ -449,7 +518,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={patchViewportRef}
|
||||
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||
>
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
@@ -467,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto p-2 "
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -478,7 +550,21 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
return node.hasAttribute("data-title");
|
||||
});
|
||||
if (!clickedHeader) return;
|
||||
openDiffFileInEditor(filePath);
|
||||
}}
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
@@ -486,6 +572,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
lineDiffType: "none",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -493,7 +580,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
|
||||
@@ -2,12 +2,9 @@ import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
}
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -29,12 +29,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -45,12 +46,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -147,12 +149,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
aheadCount: 3,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -164,12 +167,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
aheadCount: 2,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -204,7 +208,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -246,14 +250,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -290,7 +294,7 @@ describe("when: branch is behind upstream", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR", () => {
|
||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -346,12 +350,13 @@ describe("when: working tree has local changes", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasWorkingTreeChanges: true,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -411,7 +416,7 @@ describe("when: on default branch without open PR", () => {
|
||||
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -511,7 +516,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -526,12 +531,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -548,12 +554,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -568,7 +575,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
|
||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
|
||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
|
||||
@@ -58,7 +58,7 @@ function getMenuActionDisabledReason(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
|
||||
@@ -219,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
return;
|
||||
}
|
||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
||||
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -236,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
@@ -295,7 +295,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
||||
const existingOpenPrUrl =
|
||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||
@@ -365,7 +367,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.openPr?.url,
|
||||
gitStatusForActions?.pr,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
@@ -16,7 +17,7 @@ import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { toastManager } from "./ui/toast";
|
||||
@@ -63,6 +64,13 @@ interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
}
|
||||
|
||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
@@ -125,6 +133,28 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
||||
if (prState === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
};
|
||||
}
|
||||
if (prState === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
};
|
||||
}
|
||||
if (prState === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
@@ -210,6 +240,58 @@ export default function Sidebar() {
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
state.threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
queries: threadGitStatusCwds.map((cwd) => ({
|
||||
...gitStatusQueryOptions(cwd),
|
||||
staleTime: 30_000,
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prStateByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
if (!cwd) continue;
|
||||
const status = threadGitStatusQueries[index]?.data;
|
||||
if (status) {
|
||||
statusByCwd.set(cwd, status);
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPrState>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
@@ -632,6 +714,7 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
|
||||
return (
|
||||
@@ -677,6 +760,16 @@ export default function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{prStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={prStatus.label}
|
||||
title={prStatus.label}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
|
||||
@@ -112,6 +112,7 @@ interface TerminalViewportProps {
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
onSessionExited: () => void;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -123,6 +124,7 @@ function TerminalViewport({
|
||||
terminalId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -131,6 +133,12 @@ function TerminalViewport({
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const onSessionExitedRef = useRef(onSessionExited);
|
||||
const hasHandledExitRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
onSessionExitedRef.current = onSessionExited;
|
||||
}, [onSessionExited]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
@@ -306,6 +314,7 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
hasHandledExitRef.current = false;
|
||||
activeTerminal.write("\u001bc");
|
||||
if (event.snapshot.history.length > 0) {
|
||||
activeTerminal.write(event.snapshot.history);
|
||||
@@ -335,6 +344,16 @@ function TerminalViewport({
|
||||
activeTerminal,
|
||||
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
||||
);
|
||||
if (hasHandledExitRef.current) {
|
||||
return;
|
||||
}
|
||||
hasHandledExitRef.current = true;
|
||||
window.setTimeout(() => {
|
||||
if (!hasHandledExitRef.current) {
|
||||
return;
|
||||
}
|
||||
onSessionExitedRef.current();
|
||||
}, 0);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -783,6 +802,7 @@ export default function ThreadTerminalDrawer({
|
||||
terminalId={terminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -800,6 +820,7 @@ export default function ThreadTerminalDrawer({
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
|
||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
}
|
||||
|
||||
.diff-render-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.5rem;
|
||||
overflow: clip;
|
||||
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
} as const;
|
||||
|
||||
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||
|
||||
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||
}
|
||||
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
export function fnv1a32(
|
||||
input: string,
|
||||
seed = FNV_OFFSET_BASIS_32,
|
||||
multiplier = FNV_PRIME_32,
|
||||
): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LRUCache } from "./lruCache";
|
||||
|
||||
describe("LRUCache", () => {
|
||||
it("returns null for missing keys", () => {
|
||||
const cache = new LRUCache<string>(2, 100);
|
||||
expect(cache.get("missing")).toBeNull();
|
||||
});
|
||||
|
||||
it("evicts oldest by max entries", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("promotes on get and evicts least recently used", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
|
||||
cache.set("c", "C", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("b")).toBeNull();
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("evicts by memory budget", () => {
|
||||
const cache = new LRUCache<string>(10, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface CacheEntry<T> {
|
||||
value: T;
|
||||
approximateSize: number;
|
||||
}
|
||||
|
||||
export class LRUCache<T> {
|
||||
private cache = new Map<string, CacheEntry<T>>();
|
||||
private totalSize = 0;
|
||||
|
||||
constructor(
|
||||
private readonly maxEntries: number,
|
||||
private readonly maxMemoryBytes: number,
|
||||
) {}
|
||||
|
||||
get(key: string): T | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.promote(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T, approximateSize: number): void {
|
||||
const existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
this.totalSize -= existing.approximateSize;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
|
||||
private promote(key: string, entry: CacheEntry<T>): void {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
private evictIfNeeded(incomingSize: number): void {
|
||||
while (
|
||||
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const oldestEntry = this.cache.get(oldestKey);
|
||||
if (oldestEntry) {
|
||||
this.totalSize -= oldestEntry.approximateSize;
|
||||
}
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -52,9 +53,12 @@ function SettingsRouteView() {
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [customModelInput, setCustomModelInput] = useState("");
|
||||
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const customCodexModels = settings.customCodexModels;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
@@ -74,6 +78,42 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [keybindingsConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(() => {
|
||||
const normalized = normalizeModelSlug(customModelInput);
|
||||
if (!normalized) {
|
||||
setCustomModelError("Enter a model slug.");
|
||||
return;
|
||||
}
|
||||
if (MODEL_OPTIONS.some((option) => option.slug === normalized)) {
|
||||
setCustomModelError("That model is already built in.");
|
||||
return;
|
||||
}
|
||||
if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
|
||||
setCustomModelError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
|
||||
return;
|
||||
}
|
||||
if (customCodexModels.includes(normalized)) {
|
||||
setCustomModelError("That custom model is already saved.");
|
||||
return;
|
||||
}
|
||||
|
||||
updateSettings({
|
||||
customCodexModels: [...customCodexModels, normalized],
|
||||
});
|
||||
setCustomModelInput("");
|
||||
setCustomModelError(null);
|
||||
}, [customCodexModels, customModelInput, updateSettings]);
|
||||
|
||||
const removeCustomModel = useCallback(
|
||||
(slug: string) => {
|
||||
updateSettings({
|
||||
customCodexModels: customCodexModels.filter((model) => model !== slug),
|
||||
});
|
||||
setCustomModelError(null);
|
||||
},
|
||||
[customCodexModels, updateSettings],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
@@ -193,6 +233,96 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Models</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Save additional Codex model slugs so they appear in the chat model picker.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
if (customModelError) {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Example: <code>gpt-6.7-codex-ultra-preview</code>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<p>Saved custom models: {customCodexModels.length}</p>
|
||||
{customCodexModels.length > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
customCodexModels: defaults.customCodexModels,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reset custom models
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{customCodexModels.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{customCodexModels.map((slug) => (
|
||||
<div
|
||||
key={slug}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
|
||||
>
|
||||
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
|
||||
{slug}
|
||||
</code>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => removeCustomModel(slug)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border bg-background px-3 py-4 text-xs text-muted-foreground">
|
||||
No custom models saved yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||
|
||||
+38
-1
@@ -192,6 +192,43 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
||||
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:"
|
||||
? "https:"
|
||||
: wsUrl.protocol === "ws:"
|
||||
? "http:"
|
||||
: wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
if (rawUrl.startsWith("/")) {
|
||||
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||
}
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -456,7 +493,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
|
||||
@@ -71,12 +71,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
},
|
||||
@@ -863,20 +861,14 @@
|
||||
|
||||
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
|
||||
"hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
|
||||
|
||||
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
|
||||
|
||||
"highlight.js": ["[email protected]", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
|
||||
|
||||
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
@@ -983,8 +975,6 @@
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
|
||||
"lowlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="],
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
@@ -1197,8 +1187,6 @@
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
|
||||
"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
|
||||
@@ -1361,8 +1349,6 @@
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
"unist-util-find-after": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="],
|
||||
|
||||
"unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
|
||||
|
||||
"unist-util-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
|
||||
|
||||
@@ -18,6 +18,8 @@ export const GitPrStepStatus = Schema.Literals([
|
||||
"opened_existing",
|
||||
"skipped_not_requested",
|
||||
]);
|
||||
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||
export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
@@ -91,6 +93,16 @@ export type GitInitInput = typeof GitInitInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
export const GitStatusPr = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
state: GitStatusPrState,
|
||||
});
|
||||
export type GitStatusPr = typeof GitStatusPr.Type;
|
||||
|
||||
export const GitStatusResult = Schema.Struct({
|
||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
hasWorkingTreeChanges: Schema.Boolean,
|
||||
@@ -108,15 +120,7 @@ export const GitStatusResult = Schema.Struct({
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
openPr: Schema.NullOr(
|
||||
Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
pr: Schema.NullOr(GitStatusPr),
|
||||
});
|
||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||
|
||||
|
||||
@@ -22,9 +22,14 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default for missing and unknown models", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe("gpt-4.1");
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
|
||||
@@ -5,11 +5,12 @@ export const MODEL_OPTIONS = [
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
] as const;
|
||||
|
||||
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type BuiltInModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type ModelSlug = string;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
@@ -26,16 +27,12 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
||||
return normalized ?? DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
|
||||
Reference in new issue
Block a user