Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
150e171a88 | ||
|
|
39f07869d9 | ||
|
|
afc0c78f0b | ||
|
|
dadda0d490 | ||
|
|
fb9274117c | ||
|
|
88dc6c94aa | ||
|
|
585031572f | ||
|
|
cd732a2b2e | ||
|
|
875e6edcf2 | ||
|
|
e1a8ee189a | ||
|
|
e64ad4b2c7 | ||
|
|
0e146e22fb | ||
|
|
700579bb3f | ||
|
|
ad79b5a4a3 | ||
|
|
4bc43a0e2b | ||
|
|
44e409f9c6 | ||
|
|
d3d0a08237 | ||
|
|
9b0fe5efd0 | ||
|
|
0df68cc73e | ||
|
|
61e1babcc7 | ||
|
|
06912c3222 | ||
|
|
8416ecdb53 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
e8dfc42f44 | ||
|
|
37e17e9207 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -1,264 +0,0 @@
|
|||||||
name: Release
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
bump:
|
|
||||||
description: "Semantic version bump to apply before release"
|
|
||||||
required: true
|
|
||||||
default: patch
|
|
||||||
type: choice
|
|
||||||
options:
|
|
||||||
- patch
|
|
||||||
- minor
|
|
||||||
- major
|
|
||||||
release_name:
|
|
||||||
description: "Display name for the GitHub release"
|
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
draft:
|
|
||||||
description: "Create release as draft"
|
|
||||||
required: true
|
|
||||||
default: true
|
|
||||||
type: boolean
|
|
||||||
prerelease:
|
|
||||||
description: "Mark release as pre-release"
|
|
||||||
required: true
|
|
||||||
default: true
|
|
||||||
type: boolean
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: release-${{ github.ref_name }}
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
prepare-release:
|
|
||||||
name: Bump versions, commit, and tag
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
tag: ${{ steps.bump-version.outputs.tag }}
|
|
||||||
version: ${{ steps.bump-version.outputs.version }}
|
|
||||||
steps:
|
|
||||||
- name: Ensure workflow runs from a branch
|
|
||||||
run: |
|
|
||||||
if [ "${GITHUB_REF_TYPE}" != "branch" ]; then
|
|
||||||
echo "workflow_dispatch must be run from a branch ref, got: ${GITHUB_REF_TYPE}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
ref: ${{ github.ref_name }}
|
|
||||||
|
|
||||||
- name: Setup Node
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: package.json
|
|
||||||
|
|
||||||
- name: Bump app versions and infer release tag
|
|
||||||
id: bump-version
|
|
||||||
run: |
|
|
||||||
node --input-type=module <<'EOF'
|
|
||||||
import fs from "node:fs";
|
|
||||||
|
|
||||||
const bump = process.env.RELEASE_BUMP;
|
|
||||||
const files = [
|
|
||||||
"apps/server/package.json",
|
|
||||||
"apps/desktop/package.json",
|
|
||||||
"apps/web/package.json",
|
|
||||||
];
|
|
||||||
const sourceVersionFile = "apps/server/package.json";
|
|
||||||
|
|
||||||
const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
||||||
const versions = files.map((file) => {
|
|
||||||
const json = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
||||||
return { file, version: json.version };
|
|
||||||
});
|
|
||||||
|
|
||||||
const source = versions.find((entry) => entry.file === sourceVersionFile);
|
|
||||||
if (!source) {
|
|
||||||
throw new Error(`Could not find source version file '${sourceVersionFile}'.`);
|
|
||||||
}
|
|
||||||
const outOfSync = versions.filter((entry) => entry.version !== source.version);
|
|
||||||
if (outOfSync.length > 0) {
|
|
||||||
const details = outOfSync.map((entry) => `${entry.file}=${entry.version}`).join(", ");
|
|
||||||
console.warn(
|
|
||||||
`Detected out-of-sync app versions. Using ${sourceVersionFile}=${source.version} as source of truth. Others: ${details}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentVersion = source.version;
|
|
||||||
const match = semverRegex.exec(currentVersion);
|
|
||||||
if (!match) {
|
|
||||||
throw new Error(
|
|
||||||
`Version '${currentVersion}' is not a supported plain semver (x.y.z).`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let major = Number.parseInt(match[1], 10);
|
|
||||||
let minor = Number.parseInt(match[2], 10);
|
|
||||||
let patch = Number.parseInt(match[3], 10);
|
|
||||||
|
|
||||||
if (bump === "patch") {
|
|
||||||
patch += 1;
|
|
||||||
} else if (bump === "minor") {
|
|
||||||
minor += 1;
|
|
||||||
patch = 0;
|
|
||||||
} else if (bump === "major") {
|
|
||||||
major += 1;
|
|
||||||
minor = 0;
|
|
||||||
patch = 0;
|
|
||||||
} else {
|
|
||||||
throw new Error(`Unsupported bump type '${bump}'.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const version = `${major}.${minor}.${patch}`;
|
|
||||||
const tag = `v${version}`;
|
|
||||||
|
|
||||||
for (const file of files) {
|
|
||||||
const json = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
||||||
json.version = version;
|
|
||||||
fs.writeFileSync(file, `${JSON.stringify(json, null, 2)}\n`, "utf8");
|
|
||||||
}
|
|
||||||
|
|
||||||
const outputPath = process.env.GITHUB_OUTPUT;
|
|
||||||
fs.appendFileSync(outputPath, `version=${version}\n`);
|
|
||||||
fs.appendFileSync(outputPath, `tag=${tag}\n`);
|
|
||||||
|
|
||||||
console.log(`Bumped version ${currentVersion} -> ${version}`);
|
|
||||||
console.log(`Inferred release tag: ${tag}`);
|
|
||||||
EOF
|
|
||||||
env:
|
|
||||||
RELEASE_BUMP: ${{ inputs.bump }}
|
|
||||||
|
|
||||||
- name: Validate inferred tag does not already exist
|
|
||||||
run: |
|
|
||||||
tag="${{ steps.bump-version.outputs.tag }}"
|
|
||||||
if git rev-parse --verify --quiet "refs/tags/${tag}"; then
|
|
||||||
echo "Tag ${tag} already exists locally."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
if git ls-remote --tags origin "${tag}" | grep -q .; then
|
|
||||||
echo "Tag ${tag} already exists on origin."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Commit version bump
|
|
||||||
run: |
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
|
||||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json
|
|
||||||
if git diff --cached --quiet; then
|
|
||||||
echo "No version change detected; refusing to create empty release commit."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
git commit -m "chore(release): bump app versions to ${{ steps.bump-version.outputs.version }}
|
|
||||||
|
|
||||||
Co-authored-by: codex <[email protected]>"
|
|
||||||
|
|
||||||
- name: Create and push release tag
|
|
||||||
run: |
|
|
||||||
git tag -a "${{ steps.bump-version.outputs.tag }}" -m "Release ${{ steps.bump-version.outputs.tag }}"
|
|
||||||
git push origin "${{ github.ref_name }}"
|
|
||||||
git push origin "refs/tags/${{ steps.bump-version.outputs.tag }}"
|
|
||||||
|
|
||||||
build-macos:
|
|
||||||
name: Build and package macOS (${{ matrix.arch }})
|
|
||||||
runs-on: macos-14
|
|
||||||
needs: prepare-release
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
arch:
|
|
||||||
- arm64
|
|
||||||
- x64
|
|
||||||
env:
|
|
||||||
CI: "true"
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ needs.prepare-release.outputs.tag }}
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: oven-sh/setup-bun@v2
|
|
||||||
with:
|
|
||||||
bun-version-file: package.json
|
|
||||||
|
|
||||||
- name: Setup Node
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: package.json
|
|
||||||
|
|
||||||
- name: Cache Bun and Turbo
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/.bun/install/cache
|
|
||||||
.turbo
|
|
||||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Build and package macOS artifact
|
|
||||||
run: |
|
|
||||||
bun run dist:desktop:dmg -- --arch "${{ matrix.arch }}" --version "${{ needs.prepare-release.outputs.version }}"
|
|
||||||
ls -lah release
|
|
||||||
# TODO: Add production macOS signing and notarization in CI:
|
|
||||||
# - Import Developer ID Application certificate + private key into keychain.
|
|
||||||
# - Provide APPLE_ID / APPLE_TEAM_ID / APPLE_APP_SPECIFIC_PASSWORD secrets.
|
|
||||||
# - Build with signing enabled and notarize + staple before release upload.
|
|
||||||
|
|
||||||
- name: Generate SHA256 checksums
|
|
||||||
run: |
|
|
||||||
checksum_file="release/SHA256SUMS-${{ matrix.arch }}.txt"
|
|
||||||
find release -maxdepth 1 -type f ! -name "SHA256SUMS-*.txt" -print0 \
|
|
||||||
| xargs -0 shasum -a 256 > "$checksum_file"
|
|
||||||
cat "$checksum_file"
|
|
||||||
|
|
||||||
- name: Upload packaged artifacts to workflow run
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: release-assets-${{ needs.prepare-release.outputs.tag }}-${{ matrix.arch }}
|
|
||||||
path: release/*
|
|
||||||
if-no-files-found: error
|
|
||||||
|
|
||||||
publish-release:
|
|
||||||
name: Create GitHub release
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- prepare-release
|
|
||||||
- build-macos
|
|
||||||
steps:
|
|
||||||
- name: Download packaged artifacts
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
pattern: release-assets-${{ needs.prepare-release.outputs.tag }}-*
|
|
||||||
merge-multiple: true
|
|
||||||
path: release-assets
|
|
||||||
|
|
||||||
- name: Create GitHub release and upload assets
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
tag_name: ${{ needs.prepare-release.outputs.tag }}
|
|
||||||
target_commitish: ${{ needs.prepare-release.outputs.tag }}
|
|
||||||
name: ${{ inputs.release_name != '' && inputs.release_name || needs.prepare-release.outputs.tag }}
|
|
||||||
draft: ${{ inputs.draft }}
|
|
||||||
prerelease: ${{ inputs.prerelease }}
|
|
||||||
generate_release_notes: true
|
|
||||||
files: release-assets/*
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
# TODO: Add a multi-platform release matrix and publish Linux/Windows installers:
|
|
||||||
# - Linux: build/sign AppImage/deb/rpm artifacts on ubuntu runners.
|
|
||||||
# - Windows: build/sign MSI/NSIS artifacts on windows runners.
|
|
||||||
# - Consider per-platform updater metadata/signature publishing strategy.
|
|
||||||
@@ -23,6 +23,8 @@ import {
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||||
|
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||||
@@ -54,6 +56,7 @@ import {
|
|||||||
makeTestProviderAdapterHarness,
|
makeTestProviderAdapterHarness,
|
||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
|
import { ServerConfig } from "../src/config.ts";
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -227,8 +230,17 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
);
|
);
|
||||||
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
|
} as unknown as GitCoreShape);
|
||||||
|
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||||
|
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||||
|
} as unknown as TextGenerationShape);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(gitCoreLayer),
|
||||||
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
@@ -240,6 +252,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
const layer = orchestrationReactorLayer.pipe(
|
const layer = orchestrationReactorLayer.pipe(
|
||||||
Layer.provide(persistenceLayer),
|
Layer.provide(persistenceLayer),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||||
|
|
||||||
|
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||||
|
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||||
|
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return normalized.replace(/\\/g, "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentRelativePath(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly relativePath: string;
|
||||||
|
}): string | null {
|
||||||
|
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||||
|
if (!normalizedRelativePath) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||||
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createAttachmentId,
|
||||||
|
parseThreadSegmentFromAttachmentId,
|
||||||
|
resolveAttachmentPathById,
|
||||||
|
} from "./attachmentStore.ts";
|
||||||
|
|
||||||
|
describe("attachmentStore", () => {
|
||||||
|
it("sanitizes thread ids when creating attachment ids", () => {
|
||||||
|
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||||
|
expect(attachmentId).toBeTruthy();
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
expect(threadSegment).toBeTruthy();
|
||||||
|
expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
|
||||||
|
expect(threadSegment).not.toContain(".");
|
||||||
|
expect(threadSegment).not.toContain("%");
|
||||||
|
expect(threadSegment).not.toContain("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses exact thread segments from attachment ids without prefix collisions", () => {
|
||||||
|
const fooId = "foo-00000000-0000-4000-8000-000000000001";
|
||||||
|
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
|
||||||
|
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes created thread segments to lowercase", () => {
|
||||||
|
const attachmentId = createAttachmentId("Thread.Foo");
|
||||||
|
expect(attachmentId).toBeTruthy();
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||||
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
|
try {
|
||||||
|
const attachmentId = "thread-1-attachment";
|
||||||
|
const attachmentsDir = path.join(stateDir, "attachments");
|
||||||
|
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||||
|
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
|
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const resolved = resolveAttachmentPathById({
|
||||||
|
stateDir,
|
||||||
|
attachmentId,
|
||||||
|
});
|
||||||
|
expect(resolved).toBe(pngPath);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when no attachment file exists for the id", () => {
|
||||||
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
|
try {
|
||||||
|
const resolved = resolveAttachmentPathById({
|
||||||
|
stateDir,
|
||||||
|
attachmentId: "thread-1-missing",
|
||||||
|
});
|
||||||
|
expect(resolved).toBeNull();
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
|
||||||
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import {
|
||||||
|
normalizeAttachmentRelativePath,
|
||||||
|
resolveAttachmentRelativePath,
|
||||||
|
} from "./attachmentPaths.ts";
|
||||||
|
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||||
|
|
||||||
|
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||||
|
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||||
|
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||||
|
const ATTACHMENT_ID_UUID_PATTERN =
|
||||||
|
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||||
|
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||||
|
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||||
|
"i",
|
||||||
|
);
|
||||||
|
|
||||||
|
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||||
|
const segment = threadId
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9_-]+/gi, "-")
|
||||||
|
.replace(/-+/g, "-")
|
||||||
|
.replace(/^[-_]+|[-_]+$/g, "")
|
||||||
|
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
|
||||||
|
.replace(/[-_]+$/g, "");
|
||||||
|
if (segment.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return segment;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAttachmentId(threadId: string): string | null {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return `${threadSegment}-${randomUUID()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||||
|
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||||
|
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
|
||||||
|
if (!match) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return match[1]?.toLowerCase() ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||||
|
switch (attachment.type) {
|
||||||
|
case "image": {
|
||||||
|
const extension = inferImageExtension({
|
||||||
|
mimeType: attachment.mimeType,
|
||||||
|
fileName: attachment.name,
|
||||||
|
});
|
||||||
|
return `${attachment.id}${extension}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentPath(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly attachment: ChatAttachment;
|
||||||
|
}): string | null {
|
||||||
|
return resolveAttachmentRelativePath({
|
||||||
|
stateDir: input.stateDir,
|
||||||
|
relativePath: attachmentRelativePath(input.attachment),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentPathById(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly attachmentId: string;
|
||||||
|
}): string | null {
|
||||||
|
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||||
|
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||||
|
const maybePath = resolveAttachmentRelativePath({
|
||||||
|
stateDir: input.stateDir,
|
||||||
|
relativePath: `${normalizedId}${extension}`,
|
||||||
|
});
|
||||||
|
if (maybePath && existsSync(maybePath)) {
|
||||||
|
return maybePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
|
||||||
|
const normalized = normalizeAttachmentRelativePath(relativePath);
|
||||||
|
if (!normalized || normalized.includes("/")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const extensionIndex = normalized.lastIndexOf(".");
|
||||||
|
if (extensionIndex <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const id = normalized.slice(0, extensionIndex);
|
||||||
|
return id.length > 0 && !id.includes(".") ? id : null;
|
||||||
|
}
|
||||||
@@ -191,10 +191,7 @@ describe("sendTurn", () => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
name: "error.png",
|
url: "data:image/png;base64,AAAA",
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 1_024,
|
|
||||||
dataUrl: "data:image/png;base64,AAAA",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
model: "gpt-5.3",
|
model: "gpt-5.3",
|
||||||
@@ -242,10 +239,7 @@ describe("sendTurn", () => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
name: "diagram.png",
|
url: "data:image/png;base64,BBBB",
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 256,
|
|
||||||
dataUrl: "data:image/png;base64,BBBB",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
normalizeModelSlug,
|
normalizeModelSlug,
|
||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSendTurnInput,
|
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type ProviderSessionStartInput,
|
type ProviderSessionStartInput,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
@@ -71,6 +70,14 @@ interface JsonRpcNotification {
|
|||||||
params?: unknown;
|
params?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CodexAppServerSendTurnInput {
|
||||||
|
readonly sessionId: ProviderSessionId;
|
||||||
|
readonly input?: string;
|
||||||
|
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
|
||||||
|
readonly model?: string;
|
||||||
|
readonly effort?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CodexThreadTurnSnapshot {
|
export interface CodexThreadTurnSnapshot {
|
||||||
id: ProviderTurnId;
|
id: ProviderTurnId;
|
||||||
items: unknown[];
|
items: unknown[];
|
||||||
@@ -290,7 +297,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
const context = this.requireSession(input.sessionId);
|
const context = this.requireSession(input.sessionId);
|
||||||
if (!context.session.threadId) {
|
if (!context.session.threadId) {
|
||||||
throw new Error("Session is missing a thread id.");
|
throw new Error("Session is missing a thread id.");
|
||||||
@@ -310,7 +317,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
if (attachment.type === "image") {
|
if (attachment.type === "image") {
|
||||||
turnInput.push({
|
turnInput.push({
|
||||||
type: "image",
|
type: "image",
|
||||||
url: attachment.dataUrl,
|
url: attachment.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,29 @@ export interface ServerConfigShape {
|
|||||||
*/
|
*/
|
||||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||||
"t3/config/ServerConfig",
|
"t3/config/ServerConfig",
|
||||||
) {}
|
) {
|
||||||
|
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||||
|
Layer.effect(
|
||||||
|
ServerConfig,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
return {
|
||||||
|
cwd,
|
||||||
|
stateDir: statedir,
|
||||||
|
mode: "web",
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
port: 0,
|
||||||
|
host: undefined,
|
||||||
|
authToken: undefined,
|
||||||
|
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: undefined,
|
||||||
|
noBrowser: false,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Helpers
|
// Helpers
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,17 @@ import { it } from "@effect/vitest";
|
|||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
|
||||||
|
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||||
|
CodexTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
function makeFakeCodexBinary(dir: string) {
|
function makeFakeCodexBinary(dir: string) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
@@ -21,13 +28,36 @@ function makeFakeCodexBinary(dir: string) {
|
|||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
'output_path=""',
|
'output_path=""',
|
||||||
"while [ $# -gt 0 ]; do",
|
"while [ $# -gt 0 ]; do",
|
||||||
|
' if [ "$1" = "--image" ]; then',
|
||||||
|
" shift",
|
||||||
|
' if [ -n "$1" ]; then',
|
||||||
|
' seen_image="1"',
|
||||||
|
" fi",
|
||||||
|
" continue",
|
||||||
|
" fi",
|
||||||
' if [ "$1" = "--output-last-message" ]; then',
|
' if [ "$1" = "--output-last-message" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' output_path="$1"',
|
' output_path="$1"',
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
" shift",
|
||||||
"done",
|
"done",
|
||||||
"cat >/dev/null",
|
'stdin_content="$(cat)"',
|
||||||
|
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||||
|
' printf "%s\\n" "missing --image input" >&2',
|
||||||
|
" exit 2",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
" exit 3",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||||
|
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||||
|
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||||
|
" exit 4",
|
||||||
|
" fi",
|
||||||
|
"fi",
|
||||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||||
"fi",
|
"fi",
|
||||||
@@ -48,6 +78,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
output: string;
|
output: string;
|
||||||
exitCode?: number;
|
exitCode?: number;
|
||||||
stderr?: string;
|
stderr?: string;
|
||||||
|
requireImage?: boolean;
|
||||||
|
stdinMustContain?: string;
|
||||||
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
effect: Effect.Effect<A, E, R>,
|
effect: Effect.Effect<A, E, R>,
|
||||||
) {
|
) {
|
||||||
@@ -60,6 +93,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
|
||||||
yield* Effect.sync(() => {
|
yield* Effect.sync(() => {
|
||||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||||
@@ -76,6 +112,24 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
} else {
|
} else {
|
||||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (input.requireImage) {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustNotContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -83,6 +137,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
previousOutput,
|
previousOutput,
|
||||||
previousExitCode,
|
previousExitCode,
|
||||||
previousStderr,
|
previousStderr,
|
||||||
|
previousRequireImage,
|
||||||
|
previousStdinMustContain,
|
||||||
|
previousStdinMustNotContain,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
() => effect,
|
() => effect,
|
||||||
@@ -107,14 +164,29 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
} else {
|
} else {
|
||||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (previous.previousRequireImage === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustNotContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = Layer.provideMerge(
|
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||||
CodexTextGenerationLive,
|
|
||||||
NodeServices.layer,
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||||
it.effect("generates and sanitizes commit messages", () =>
|
it.effect("generates and sanitizes commit messages", () =>
|
||||||
@@ -170,6 +242,216 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("generates branch names and normalizes branch fragments", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: " Feat/Session ",
|
||||||
|
}),
|
||||||
|
stdinMustNotContain: "Image attachments supplied to the model",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Please update session handling.",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("feat/session");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/session-timeout",
|
||||||
|
}),
|
||||||
|
stdinMustNotContain: "Attachment metadata:",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix timeout behavior.",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("passes image attachments through as codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
stdinMustContain: "Attachment metadata:",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: attachmentId,
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const attachmentId =
|
||||||
|
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: attachmentId,
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.tap(() =>
|
||||||
|
fs.stat(imagePath).pipe(
|
||||||
|
Effect.map((fileInfo) => {
|
||||||
|
expect(fileInfo.type).toBe("File");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.ensuring(
|
||||||
|
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("ignores missing attachment ids for codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||||
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const result = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: missingAttachmentId,
|
||||||
|
name: "outside.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("missing --image input");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect(
|
||||||
|
"fails with typed TextGenerationError when codex returns wrong branch payload shape",
|
||||||
|
() =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
title: "This is not a branch payload",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const result = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix websocket reconnect flake",
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,8 +3,12 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
|
type BranchNameGenerationInput,
|
||||||
|
type BranchNameGenerationResult,
|
||||||
type CommitMessageGenerationResult,
|
type CommitMessageGenerationResult,
|
||||||
type PrContentGenerationResult,
|
type PrContentGenerationResult,
|
||||||
type TextGenerationShape,
|
type TextGenerationShape,
|
||||||
@@ -15,26 +19,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
|
|||||||
const CODEX_REASONING_EFFORT = "low";
|
const CODEX_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
subject: { type: "string" },
|
|
||||||
body: { type: "string" },
|
|
||||||
},
|
|
||||||
required: ["subject", "body"],
|
|
||||||
additionalProperties: false,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const PR_OUTPUT_SCHEMA_JSON = {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
title: { type: "string" },
|
|
||||||
body: { type: "string" },
|
|
||||||
},
|
|
||||||
required: ["title", "body"],
|
|
||||||
additionalProperties: false,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
function normalizeCodexError(
|
function normalizeCodexError(
|
||||||
operation: string,
|
operation: string,
|
||||||
error: unknown,
|
error: unknown,
|
||||||
@@ -71,32 +55,6 @@ function normalizeCodexError(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
|
|
||||||
if (!raw || typeof raw !== "object") {
|
|
||||||
throw new Error("Codex returned a non-object commit message payload.");
|
|
||||||
}
|
|
||||||
const record = raw as Record<string, unknown>;
|
|
||||||
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
|
|
||||||
const body = typeof record.body === "string" ? record.body : "";
|
|
||||||
if (subject.length === 0) {
|
|
||||||
throw new Error("Codex returned an empty commit subject.");
|
|
||||||
}
|
|
||||||
return { subject, body };
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePrOutput(raw: unknown): { title: string; body: string } {
|
|
||||||
if (!raw || typeof raw !== "object") {
|
|
||||||
throw new Error("Codex returned a non-object PR payload.");
|
|
||||||
}
|
|
||||||
const record = raw as Record<string, unknown>;
|
|
||||||
const title = typeof record.title === "string" ? record.title.trim() : "";
|
|
||||||
const body = typeof record.body === "string" ? record.body.trim() : "";
|
|
||||||
if (title.length === 0 || body.length === 0) {
|
|
||||||
throw new Error("Codex returned an invalid PR title/body payload.");
|
|
||||||
}
|
|
||||||
return { title, body };
|
|
||||||
}
|
|
||||||
|
|
||||||
function limitSection(value: string, maxChars: number): string {
|
function limitSection(value: string, maxChars: number): string {
|
||||||
if (value.length <= maxChars) return value;
|
if (value.length <= maxChars) return value;
|
||||||
const truncated = value.slice(0, maxChars);
|
const truncated = value.slice(0, maxChars);
|
||||||
@@ -124,10 +82,33 @@ function sanitizePrTitle(raw: string): string {
|
|||||||
return "Update project changes";
|
return "Update project changes";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sanitizeBranchName(raw: string): string {
|
||||||
|
const normalized = raw
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/['"`]/g, "")
|
||||||
|
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||||
|
|
||||||
|
const branchFragment = normalized
|
||||||
|
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||||
|
.replace(/\/+/g, "/")
|
||||||
|
.replace(/-+/g, "-")
|
||||||
|
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||||
|
.slice(0, 64)
|
||||||
|
.replace(/[./_-]+$/g, "");
|
||||||
|
|
||||||
|
return branchFragment.length > 0 ? branchFragment : "update";
|
||||||
|
}
|
||||||
|
|
||||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
|
|
||||||
|
type MaterializedImageAttachments = {
|
||||||
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
|
};
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
const readStreamAsString = <E>(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -171,24 +152,59 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const runCodexJson = <T>({
|
const materializeImageAttachments = (
|
||||||
|
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||||
|
attachments: BranchNameGenerationInput["attachments"],
|
||||||
|
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (!attachments || attachments.length === 0) {
|
||||||
|
return { imagePaths: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const imagePaths: string[] = [];
|
||||||
|
for (const attachment of attachments) {
|
||||||
|
if (attachment.type !== "image") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolvedPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(resolvedPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
imagePaths.push(resolvedPath);
|
||||||
|
}
|
||||||
|
return { imagePaths };
|
||||||
|
});
|
||||||
|
|
||||||
|
const runCodexJson = <S extends Schema.Top>({
|
||||||
operation,
|
operation,
|
||||||
cwd,
|
cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson,
|
outputSchemaJson,
|
||||||
parse,
|
imagePaths = [],
|
||||||
|
cleanupPaths = [],
|
||||||
}: {
|
}: {
|
||||||
operation: "generateCommitMessage" | "generatePrContent";
|
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: object;
|
outputSchemaJson: S;
|
||||||
parse: (raw: unknown) => T;
|
imagePaths?: ReadonlyArray<string>;
|
||||||
}): Effect.Effect<T, TextGenerationError> =>
|
cleanupPaths?: ReadonlyArray<string>;
|
||||||
|
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const schemaPath = yield* writeTempFile(
|
const schemaPath = yield* writeTempFile(
|
||||||
operation,
|
operation,
|
||||||
"codex-schema",
|
"codex-schema",
|
||||||
JSON.stringify(outputSchemaJson),
|
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
|
||||||
);
|
);
|
||||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||||
|
|
||||||
@@ -208,6 +224,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
schemaPath,
|
schemaPath,
|
||||||
"--output-last-message",
|
"--output-last-message",
|
||||||
outputPath,
|
outputPath,
|
||||||
|
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||||
"-",
|
"-",
|
||||||
],
|
],
|
||||||
{
|
{
|
||||||
@@ -254,9 +271,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
|
const cleanup = Effect.all(
|
||||||
concurrency: "unbounded",
|
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||||
}).pipe(Effect.asVoid);
|
{
|
||||||
|
concurrency: "unbounded",
|
||||||
|
},
|
||||||
|
).pipe(Effect.asVoid);
|
||||||
|
|
||||||
return yield* Effect.gen(function* () {
|
return yield* Effect.gen(function* () {
|
||||||
yield* runCodexCommand.pipe(
|
yield* runCodexCommand.pipe(
|
||||||
@@ -273,7 +293,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
|
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
new TextGenerationError({
|
new TextGenerationError({
|
||||||
@@ -282,30 +302,17 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
cause,
|
cause,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex returned invalid structured output.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const trimmed = rawOutput.trim();
|
|
||||||
if (trimmed.length === 0) {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned an empty response.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsedJson = yield* Effect.try({
|
|
||||||
try: () => JSON.parse(trimmed) as unknown,
|
|
||||||
catch: (cause) =>
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned invalid JSON output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
return yield* Effect.try({
|
|
||||||
try: () => parse(parsedJson),
|
|
||||||
catch: (cause) =>
|
|
||||||
normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
|
|
||||||
});
|
|
||||||
}).pipe(Effect.ensuring(cleanup));
|
}).pipe(Effect.ensuring(cleanup));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -331,8 +338,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
outputSchemaJson: Schema.Struct({
|
||||||
parse: (raw) => parseCommitOutput(raw),
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
}),
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(generated) =>
|
(generated) =>
|
||||||
@@ -371,8 +380,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
outputSchemaJson: Schema.Struct({
|
||||||
parse: (raw) => parsePrOutput(raw),
|
title: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
}),
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(generated) =>
|
(generated) =>
|
||||||
@@ -384,9 +395,55 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||||
|
const attachmentLines = (input.attachments ?? []).map(
|
||||||
|
(attachment) =>
|
||||||
|
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const promptSections = [
|
||||||
|
"You generate concise git branch names.",
|
||||||
|
"Return a JSON object with key: branch.",
|
||||||
|
"Rules:",
|
||||||
|
"- Branch should describe the requested work from the user message.",
|
||||||
|
"- Keep it short and specific (2-6 words).",
|
||||||
|
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||||
|
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||||
|
"",
|
||||||
|
"User message:",
|
||||||
|
limitSection(input.message, 8_000),
|
||||||
|
];
|
||||||
|
if (attachmentLines.length > 0) {
|
||||||
|
promptSections.push(
|
||||||
|
"",
|
||||||
|
"Attachment metadata:",
|
||||||
|
limitSection(attachmentLines.join("\n"), 4_000),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const prompt = promptSections.join("\n");
|
||||||
|
|
||||||
|
const generated = yield* runCodexJson({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: Schema.Struct({
|
||||||
|
branch: Schema.String,
|
||||||
|
}),
|
||||||
|
imagePaths,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
branch: sanitizeBranchName(generated.branch),
|
||||||
|
} satisfies BranchNameGenerationResult;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
generatePrContent,
|
generatePrContent,
|
||||||
|
generateBranchName,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -106,6 +106,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
|||||||
listBranches: (input) => core.listBranches(input),
|
listBranches: (input) => core.listBranches(input),
|
||||||
createWorktree: (input) => core.createWorktree(input),
|
createWorktree: (input) => core.createWorktree(input),
|
||||||
removeWorktree: (input) => core.removeWorktree(input),
|
removeWorktree: (input) => core.removeWorktree(input),
|
||||||
|
renameBranch: (input) => core.renameBranch(input),
|
||||||
createBranch: (input) => core.createBranch(input),
|
createBranch: (input) => core.createBranch(input),
|
||||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||||
initRepo: (input) => core.initRepo(input),
|
initRepo: (input) => core.initRepo(input),
|
||||||
@@ -154,6 +155,13 @@ function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0])
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renameGitBranch(input: Parameters<GitCoreShape["renameBranch"]>[0]) {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const core = yield* GitCore;
|
||||||
|
return yield* core.renameBranch(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function pullGitBranch({ cwd }: { cwd: string }) {
|
function pullGitBranch({ cwd }: { cwd: string }) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const core = yield* GitCore;
|
const core = yield* GitCore;
|
||||||
@@ -650,6 +658,129 @@ it.layer(TestLayer)("git integration", (it) => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── renameGitBranch ──
|
||||||
|
|
||||||
|
describe("renameGitBranch", () => {
|
||||||
|
it.effect("renames the current branch", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "feature/old-name",
|
||||||
|
newBranch: "feature/new-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("feature/new-name");
|
||||||
|
|
||||||
|
const branches = yield* listGitBranches({ cwd: tmp });
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false);
|
||||||
|
const current = branches.branches.find((branch) => branch.current);
|
||||||
|
expect(current?.name).toBe("feature/new-name");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns success without git invocation when old/new names match", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
const current = (yield* listGitBranches({ cwd: tmp })).branches.find((b) => b.current)!;
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: current.name,
|
||||||
|
newBranch: current.name,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe(current.name);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("appends numeric suffix when target branch already exists", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "t3code/tmp-working",
|
||||||
|
newBranch: "t3code/feat/session",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("t3code/feat/session-1");
|
||||||
|
const branches = yield* listGitBranches({ cwd: tmp });
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
const current = branches.branches.find((branch) => branch.current);
|
||||||
|
expect(current?.name).toBe("t3code/feat/session-1");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("increments suffix until it finds an available branch name", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session-1" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "t3code/tmp-working",
|
||||||
|
newBranch: "t3code/feat/session",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("t3code/feat/session-2");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses '--' separator for branch rename arguments", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
|
||||||
|
const realGitService = yield* GitService;
|
||||||
|
let renameArgs: ReadonlyArray<string> | null = null;
|
||||||
|
const core = yield* makeIsolatedGitCore({
|
||||||
|
execute: (input) => {
|
||||||
|
if (input.args[0] === "branch" && input.args[1] === "-m") {
|
||||||
|
renameArgs = [...input.args];
|
||||||
|
}
|
||||||
|
return realGitService.execute(input);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const renamed = yield* core.renameBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "feature/old-name",
|
||||||
|
newBranch: "feature/new-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("feature/new-name");
|
||||||
|
expect(renameArgs).toEqual([
|
||||||
|
"branch",
|
||||||
|
"-m",
|
||||||
|
"--",
|
||||||
|
"feature/old-name",
|
||||||
|
"feature/new-name",
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
// ── createGitWorktree + removeGitWorktree ──
|
// ── createGitWorktree + removeGitWorktree ──
|
||||||
|
|
||||||
describe("createGitWorktree", () => {
|
describe("createGitWorktree", () => {
|
||||||
|
|||||||
@@ -158,6 +158,43 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
Effect.map((result) => result.stdout),
|
Effect.map((result) => result.stdout),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||||
|
executeGit(
|
||||||
|
"GitCore.branchExists",
|
||||||
|
cwd,
|
||||||
|
["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
|
||||||
|
{
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
timeoutMs: 5_000,
|
||||||
|
},
|
||||||
|
).pipe(Effect.map((result) => result.code === 0));
|
||||||
|
|
||||||
|
const resolveAvailableBranchName = (
|
||||||
|
cwd: string,
|
||||||
|
desiredBranch: string,
|
||||||
|
): Effect.Effect<string, GitCommandError> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const isDesiredTaken = yield* branchExists(cwd, desiredBranch);
|
||||||
|
if (!isDesiredTaken) {
|
||||||
|
return desiredBranch;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let suffix = 1; suffix <= 100; suffix += 1) {
|
||||||
|
const candidate = `${desiredBranch}-${suffix}`;
|
||||||
|
const isCandidateTaken = yield* branchExists(cwd, candidate);
|
||||||
|
if (!isCandidateTaken) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return yield* createGitCommandError(
|
||||||
|
"GitCore.renameBranch",
|
||||||
|
cwd,
|
||||||
|
["branch", "-m", "--", desiredBranch],
|
||||||
|
`Could not find an available branch name for '${desiredBranch}'.`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const resolveCurrentUpstream = (
|
const resolveCurrentUpstream = (
|
||||||
cwd: string,
|
cwd: string,
|
||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
@@ -393,7 +430,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
openPr: null,
|
pr: null,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -711,6 +748,26 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const renameBranch: GitCoreShape["renameBranch"] = (input) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (input.oldBranch === input.newBranch) {
|
||||||
|
return { branch: input.newBranch };
|
||||||
|
}
|
||||||
|
const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);
|
||||||
|
|
||||||
|
yield* executeGit(
|
||||||
|
"GitCore.renameBranch",
|
||||||
|
input.cwd,
|
||||||
|
["branch", "-m", "--", input.oldBranch, targetBranch],
|
||||||
|
{
|
||||||
|
timeoutMs: 10_000,
|
||||||
|
fallbackErrorMessage: "git branch rename failed",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return { branch: targetBranch };
|
||||||
|
});
|
||||||
|
|
||||||
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
||||||
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
@@ -725,11 +782,9 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Refresh upstream refs in the background so checkout remains responsive.
|
// Refresh upstream refs in the background so checkout remains responsive.
|
||||||
yield* Effect.sync(() => {
|
yield* Effect.forkDetach(
|
||||||
void Effect.runPromise(
|
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
);
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
||||||
@@ -750,6 +805,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
listBranches,
|
listBranches,
|
||||||
createWorktree,
|
createWorktree,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
renameBranch,
|
||||||
createBranch,
|
createBranch,
|
||||||
checkoutBranch,
|
checkoutBranch,
|
||||||
initRepo,
|
initRepo,
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ interface FakeGitTextGeneration {
|
|||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||||
|
generateBranchName: (input: {
|
||||||
|
cwd: string;
|
||||||
|
message: string;
|
||||||
|
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeTempDir(
|
function makeTempDir(
|
||||||
@@ -110,6 +114,10 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
title: "Add stacked git actions",
|
title: "Add stacked git actions",
|
||||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||||
}),
|
}),
|
||||||
|
generateBranchName: () =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "update-workflow",
|
||||||
|
}),
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -136,6 +144,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
generateBranchName: (input) =>
|
||||||
|
implementation.generateBranchName(input).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "fake text generation failed",
|
||||||
|
...(cause !== undefined ? { cause } : {}),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,7 +316,7 @@ function makeManager(input?: {
|
|||||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||||
|
|
||||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
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* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -324,17 +343,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-open-pr");
|
expect(status.branch).toBe("feature/status-open-pr");
|
||||||
expect(status.openPr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/status-open-pr",
|
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* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -354,7 +459,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-no-gh");
|
expect(status.branch).toBe("feature/status-no-gh");
|
||||||
expect(status.openPr).toBeNull();
|
expect(status.pr).toBeNull();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,62 @@ interface OpenPrInfo {
|
|||||||
headRefName: string;
|
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 {
|
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||||
return new GitManagerError({
|
return new GitManagerError({
|
||||||
operation,
|
operation,
|
||||||
@@ -79,12 +135,13 @@ function extractBranchFromRef(ref: string): string {
|
|||||||
return normalized.slice(firstSlash + 1).trim();
|
return normalized.slice(firstSlash + 1).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
function toStatusPr(pr: PullRequestInfo): {
|
||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
url: string;
|
||||||
baseBranch: string;
|
baseBranch: string;
|
||||||
headBranch: string;
|
headBranch: string;
|
||||||
|
state: "open" | "closed" | "merged";
|
||||||
} {
|
} {
|
||||||
return {
|
return {
|
||||||
number: pr.number,
|
number: pr.number,
|
||||||
@@ -92,6 +149,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
|
|||||||
url: pr.url,
|
url: pr.url,
|
||||||
baseBranch: pr.baseRefName,
|
baseBranch: pr.baseRefName,
|
||||||
headBranch: pr.headRefName,
|
headBranch: pr.headRefName,
|
||||||
|
state: pr.state,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,10 +181,56 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
url: first.url,
|
url: first.url,
|
||||||
baseRefName: first.baseRefName,
|
baseRefName: first.baseRefName,
|
||||||
headRefName: first.headRefName,
|
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) =>
|
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
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 status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||||
const details = yield* gitCore.statusDetails(input.cwd);
|
const details = yield* gitCore.statusDetails(input.cwd);
|
||||||
|
|
||||||
const openPr =
|
const pr =
|
||||||
details.branch && details.hasUpstream
|
details.branch !== null
|
||||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
Effect.catch(() => Effect.succeed(null)),
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
@@ -273,7 +377,7 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
openPr,
|
pr,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import type {
|
|||||||
|
|
||||||
import type { GitCommandError } from "../Errors.ts";
|
import type { GitCommandError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||||
upstreamRef: string | null;
|
upstreamRef: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +46,16 @@ export interface GitRangeContext {
|
|||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchInput {
|
||||||
|
cwd: string;
|
||||||
|
oldBranch: string;
|
||||||
|
newBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchResult {
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||||
*/
|
*/
|
||||||
@@ -124,6 +134,13 @@ export interface GitCoreShape {
|
|||||||
*/
|
*/
|
||||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename an existing local branch.
|
||||||
|
*/
|
||||||
|
readonly renameBranch: (
|
||||||
|
input: GitRenameBranchInput,
|
||||||
|
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a local branch.
|
* Create a local branch.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
*/
|
*/
|
||||||
import { ServiceMap } from "effect";
|
import { ServiceMap } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import type { TextGenerationError } from "../Errors.ts";
|
import type { TextGenerationError } from "../Errors.ts";
|
||||||
|
|
||||||
@@ -37,11 +38,22 @@ export interface PrContentGenerationResult {
|
|||||||
body: string;
|
body: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BranchNameGenerationInput {
|
||||||
|
cwd: string;
|
||||||
|
message: string;
|
||||||
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BranchNameGenerationResult {
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TextGenerationService {
|
export interface TextGenerationService {
|
||||||
generateCommitMessage(
|
generateCommitMessage(
|
||||||
input: CommitMessageGenerationInput,
|
input: CommitMessageGenerationInput,
|
||||||
): Promise<CommitMessageGenerationResult>;
|
): Promise<CommitMessageGenerationResult>;
|
||||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||||
|
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -61,6 +73,13 @@ export interface TextGenerationShape {
|
|||||||
readonly generatePrContent: (
|
readonly generatePrContent: (
|
||||||
input: PrContentGenerationInput,
|
input: PrContentGenerationInput,
|
||||||
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a concise branch name from a user message.
|
||||||
|
*/
|
||||||
|
readonly generateBranchName: (
|
||||||
|
input: BranchNameGenerationInput,
|
||||||
|
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||||
|
|
||||||
|
describe("imageMime", () => {
|
||||||
|
it("parses base64 data URL with mime type", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses base64 data URL with mime parameters", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-base64 data URL", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects missing mime type", () => {
|
||||||
|
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses base64 data URL with spaces in payload", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not read inherited keys from mime extension map", () => {
|
||||||
|
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import Mime from "@effect/platform-node/Mime";
|
||||||
|
|
||||||
|
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||||
|
"image/avif": ".avif",
|
||||||
|
"image/bmp": ".bmp",
|
||||||
|
"image/gif": ".gif",
|
||||||
|
"image/heic": ".heic",
|
||||||
|
"image/heif": ".heif",
|
||||||
|
"image/jpeg": ".jpg",
|
||||||
|
"image/jpg": ".jpg",
|
||||||
|
"image/png": ".png",
|
||||||
|
"image/svg+xml": ".svg",
|
||||||
|
"image/tiff": ".tiff",
|
||||||
|
"image/webp": ".webp",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||||
|
".avif",
|
||||||
|
".bmp",
|
||||||
|
".gif",
|
||||||
|
".heic",
|
||||||
|
".heif",
|
||||||
|
".ico",
|
||||||
|
".jpeg",
|
||||||
|
".jpg",
|
||||||
|
".png",
|
||||||
|
".svg",
|
||||||
|
".tiff",
|
||||||
|
".webp",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function parseBase64DataUrl(
|
||||||
|
dataUrl: string,
|
||||||
|
): { readonly mimeType: string; readonly base64: string } | null {
|
||||||
|
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
const headerParts = (match[1] ?? "")
|
||||||
|
.split(";")
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter((part) => part.length > 0);
|
||||||
|
if (headerParts.length < 2) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const trailingToken = headerParts.at(-1)?.toLowerCase();
|
||||||
|
if (trailingToken !== "base64") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mimeType = headerParts[0]?.toLowerCase();
|
||||||
|
const base64 = match[2]?.replace(/\s+/g, "");
|
||||||
|
if (!mimeType || !base64) return null;
|
||||||
|
|
||||||
|
return { mimeType, base64 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||||
|
const key = input.mimeType.toLowerCase();
|
||||||
|
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||||
|
? IMAGE_EXTENSION_BY_MIME_TYPE[key]
|
||||||
|
: undefined;
|
||||||
|
if (fromMime) {
|
||||||
|
return fromMime;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||||
|
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
|
||||||
|
return fromMimeExtension;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileName = input.fileName?.trim() ?? "";
|
||||||
|
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||||
|
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||||
|
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||||
|
return fileNameExtension;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ".bin";
|
||||||
|
}
|
||||||
@@ -49,10 +49,21 @@ const testLayer = Layer.mergeAll(
|
|||||||
const runCli = (
|
const runCli = (
|
||||||
args: ReadonlyArray<string>,
|
args: ReadonlyArray<string>,
|
||||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||||
) =>
|
) => {
|
||||||
Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
|
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_STATE_DIR: uniqueStateDir,
|
||||||
|
...env,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import {
|
|||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
@@ -238,6 +239,7 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(CheckpointStoreLive),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import {
|
|||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||||
@@ -37,6 +39,8 @@ async function createOrchestrationSystem() {
|
|||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
@@ -310,6 +314,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,3 @@
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
@@ -39,10 +38,11 @@ import {
|
|||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
import {
|
import {
|
||||||
ATTACHMENTS_ROUTE_PREFIX,
|
attachmentRelativePath,
|
||||||
IMAGE_EXTENSION_BY_MIME_TYPE,
|
parseAttachmentIdFromRelativePath,
|
||||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
parseThreadSegmentFromAttachmentId,
|
||||||
} from "../../projectFaviconRoute.ts";
|
toSafeThreadAttachmentSegment,
|
||||||
|
} from "../../attachmentStore.ts";
|
||||||
|
|
||||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||||
projects: "projection.projects",
|
projects: "projection.projects",
|
||||||
@@ -66,115 +66,16 @@ interface ProjectorDefinition {
|
|||||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PendingAttachmentWrite {
|
|
||||||
readonly absolutePath: string;
|
|
||||||
readonly bytes: Uint8Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttachmentSideEffects {
|
interface AttachmentSideEffects {
|
||||||
readonly writes: Array<PendingAttachmentWrite>;
|
|
||||||
readonly deletedThreadIds: Set<string>;
|
readonly deletedThreadIds: Set<string>;
|
||||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
const materializeAttachmentsForProjection = Effect.fn(
|
||||||
const segment = encodeURIComponent(threadId);
|
(input: {
|
||||||
if (
|
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||||
segment.length === 0 ||
|
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||||
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 {
|
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||||
if (typeof payload !== "object" || payload === null) {
|
if (typeof payload !== "object" || payload === null) {
|
||||||
@@ -288,18 +189,6 @@ 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(
|
function collectThreadAttachmentRelativePaths(
|
||||||
threadId: string,
|
threadId: string,
|
||||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||||
@@ -308,41 +197,31 @@ function collectThreadAttachmentRelativePaths(
|
|||||||
if (!threadSegment) {
|
if (!threadSegment) {
|
||||||
return new Set();
|
return new Set();
|
||||||
}
|
}
|
||||||
const threadPrefix = `${threadSegment}/`;
|
|
||||||
const relativePaths = new Set<string>();
|
const relativePaths = new Set<string>();
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
for (const attachment of message.attachments ?? []) {
|
for (const attachment of message.attachments ?? []) {
|
||||||
if (attachment.type !== "image") {
|
if (attachment.type !== "image") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||||
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
relativePaths.add(attachmentRelativePath(attachment));
|
||||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return relativePaths;
|
return relativePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||||
readonly sideEffects: AttachmentSideEffects;
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
readonly fileSystem: FileSystem.FileSystem;
|
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||||
readonly path: Path.Path;
|
const path = yield* Effect.service(Path.Path);
|
||||||
}) {
|
|
||||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
|
||||||
if (Option.isNone(serverConfig)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.sideEffects.deletedThreadIds,
|
sideEffects.deletedThreadIds,
|
||||||
(threadId) =>
|
(threadId) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
@@ -352,16 +231,39 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
const entries = yield* fileSystem
|
||||||
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
|
yield* Effect.forEach(
|
||||||
|
entries,
|
||||||
|
(entry) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
}),
|
}),
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.sideEffects.prunedThreadRelativePaths.entries(),
|
sideEffects.prunedThreadRelativePaths.entries(),
|
||||||
([threadId, keptThreadRelativePaths]) => {
|
([threadId, keptThreadRelativePaths]) => {
|
||||||
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||||
return Effect.void;
|
return Effect.void;
|
||||||
}
|
}
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
@@ -370,29 +272,36 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
const entries = yield* fileSystem
|
||||||
const entries = yield* input.fileSystem
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
.readDirectory(threadDir, { recursive: true })
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
entries,
|
entries,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||||
const fileInfo = yield* input.fileSystem
|
const fileInfo = yield* fileSystem
|
||||||
.stat(absolutePath)
|
.stat(absolutePath)
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||||
yield* input.fileSystem.remove(absolutePath, { force: true });
|
yield* fileSystem.remove(absolutePath, { force: true });
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
@@ -402,22 +311,6 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
{ 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 makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||||
@@ -434,6 +327,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
const serverConfig = yield* ServerConfig;
|
||||||
|
|
||||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -634,13 +528,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const nextAttachments =
|
const nextAttachments =
|
||||||
event.payload.attachments !== undefined
|
event.payload.attachments !== undefined
|
||||||
? yield* materializeAttachmentsForProjection({
|
? yield* materializeAttachmentsForProjection({
|
||||||
threadId: event.payload.threadId,
|
|
||||||
messageId: event.payload.messageId,
|
|
||||||
attachments: event.payload.attachments,
|
attachments: event.payload.attachments,
|
||||||
stageFileWrite: (pendingWrite) => {
|
})
|
||||||
attachmentSideEffects.writes.push(pendingWrite);
|
|
||||||
},
|
|
||||||
}).pipe(Effect.provideService(Path.Path, path))
|
|
||||||
: existingMessage?.attachments;
|
: existingMessage?.attachments;
|
||||||
yield* projectionThreadMessageRepository.upsert({
|
yield* projectionThreadMessageRepository.upsert({
|
||||||
messageId: event.payload.messageId,
|
messageId: event.payload.messageId,
|
||||||
@@ -1131,7 +1020,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const attachmentSideEffects: AttachmentSideEffects = {
|
const attachmentSideEffects: AttachmentSideEffects = {
|
||||||
writes: [],
|
|
||||||
deletedThreadIds: new Set<string>(),
|
deletedThreadIds: new Set<string>(),
|
||||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||||
};
|
};
|
||||||
@@ -1148,11 +1036,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* runAttachmentSideEffects({
|
yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
|
||||||
sideEffects: attachmentSideEffects,
|
|
||||||
fileSystem,
|
|
||||||
path,
|
|
||||||
}).pipe(
|
|
||||||
Effect.catch((cause) =>
|
Effect.catch((cause) =>
|
||||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||||
projector: projector.name,
|
projector: projector.name,
|
||||||
@@ -1184,6 +1068,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
}).pipe(
|
}).pipe(
|
||||||
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
Effect.catchTag("SqlError", (sqlError) =>
|
Effect.catchTag("SqlError", (sqlError) =>
|
||||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||||
@@ -1195,6 +1082,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
bootstrapProjector,
|
bootstrapProjector,
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
Effect.tap(() =>
|
Effect.tap(() =>
|
||||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
@@ -13,6 +17,8 @@ import {
|
|||||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { TextGenerationError } from "../../git/Errors.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||||
@@ -20,11 +26,14 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
|
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||||
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
@@ -56,6 +65,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
unknown
|
unknown
|
||||||
> | null = null;
|
> | null = null;
|
||||||
let scope: Scope.Closeable | null = null;
|
let scope: Scope.Closeable | null = null;
|
||||||
|
const createdStateDirs = new Set<string>();
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
if (scope) {
|
if (scope) {
|
||||||
@@ -66,10 +76,16 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
}
|
}
|
||||||
runtime = null;
|
runtime = null;
|
||||||
|
for (const stateDir of createdStateDirs) {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
createdStateDirs.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function createHarness() {
|
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||||
|
createdStateDirs.add(stateDir);
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
let nextSessionIndex = 1;
|
let nextSessionIndex = 1;
|
||||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||||
@@ -92,6 +108,16 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||||
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
||||||
const stopSession = vi.fn((_: unknown) => Effect.void);
|
const stopSession = vi.fn((_: unknown) => Effect.void);
|
||||||
|
const renameBranch = vi.fn((_: unknown) =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "t3code/generated-name",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "generated-name",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||||
const service: ProviderServiceShape = {
|
const service: ProviderServiceShape = {
|
||||||
@@ -115,8 +141,15 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const layer = ProviderCommandReactorLive.pipe(
|
const layer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||||
|
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||||
|
Layer.provideMerge(
|
||||||
|
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
runtime = ManagedRuntime.make(layer);
|
const runtime = ManagedRuntime.make(layer);
|
||||||
|
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
@@ -155,6 +188,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
interruptTurn,
|
interruptTurn,
|
||||||
respondToRequest,
|
respondToRequest,
|
||||||
stopSession,
|
stopSession,
|
||||||
|
renameBranch,
|
||||||
|
generateBranchName,
|
||||||
|
stateDir,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,6 +232,247 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("generates and renames temporary worktree branch on first turn", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/89abc123",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-worktree-rename"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-rename",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
|
||||||
|
|
||||||
|
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
message: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-rename",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
oldBranch: "t3code/89abc123",
|
||||||
|
newBranch: "t3code/generated-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const readModel = Effect.runSync(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
return thread?.branch === "t3code/generated-name";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes persisted attachment references to branch generation and turn start", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/abcdef12",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-persisted-attachments"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
|
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||||
|
message: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips worktree branch generation after the first user turn", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/1234abcd",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-first"),
|
||||||
|
role: "user",
|
||||||
|
text: "first",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-second"),
|
||||||
|
role: "user",
|
||||||
|
text: "second",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||||
|
expect(harness.generateBranchName.mock.calls.length).toBe(1);
|
||||||
|
expect(harness.renameBranch.mock.calls.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips worktree rename when branch-name generation fails", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
harness.generateBranchName.mockImplementationOnce(() =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "model returned invalid payload",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/0000abcd",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-null-branch"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual regression",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await Effect.runPromise(Effect.sleep("20 millis"));
|
||||||
|
expect(harness.renameBranch.mock.calls.length).toBe(0);
|
||||||
|
|
||||||
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
|
expect(thread?.branch).toBe("t3code/0000abcd");
|
||||||
|
});
|
||||||
|
|
||||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -328,8 +605,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
|
harness.startSession.mockImplementationOnce(
|
||||||
Effect.fail(new Error("simulated restart failure")) as never,
|
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
await Effect.runPromise(
|
await Effect.runPromise(
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import {
|
|||||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||||
|
|
||||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||||
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import {
|
import {
|
||||||
@@ -66,10 +68,41 @@ const HANDLED_TURN_START_KEY_MAX = 10_000;
|
|||||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||||
|
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||||
|
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||||
|
|
||||||
|
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||||
|
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||||
|
const normalized = raw
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/^refs\/heads\//, "")
|
||||||
|
.replace(/['"`]/g, "");
|
||||||
|
|
||||||
|
const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
|
||||||
|
? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
|
||||||
|
: normalized;
|
||||||
|
|
||||||
|
const branchFragment = withoutPrefix
|
||||||
|
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||||
|
.replace(/\/+/g, "/")
|
||||||
|
.replace(/-+/g, "-")
|
||||||
|
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||||
|
.slice(0, 64)
|
||||||
|
.replace(/[./_-]+$/g, "");
|
||||||
|
|
||||||
|
const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
|
||||||
|
return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
|
||||||
|
}
|
||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
|
const git = yield* GitCore;
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||||
@@ -190,7 +223,8 @@ const make = Effect.gen(function* () {
|
|||||||
const existingSessionId = thread.session?.providerSessionId;
|
const existingSessionId = thread.session?.providerSessionId;
|
||||||
if (existingSessionId) {
|
if (existingSessionId) {
|
||||||
const approvalPolicyChanged =
|
const approvalPolicyChanged =
|
||||||
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
|
options?.approvalPolicy !== undefined &&
|
||||||
|
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||||
const sandboxModeChanged =
|
const sandboxModeChanged =
|
||||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||||
|
|
||||||
@@ -198,7 +232,9 @@ const make = Effect.gen(function* () {
|
|||||||
return existingSessionId;
|
return existingSessionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
|
const restartedSession = yield* startProviderSession(
|
||||||
|
thread.session?.providerThreadId ?? null,
|
||||||
|
);
|
||||||
yield* bindSessionToThread(restartedSession);
|
yield* bindSessionToThread(restartedSession);
|
||||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||||
Effect.catchCause((cause) =>
|
Effect.catchCause((cause) =>
|
||||||
@@ -247,6 +283,74 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
|
||||||
|
readonly threadId: ThreadId;
|
||||||
|
readonly branch: string | null;
|
||||||
|
readonly worktreePath: string | null;
|
||||||
|
readonly messageId: string;
|
||||||
|
readonly messageText: string;
|
||||||
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
|
}) {
|
||||||
|
if (!input.branch || !input.worktreePath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isTemporaryWorktreeBranch(input.branch)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const thread = yield* resolveThread(input.threadId);
|
||||||
|
if (!thread) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userMessages = thread.messages.filter((message) => message.role === "user");
|
||||||
|
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldBranch = input.branch;
|
||||||
|
const cwd = input.worktreePath;
|
||||||
|
const attachments = input.attachments ?? [];
|
||||||
|
yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd,
|
||||||
|
message: input.messageText,
|
||||||
|
...(attachments.length > 0 ? { attachments } : {}),
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.catch((error) =>
|
||||||
|
Effect.logWarning(
|
||||||
|
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.flatMap((generated) => {
|
||||||
|
if (!generated) return Effect.void;
|
||||||
|
|
||||||
|
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||||
|
if (targetBranch === oldBranch) return Effect.void;
|
||||||
|
|
||||||
|
return Effect.flatMap(
|
||||||
|
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||||
|
(renamed) =>
|
||||||
|
orchestrationEngine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: serverCommandId("worktree-branch-rename"),
|
||||||
|
threadId: input.threadId,
|
||||||
|
branch: renamed.branch,
|
||||||
|
worktreePath: cwd,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
Effect.catchCause((cause) =>
|
||||||
|
Effect.logWarning(
|
||||||
|
"provider command reactor failed to generate or rename worktree branch",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||||
) {
|
) {
|
||||||
@@ -273,6 +377,15 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
||||||
|
threadId: event.payload.threadId,
|
||||||
|
branch: thread.branch,
|
||||||
|
worktreePath: thread.worktreePath,
|
||||||
|
messageId: message.id,
|
||||||
|
messageText: message.text,
|
||||||
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
|
}).pipe(Effect.forkScoped);
|
||||||
|
|
||||||
yield* sendTurnForThread({
|
yield* sendTurnForThread({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
messageText: message.text,
|
messageText: message.text,
|
||||||
|
|||||||
@@ -28,11 +28,12 @@ import {
|
|||||||
type OrchestrationEngineShape,
|
type OrchestrationEngineShape,
|
||||||
} from "../Services/OrchestrationEngine.ts";
|
} from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asProviderThreadId = (value: string): ProviderThreadId =>
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
ProviderThreadId.makeUnsafe(value);
|
|
||||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
@@ -122,6 +123,8 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
@@ -255,7 +258,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
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?.session?.status).toBe("running");
|
expect(midThread?.session?.status).toBe("running");
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||||
|
|
||||||
@@ -308,7 +313,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
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?.session?.status).toBe("running");
|
expect(midThread?.session?.status).toBe("running");
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||||
|
|
||||||
@@ -401,7 +408,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
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?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
|
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
@@ -416,10 +425,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-buffered"),
|
itemId: asItemId("item-buffered"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-buffered" && !message.streaming,
|
||||||
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
|
),
|
||||||
);
|
);
|
||||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
||||||
expect(message?.text).toBe("buffer me");
|
expect(message?.text).toBe("buffer me");
|
||||||
@@ -475,15 +484,13 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
delta: "hello live",
|
delta: "hello live",
|
||||||
});
|
});
|
||||||
|
|
||||||
const liveThread = await waitForThread(
|
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) =>
|
||||||
entry.messages.some(
|
message.id === "assistant:item-streaming-mode" &&
|
||||||
(message) =>
|
message.streaming &&
|
||||||
message.id === "assistant:item-streaming-mode" &&
|
message.text === "hello live",
|
||||||
message.streaming &&
|
),
|
||||||
message.text === "hello live",
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const liveMessage = liveThread.messages.find(
|
const liveMessage = liveThread.messages.find(
|
||||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||||
@@ -500,12 +507,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-streaming-mode"),
|
itemId: asItemId("item-streaming-mode"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const finalThread = await waitForThread(
|
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||||
entry.messages.some(
|
),
|
||||||
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const finalMessage = finalThread.messages.find(
|
const finalMessage = finalThread.messages.find(
|
||||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||||
@@ -554,12 +559,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-buffer-spill"),
|
itemId: asItemId("item-buffer-spill"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||||
entry.messages.some(
|
),
|
||||||
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
||||||
expect(message?.text.length).toBe(oversizedText.length);
|
expect(message?.text.length).toBe(oversizedText.length);
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
|||||||
const persistedAttachments = [
|
const persistedAttachments = [
|
||||||
{
|
{
|
||||||
type: "image" as const,
|
type: "image" as const,
|
||||||
|
id: "thread-preserve-attachments-att-1",
|
||||||
name: "example.png",
|
name: "example.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -74,10 +74,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
|
id: "thread-clear-attachments-att-1",
|
||||||
name: "example.png",
|
name: "example.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isStreaming: false,
|
isStreaming: false,
|
||||||
|
|||||||
@@ -2,32 +2,6 @@ import fs from "node:fs";
|
|||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import path from "node:path";
|
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> = {
|
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||||
".png": "image/png",
|
".png": "image/png",
|
||||||
".jpg": "image/jpeg",
|
".jpg": "image/jpeg",
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
ProviderItemId,
|
ProviderItemId,
|
||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSendTurnInput,
|
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type ProviderSessionStartInput,
|
type ProviderSessionStartInput,
|
||||||
@@ -12,12 +11,17 @@ import {
|
|||||||
ProviderTurnId,
|
ProviderTurnId,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||||
import { assertFailure } from "@effect/vitest/utils";
|
import { assertFailure } from "@effect/vitest/utils";
|
||||||
|
|
||||||
import { Effect, Fiber, Stream } from "effect";
|
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||||
|
|
||||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
import {
|
||||||
|
CodexAppServerManager,
|
||||||
|
type CodexAppServerSendTurnInput,
|
||||||
|
} from "../../codexAppServerManager.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||||
@@ -44,7 +48,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
);
|
);
|
||||||
|
|
||||||
public sendTurnImpl = vi.fn(
|
public sendTurnImpl = vi.fn(
|
||||||
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
||||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
}),
|
}),
|
||||||
@@ -78,7 +82,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
return this.startSessionImpl(input);
|
return this.startSessionImpl(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
override sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
return this.sendTurnImpl(input);
|
return this.sendTurnImpl(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +122,12 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const validationManager = new FakeCodexManager();
|
const validationManager = new FakeCodexManager();
|
||||||
const validationLayer = it.layer(makeCodexAdapterLive({ manager: validationManager }));
|
const validationLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
validationLayer("CodexAdapterLive validation", (it) => {
|
validationLayer("CodexAdapterLive validation", (it) => {
|
||||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||||
@@ -147,7 +156,12 @@ const sessionErrorManager = new FakeCodexManager();
|
|||||||
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||||
throw new Error("Unknown session: sess-missing");
|
throw new Error("Unknown session: sess-missing");
|
||||||
});
|
});
|
||||||
const sessionErrorLayer = it.layer(makeCodexAdapterLive({ manager: sessionErrorManager }));
|
const sessionErrorLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||||
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
|
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
|
||||||
@@ -178,7 +192,12 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const lifecycleManager = new FakeCodexManager();
|
const lifecycleManager = new FakeCodexManager();
|
||||||
const lifecycleLayer = it.layer(makeCodexAdapterLive({ manager: lifecycleManager }));
|
const lifecycleLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||||
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ProviderTurnId,
|
ProviderTurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, Queue, Schema, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ProviderAdapterProcessError,
|
ProviderAdapterProcessError,
|
||||||
@@ -29,6 +29,8 @@ import {
|
|||||||
} from "../Errors.ts";
|
} from "../Errors.ts";
|
||||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||||
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||||
|
|
||||||
const PROVIDER = "codex" as const;
|
const PROVIDER = "codex" as const;
|
||||||
@@ -426,6 +428,8 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
|||||||
|
|
||||||
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
const nativeEventLogger =
|
const nativeEventLogger =
|
||||||
options?.nativeEventLogPath !== undefined
|
options?.nativeEventLogPath !== undefined
|
||||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||||
@@ -475,9 +479,48 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
|||||||
};
|
};
|
||||||
|
|
||||||
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
||||||
Effect.tryPromise({
|
Effect.gen(function* () {
|
||||||
try: () => manager.sendTurn(input),
|
const codexAttachments = yield* Effect.forEach(
|
||||||
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
input.attachments ?? [],
|
||||||
|
(attachment) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const attachmentPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!attachmentPath) {
|
||||||
|
return yield* Effect.fail(
|
||||||
|
toRequestError(
|
||||||
|
input.sessionId,
|
||||||
|
"turn/start",
|
||||||
|
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||||
|
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
type: "image" as const,
|
||||||
|
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
return yield* Effect.tryPromise({
|
||||||
|
try: () => {
|
||||||
|
const managerInput = {
|
||||||
|
sessionId: input.sessionId,
|
||||||
|
...(input.input !== undefined ? { input: input.input } : {}),
|
||||||
|
...(input.model !== undefined ? { model: input.model } : {}),
|
||||||
|
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||||
|
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||||
|
};
|
||||||
|
return manager.sendTurn(managerInput);
|
||||||
|
},
|
||||||
|
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
|
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { Effect, Layer } from "effect";
|
import { Effect, FileSystem, Layer } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||||
@@ -37,7 +37,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
|||||||
export function makeServerProviderLayer(): Layer.Layer<
|
export function makeServerProviderLayer(): Layer.Layer<
|
||||||
ProviderService,
|
ProviderService,
|
||||||
ProviderUnsupportedError,
|
ProviderUnsupportedError,
|
||||||
SqlClient.SqlClient | ServerConfig
|
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const { stateDir } = yield* ServerConfig;
|
const { stateDir } = yield* ServerConfig;
|
||||||
@@ -56,6 +56,9 @@ export function makeServerProviderLayer(): Layer.Layer<
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function makeServerRuntimeServicesLayer() {
|
export function makeServerRuntimeServicesLayer() {
|
||||||
|
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
||||||
|
const textGenerationLayer = CodexTextGenerationLive;
|
||||||
|
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
@@ -78,6 +81,8 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
);
|
);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(gitCoreLayer),
|
||||||
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
@@ -92,12 +97,10 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||||
);
|
);
|
||||||
|
|
||||||
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
|
||||||
|
|
||||||
const gitManagerLayer = GitManagerLive.pipe(
|
const gitManagerLayer = GitManagerLive.pipe(
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(GitHubCliLive),
|
Layer.provideMerge(GitHubCliLive),
|
||||||
Layer.provideMerge(CodexTextGenerationLive),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
|
|
||||||
return Layer.mergeAll(
|
return Layer.mergeAll(
|
||||||
|
|||||||
@@ -369,7 +369,10 @@ describe("WebSocket Server", () => {
|
|||||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||||
open?: OpenShape;
|
open?: OpenShape;
|
||||||
gitManager?: GitManagerShape;
|
gitManager?: GitManagerShape;
|
||||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
gitCore?: Pick<
|
||||||
|
GitCoreShape,
|
||||||
|
"listBranches" | "initRepo" | "pullCurrentBranch"
|
||||||
|
>;
|
||||||
terminalManager?: TerminalManagerShape;
|
terminalManager?: TerminalManagerShape;
|
||||||
} = {},
|
} = {},
|
||||||
): Promise<Http.Server> {
|
): Promise<Http.Server> {
|
||||||
@@ -417,6 +420,7 @@ describe("WebSocket Server", () => {
|
|||||||
Layer.provideMerge(runtimeLayer),
|
Layer.provideMerge(runtimeLayer),
|
||||||
Layer.provideMerge(openLayer),
|
Layer.provideMerge(openLayer),
|
||||||
Layer.provideMerge(serverConfigLayer),
|
Layer.provideMerge(serverConfigLayer),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtimeServices = await Effect.runPromise(
|
const runtimeServices = await Effect.runPromise(
|
||||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||||
@@ -1507,6 +1511,7 @@ describe("WebSocket Server", () => {
|
|||||||
expect(pullResponse.result).toBeUndefined();
|
expect(pullResponse.result).toBeUndefined();
|
||||||
expect(pullResponse.error?.message).toContain("No upstream configured");
|
expect(pullResponse.error?.message).toContain("No upstream configured");
|
||||||
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
|
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports git.status over websocket", async () => {
|
it("supports git.status over websocket", async () => {
|
||||||
@@ -1521,7 +1526,7 @@ describe("WebSocket Server", () => {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
openPr: null,
|
pr: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||||
|
|||||||
+114
-13
@@ -12,8 +12,11 @@ import type { Duplex } from "node:stream";
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
import Mime from "@effect/platform-node/Mime";
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
|
type ClientOrchestrationCommand,
|
||||||
|
type OrchestrationCommand,
|
||||||
ORCHESTRATION_WS_CHANNELS,
|
ORCHESTRATION_WS_CHANNELS,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_WS_METHODS,
|
||||||
|
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TerminalEvent,
|
TerminalEvent,
|
||||||
@@ -54,7 +57,14 @@ import { clamp } from "effect/Number";
|
|||||||
import { Open } from "./open";
|
import { Open } from "./open";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig } from "./config";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
|
import {
|
||||||
|
ATTACHMENTS_ROUTE_PREFIX,
|
||||||
|
normalizeAttachmentRelativePath,
|
||||||
|
resolveAttachmentRelativePath,
|
||||||
|
} from "./attachmentPaths";
|
||||||
|
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||||
|
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerShape - Service API for server lifecycle control.
|
* ServerShape - Service API for server lifecycle control.
|
||||||
@@ -230,6 +240,88 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||||
|
readonly command: ClientOrchestrationCommand;
|
||||||
|
}) {
|
||||||
|
if (input.command.type !== "thread.turn.start") {
|
||||||
|
return input.command as OrchestrationCommand;
|
||||||
|
}
|
||||||
|
const turnStartCommand = input.command;
|
||||||
|
|
||||||
|
const normalizedAttachments = yield* Effect.forEach(
|
||||||
|
turnStartCommand.message.attachments,
|
||||||
|
(attachment) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||||
|
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = Buffer.from(parsed.base64, "base64");
|
||||||
|
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachmentId = createAttachmentId(turnStartCommand.threadId);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: "Failed to create a safe attachment id.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const persistedAttachment = {
|
||||||
|
type: "image" as const,
|
||||||
|
id: attachmentId,
|
||||||
|
name: attachment.name,
|
||||||
|
mimeType: parsed.mimeType.toLowerCase(),
|
||||||
|
sizeBytes: bytes.byteLength,
|
||||||
|
};
|
||||||
|
|
||||||
|
const attachmentPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment: persistedAttachment,
|
||||||
|
});
|
||||||
|
if (!attachmentPath) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
() =>
|
||||||
|
new RouteRequestError({
|
||||||
|
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
() =>
|
||||||
|
new RouteRequestError({
|
||||||
|
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return persistedAttachment;
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...turnStartCommand,
|
||||||
|
message: {
|
||||||
|
...turnStartCommand.message,
|
||||||
|
attachments: normalizedAttachments,
|
||||||
|
},
|
||||||
|
} satisfies OrchestrationCommand;
|
||||||
|
});
|
||||||
|
|
||||||
// HTTP server — serves static files or redirects to Vite dev server
|
// HTTP server — serves static files or redirects to Vite dev server
|
||||||
const httpServer = http.createServer((req, res) => {
|
const httpServer = http.createServer((req, res) => {
|
||||||
const respond = (
|
const respond = (
|
||||||
@@ -249,22 +341,30 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
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 rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||||
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||||
|
if (!normalizedRelativePath) {
|
||||||
if (
|
|
||||||
normalizedRelativePath.length === 0 ||
|
|
||||||
normalizedRelativePath.startsWith("..") ||
|
|
||||||
normalizedRelativePath.includes("\0")
|
|
||||||
) {
|
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
const isIdLookup =
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
const filePath = isIdLookup
|
||||||
|
? resolveAttachmentPathById({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachmentId: normalizedRelativePath,
|
||||||
|
})
|
||||||
|
: resolveAttachmentRelativePath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
relativePath: normalizedRelativePath,
|
||||||
|
});
|
||||||
|
if (!filePath) {
|
||||||
|
respond(
|
||||||
|
isIdLookup ? 404 : 400,
|
||||||
|
{ "Content-Type": "text/plain" },
|
||||||
|
isIdLookup ? "Not Found" : "Invalid attachment path",
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -506,7 +606,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
||||||
const { command } = request.body;
|
const { command } = request.body;
|
||||||
return yield* orchestrationEngine.dispatch(command);
|
const normalizedCommand = yield* normalizeDispatchCommand({ command });
|
||||||
|
return yield* orchestrationEngine.dispatch(normalizedCommand);
|
||||||
}
|
}
|
||||||
|
|
||||||
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
||||||
|
|||||||
@@ -22,12 +22,10 @@
|
|||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"highlight.js": "^11.11.1",
|
|
||||||
"lucide-react": "^0.564.0",
|
"lucide-react": "^0.564.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.4.0"
|
"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 { useCallback, useSyncExternalStore } from "react";
|
||||||
import { Option, Schema } from "effect";
|
import { Option, Schema } from "effect";
|
||||||
|
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||||
|
|
||||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
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({
|
const AppSettingsSchema = Schema.Struct({
|
||||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||||
@@ -14,8 +18,16 @@ const AppSettingsSchema = Schema.Struct({
|
|||||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||||
Schema.withConstructorDefault(() => Option.some(false)),
|
Schema.withConstructorDefault(() => Option.some(false)),
|
||||||
),
|
),
|
||||||
|
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||||
|
Schema.withConstructorDefault(() => Option.some([])),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||||
|
export interface AppModelOption {
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
isCustom: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||||
|
|
||||||
@@ -23,6 +35,76 @@ let listeners: Array<() => void> = [];
|
|||||||
let cachedRawSettings: string | null | undefined;
|
let cachedRawSettings: string | null | undefined;
|
||||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
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 {
|
function emitChange(): void {
|
||||||
for (const listener of listeners) {
|
for (const listener of listeners) {
|
||||||
listener();
|
listener();
|
||||||
@@ -35,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||||
} catch {
|
} catch {
|
||||||
return DEFAULT_APP_SETTINGS;
|
return DEFAULT_APP_SETTINGS;
|
||||||
}
|
}
|
||||||
@@ -96,10 +178,12 @@ export function useAppSettings() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
const next = normalizeAppSettings(
|
||||||
...getAppSettingsSnapshot(),
|
Schema.decodeSync(AppSettingsSchema)({
|
||||||
...patch,
|
...getAppSettingsSnapshot(),
|
||||||
});
|
...patch,
|
||||||
|
}),
|
||||||
|
);
|
||||||
persistSettings(next);
|
persistSettings(next);
|
||||||
emitChange();
|
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 type { Components } from "react-markdown";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import rehypeHighlight from "rehype-highlight";
|
|
||||||
import remarkGfm from "remark-gfm";
|
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 { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||||
|
import { readNativeApi } from "../nativeApi";
|
||||||
import { preferredTerminalEditor } from "../terminal-links";
|
import { preferredTerminalEditor } from "../terminal-links";
|
||||||
|
|
||||||
interface ChatMarkdownProps {
|
interface ChatMarkdownProps {
|
||||||
text: string;
|
text: string;
|
||||||
cwd: string | undefined;
|
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>(
|
const markdownComponents = useMemo<Components>(
|
||||||
() => ({
|
() => ({
|
||||||
a({ node: _node, href, ...props }) {
|
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 (
|
return (
|
||||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||||
<ReactMarkdown
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
remarkPlugins={[remarkGfm]}
|
|
||||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
|
||||||
components={markdownComponents}
|
|
||||||
>
|
|
||||||
{text}
|
{text}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,11 +6,9 @@ import {
|
|||||||
type EditorId,
|
type EditorId,
|
||||||
type KeybindingCommand,
|
type KeybindingCommand,
|
||||||
type MessageId,
|
type MessageId,
|
||||||
MODEL_OPTIONS,
|
|
||||||
type ProjectId,
|
type ProjectId,
|
||||||
type ProjectEntry,
|
type ProjectEntry,
|
||||||
type ProjectScript,
|
type ProjectScript,
|
||||||
ModelSlug,
|
|
||||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||||
REASONING_OPTIONS,
|
REASONING_OPTIONS,
|
||||||
@@ -112,7 +110,7 @@ import { Toggle } from "./ui/toggle";
|
|||||||
import { SidebarTrigger } from "./ui/sidebar";
|
import { SidebarTrigger } from "./ui/sidebar";
|
||||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||||
import { readNativeApi } from "~/nativeApi";
|
import { readNativeApi } from "~/nativeApi";
|
||||||
import { useAppSettings } from "../appSettings";
|
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||||
import { clamp } from "effect/Number";
|
import { clamp } from "effect/Number";
|
||||||
|
|
||||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||||
@@ -129,14 +127,9 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
|||||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||||
const SEARCHABLE_MODEL_OPTIONS = MODEL_OPTIONS.map(({ slug, name }) => ({
|
|
||||||
slug,
|
|
||||||
name,
|
|
||||||
searchSlug: slug.toLowerCase(),
|
|
||||||
searchName: name.toLowerCase(),
|
|
||||||
}));
|
|
||||||
const SCRIPT_TERMINAL_COLS = 120;
|
const SCRIPT_TERMINAL_COLS = 120;
|
||||||
const SCRIPT_TERMINAL_ROWS = 30;
|
const SCRIPT_TERMINAL_ROWS = 30;
|
||||||
|
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||||
|
|
||||||
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
||||||
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
||||||
@@ -216,7 +209,7 @@ type ComposerCommandItem =
|
|||||||
| {
|
| {
|
||||||
id: string;
|
id: string;
|
||||||
type: "model";
|
type: "model";
|
||||||
model: ModelSlug;
|
model: string;
|
||||||
label: string;
|
label: string;
|
||||||
description: string;
|
description: string;
|
||||||
};
|
};
|
||||||
@@ -240,6 +233,12 @@ function readFileAsDataUrl(file: File): Promise<string> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function buildTemporaryWorktreeBranchName(): string {
|
||||||
|
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||||
|
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||||
|
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||||
pathValue: string;
|
pathValue: string;
|
||||||
kind: "file" | "directory";
|
kind: "file" | "directory";
|
||||||
@@ -438,6 +437,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const selectedModel = resolveModelSlug(
|
const selectedModel = resolveModelSlug(
|
||||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||||
);
|
);
|
||||||
|
const modelOptions = useMemo(
|
||||||
|
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||||
|
[selectedModel, settings.customCodexModels],
|
||||||
|
);
|
||||||
const phase = derivePhase(activeThread?.session ?? null);
|
const phase = derivePhase(activeThread?.session ?? null);
|
||||||
const isSendBusy = sendPhase !== "idle";
|
const isSendBusy = sendPhase !== "idle";
|
||||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||||
@@ -614,18 +617,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return SEARCHABLE_MODEL_OPTIONS.filter(({ searchSlug, searchName }) => {
|
return modelOptions
|
||||||
const query = composerTrigger.query.trim().toLowerCase();
|
.map(({ slug, name }) => ({
|
||||||
if (!query) return true;
|
slug,
|
||||||
return searchSlug.includes(query) || searchName.includes(query);
|
name,
|
||||||
}).map(({ slug, name }) => ({
|
searchSlug: slug.toLowerCase(),
|
||||||
id: `model:${slug}`,
|
searchName: name.toLowerCase(),
|
||||||
type: "model",
|
}))
|
||||||
model: slug,
|
.filter(({ searchSlug, searchName }) => {
|
||||||
label: name,
|
const query = composerTrigger.query.trim().toLowerCase();
|
||||||
description: slug,
|
if (!query) return true;
|
||||||
}));
|
return searchSlug.includes(query) || searchName.includes(query);
|
||||||
}, [composerTrigger, workspaceEntries]);
|
})
|
||||||
|
.map(({ slug, name }) => ({
|
||||||
|
id: `model:${slug}`,
|
||||||
|
type: "model" as const,
|
||||||
|
model: slug,
|
||||||
|
label: name,
|
||||||
|
description: slug,
|
||||||
|
}));
|
||||||
|
}, [composerTrigger, modelOptions, workspaceEntries]);
|
||||||
const composerMenuOpen = Boolean(composerTrigger);
|
const composerMenuOpen = Boolean(composerTrigger);
|
||||||
const activeComposerMenuItem = useMemo(
|
const activeComposerMenuItem = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -1474,6 +1485,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const composerImagesSnapshot = [...composerImages];
|
const composerImagesSnapshot = [...composerImages];
|
||||||
const messageIdForSend = newMessageId();
|
const messageIdForSend = newMessageId();
|
||||||
const messageCreatedAt = new Date().toISOString();
|
const messageCreatedAt = new Date().toISOString();
|
||||||
|
const turnAttachmentsPromise = Promise.all(
|
||||||
|
composerImagesSnapshot.map(async (image) => ({
|
||||||
|
type: "image" as const,
|
||||||
|
name: image.name,
|
||||||
|
mimeType: image.mimeType,
|
||||||
|
sizeBytes: image.sizeBytes,
|
||||||
|
dataUrl: await readFileAsDataUrl(image.file),
|
||||||
|
})),
|
||||||
|
);
|
||||||
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
||||||
type: "image" as const,
|
type: "image" as const,
|
||||||
id: image.id,
|
id: image.id,
|
||||||
@@ -1506,7 +1526,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
// On first message: lock in branch + create worktree if needed.
|
// On first message: lock in branch + create worktree if needed.
|
||||||
if (baseBranchForWorktree) {
|
if (baseBranchForWorktree) {
|
||||||
setSendPhase("preparing-worktree");
|
setSendPhase("preparing-worktree");
|
||||||
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
|
const newBranch = buildTemporaryWorktreeBranchName();
|
||||||
const result = await createWorktreeMutation.mutateAsync({
|
const result = await createWorktreeMutation.mutateAsync({
|
||||||
cwd: activeProject.cwd,
|
cwd: activeProject.cwd,
|
||||||
branch: baseBranchForWorktree,
|
branch: baseBranchForWorktree,
|
||||||
@@ -1554,25 +1574,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setSendPhase("sending-turn");
|
setSendPhase("sending-turn");
|
||||||
const turnAttachments = await Promise.all(
|
const turnAttachments = await turnAttachmentsPromise;
|
||||||
composerImagesSnapshot.map(
|
|
||||||
async (
|
|
||||||
image,
|
|
||||||
): Promise<{
|
|
||||||
type: "image";
|
|
||||||
name: string;
|
|
||||||
mimeType: string;
|
|
||||||
sizeBytes: number;
|
|
||||||
dataUrl: string;
|
|
||||||
}> => ({
|
|
||||||
type: "image",
|
|
||||||
name: image.name,
|
|
||||||
mimeType: image.mimeType,
|
|
||||||
sizeBytes: image.sizeBytes,
|
|
||||||
dataUrl: await readFileAsDataUrl(image.file),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
attemptedTurnStart = true;
|
attemptedTurnStart = true;
|
||||||
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
||||||
const sandboxMode =
|
const sandboxMode =
|
||||||
@@ -1660,7 +1662,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const onModelSelect = useCallback(
|
const onModelSelect = useCallback(
|
||||||
(model: ModelSlug) => {
|
(model: string) => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!activeThread) return;
|
if (!activeThread) return;
|
||||||
if (api) {
|
if (api) {
|
||||||
@@ -2012,7 +2014,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
|
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
|
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
|
||||||
{/* Model picker */}
|
{/* Model picker */}
|
||||||
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
|
<ModelPicker
|
||||||
|
model={selectedModel}
|
||||||
|
options={modelOptions}
|
||||||
|
onModelChange={onModelSelect}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Divider */}
|
{/* Divider */}
|
||||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||||
@@ -2759,7 +2765,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="min-w-0 px-1 py-0.5">
|
<div className="min-w-0 px-1 py-0.5">
|
||||||
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
<ChatMarkdown
|
||||||
|
text={messageText}
|
||||||
|
cwd={markdownCwd}
|
||||||
|
isStreaming={Boolean(row.message.streaming)}
|
||||||
|
/>
|
||||||
{(() => {
|
{(() => {
|
||||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||||
if (!turnSummary) return null;
|
if (!turnSummary) return null;
|
||||||
@@ -2912,12 +2922,13 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const ModelPicker = memo(function ModelPicker(props: {
|
const ModelPicker = memo(function ModelPicker(props: {
|
||||||
model: ModelSlug;
|
model: string;
|
||||||
onModelChange: (model: ModelSlug) => void;
|
options: ReadonlyArray<{ slug: string; name: string }>;
|
||||||
|
onModelChange: (model: string) => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<Select
|
<Select
|
||||||
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
|
items={props.options.map((option) => ({ label: option.name, value: option.slug }))}
|
||||||
value={props.model}
|
value={props.model}
|
||||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||||
>
|
>
|
||||||
@@ -2925,7 +2936,7 @@ const ModelPicker = memo(function ModelPicker(props: {
|
|||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectPopup alignItemWithTrigger={false}>
|
<SelectPopup alignItemWithTrigger={false}>
|
||||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
{props.options.map(({ slug, name }) => (
|
||||||
<SelectItem key={slug} value={slug}>
|
<SelectItem key={slug} value={slug}>
|
||||||
{name}
|
{name}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"
|
|||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||||
|
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||||
@@ -18,10 +19,47 @@ import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
|||||||
type DiffRenderMode = "stacked" | "split";
|
type DiffRenderMode = "stacked" | "split";
|
||||||
type DiffThemeType = "light" | "dark";
|
type DiffThemeType = "light" | "dark";
|
||||||
|
|
||||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
const DIFF_PANEL_UNSAFE_CSS = `
|
||||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
[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;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
type RenderablePatch =
|
type RenderablePatch =
|
||||||
| {
|
| {
|
||||||
kind: "files";
|
kind: "files";
|
||||||
@@ -425,7 +463,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-full min-w-0 flex-col bg-card",
|
"flex h-full min-w-0 flex-col bg-background",
|
||||||
mode === "inline"
|
mode === "inline"
|
||||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||||
: "w-full",
|
: "w-full",
|
||||||
@@ -449,7 +487,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
</div>
|
</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 && (
|
{checkpointDiffError && !renderablePatch && (
|
||||||
<div className="px-3">
|
<div className="px-3">
|
||||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||||
@@ -467,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
</div>
|
</div>
|
||||||
) : renderablePatch.kind === "files" ? (
|
) : renderablePatch.kind === "files" ? (
|
||||||
<Virtualizer
|
<Virtualizer
|
||||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
|
||||||
config={{
|
config={{
|
||||||
overscrollSize: 600,
|
overscrollSize: 600,
|
||||||
intersectionObserverMargin: 1200,
|
intersectionObserverMargin: 1200,
|
||||||
@@ -478,7 +519,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||||
return (
|
return (
|
||||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
<div
|
||||||
|
key={themedFileKey}
|
||||||
|
data-diff-file-path={filePath}
|
||||||
|
className="diff-render-file rounded-md"
|
||||||
|
>
|
||||||
<FileDiff
|
<FileDiff
|
||||||
fileDiff={fileDiff}
|
fileDiff={fileDiff}
|
||||||
options={{
|
options={{
|
||||||
@@ -486,6 +531,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
lineDiffType: "none",
|
lineDiffType: "none",
|
||||||
theme: resolveDiffThemeName(resolvedTheme),
|
theme: resolveDiffThemeName(resolvedTheme),
|
||||||
themeType: resolvedTheme as DiffThemeType,
|
themeType: resolvedTheme as DiffThemeType,
|
||||||
|
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,12 +2,9 @@ import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
|||||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||||
import { useEffect, useMemo, type ReactNode } from "react";
|
import { useEffect, useMemo, type ReactNode } from "react";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
|
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||||
|
|
||||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
|
||||||
}
|
|
||||||
|
|
||||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
|
||||||
const workerPool = useWorkerPool();
|
const workerPool = useWorkerPool();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
|||||||
hasUpstream: true,
|
hasUpstream: true,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
openPr: null,
|
pr: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -29,12 +29,13 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("resolveQuickAction opens the existing PR", () => {
|
it("resolveQuickAction opens the existing PR", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
openPr: {
|
pr: {
|
||||||
number: 10,
|
number: 10,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/10",
|
url: "https://example.com/pr/10",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -45,12 +46,13 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
openPr: {
|
pr: {
|
||||||
number: 11,
|
number: 11,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/11",
|
url: "https://example.com/pr/11",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -147,12 +149,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
aheadCount: 3,
|
aheadCount: 3,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/13",
|
url: "https://example.com/pr/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -164,12 +167,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
aheadCount: 2,
|
aheadCount: 2,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 12,
|
number: 12,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/12",
|
url: "https://example.com/pr/12",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
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", () => {
|
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||||
it("resolveQuickAction pushes and creates a 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, {
|
assert.deepInclude(quick, {
|
||||||
kind: "run_action",
|
kind: "run_action",
|
||||||
action: "commit_push_pr",
|
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", () => {
|
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, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
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", () => {
|
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||||
it("resolveQuickAction returns disabled no-action state", () => {
|
it("resolveQuickAction returns disabled no-action state", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
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, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -290,7 +294,7 @@ describe("when: branch is behind upstream", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables push and create PR", () => {
|
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, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -346,12 +350,13 @@ describe("when: working tree has local changes", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 16,
|
number: 16,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/16",
|
url: "https://example.com/pr/16",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -411,7 +416,7 @@ describe("when: on default branch without open PR", () => {
|
|||||||
|
|
||||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||||
false,
|
false,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -511,7 +516,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
|||||||
describe("when: branch has no upstream configured", () => {
|
describe("when: branch has no upstream configured", () => {
|
||||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
@@ -526,12 +531,13 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 14,
|
number: 14,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/14",
|
url: "https://example.com/pr/14",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -548,12 +554,13 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 1,
|
aheadCount: 1,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 15,
|
number: 15,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/15",
|
url: "https://example.com/pr/15",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -568,7 +575,7 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
|
|
||||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const canCommit = !isBusy && hasChanges;
|
const canCommit = !isBusy && hasChanges;
|
||||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const isDiverged = isAhead && isBehind;
|
const isDiverged = isAhead && isBehind;
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ function getMenuActionDisabledReason(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
|
|
||||||
@@ -219,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||||
if (!prUrl) {
|
if (!prUrl) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -236,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
data: threadToastData,
|
data: threadToastData,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||||
const runGitActionWithToast = useCallback(
|
const runGitActionWithToast = useCallback(
|
||||||
async ({
|
async ({
|
||||||
action,
|
action,
|
||||||
@@ -295,7 +295,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
stopProgressUpdates();
|
stopProgressUpdates();
|
||||||
const resultToast = summarizeGitResult(result);
|
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 shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||||
const shouldOfferOpenPrCta =
|
const shouldOfferOpenPrCta =
|
||||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||||
@@ -365,7 +367,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
[
|
[
|
||||||
gitStatusForActions?.branch,
|
gitStatusForActions?.branch,
|
||||||
gitStatusForActions?.hasWorkingTreeChanges,
|
gitStatusForActions?.hasWorkingTreeChanges,
|
||||||
gitStatusForActions?.openPr?.url,
|
gitStatusForActions?.pr,
|
||||||
isDefaultBranch,
|
isDefaultBranch,
|
||||||
maybeConfirmPushToDefaultBranch,
|
maybeConfirmPushToDefaultBranch,
|
||||||
runImmediateGitActionMutation,
|
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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
|
type GitStatusResult,
|
||||||
type ResolvedKeybindingsConfig,
|
type ResolvedKeybindingsConfig,
|
||||||
} from "@t3tools/contracts";
|
} 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 { useNavigate, useParams } from "@tanstack/react-router";
|
||||||
import { useAppSettings } from "../appSettings";
|
import { useAppSettings } from "../appSettings";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
@@ -16,7 +17,7 @@ import { useStore } from "../store";
|
|||||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||||
import { type Thread } from "../types";
|
import { type Thread } from "../types";
|
||||||
import { derivePendingApprovals } from "../session-logic";
|
import { derivePendingApprovals } from "../session-logic";
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
import { toastManager } from "./ui/toast";
|
import { toastManager } from "./ui/toast";
|
||||||
@@ -63,6 +64,13 @@ interface TerminalStatusIndicator {
|
|||||||
pulse: boolean;
|
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 {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurn?.completedAt) return false;
|
if (!thread.latestTurn?.completedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
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() {
|
function T3Wordmark() {
|
||||||
return (
|
return (
|
||||||
<svg
|
<svg
|
||||||
@@ -210,6 +240,58 @@ export default function Sidebar() {
|
|||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [state.threads]);
|
}, [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(
|
const handleNewThread = useCallback(
|
||||||
(
|
(
|
||||||
@@ -632,6 +714,7 @@ export default function Sidebar() {
|
|||||||
thread,
|
thread,
|
||||||
pendingApprovalByThreadId.get(thread.id) === true,
|
pendingApprovalByThreadId.get(thread.id) === true,
|
||||||
);
|
);
|
||||||
|
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||||
const terminalStatus = terminalStatusIndicator(thread);
|
const terminalStatus = terminalStatusIndicator(thread);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -677,6 +760,16 @@ export default function Sidebar() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
<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 && (
|
{terminalStatus && (
|
||||||
<span
|
<span
|
||||||
role="img"
|
role="img"
|
||||||
|
|||||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
|||||||
font-size: 0.875rem;
|
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 {
|
.chat-markdown table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
|||||||
padding: 0.35rem 0.45rem;
|
padding: 0.35rem 0.45rem;
|
||||||
text-align: left;
|
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_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||||
const FNV_PRIME_32 = 0x01000193;
|
const FNV_PRIME_32 = 0x01000193;
|
||||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
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;
|
let hash = seed >>> 0;
|
||||||
for (let index = 0; index < input.length; index += 1) {
|
for (let index = 0; index < input.length; index += 1) {
|
||||||
hash ^= input.charCodeAt(index);
|
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 { StoreProvider } from "./store";
|
||||||
|
|
||||||
import "@xterm/xterm/css/xterm.css";
|
import "@xterm/xterm/css/xterm.css";
|
||||||
import "highlight.js/styles/github-dark.css";
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
import { APP_DISPLAY_NAME } from "./branding";
|
import { APP_DISPLAY_NAME } from "./branding";
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { createFileRoute } from "@tanstack/react-router";
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useCallback, useState } from "react";
|
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 { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
@@ -52,9 +53,12 @@ function SettingsRouteView() {
|
|||||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||||
|
const [customModelInput, setCustomModelInput] = useState("");
|
||||||
|
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||||
|
|
||||||
const codexBinaryPath = settings.codexBinaryPath;
|
const codexBinaryPath = settings.codexBinaryPath;
|
||||||
const codexHomePath = settings.codexHomePath;
|
const codexHomePath = settings.codexHomePath;
|
||||||
|
const customCodexModels = settings.customCodexModels;
|
||||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||||
|
|
||||||
const openKeybindingsFile = useCallback(() => {
|
const openKeybindingsFile = useCallback(() => {
|
||||||
@@ -74,6 +78,42 @@ function SettingsRouteView() {
|
|||||||
});
|
});
|
||||||
}, [keybindingsConfigPath]);
|
}, [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 (
|
return (
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
<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">
|
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||||
@@ -193,6 +233,96 @@ function SettingsRouteView() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</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">
|
<section className="rounded-2xl border border-border bg-card p-5">
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||||
|
|||||||
@@ -229,6 +229,10 @@ function toAttachmentPreviewUrl(rawUrl: string): string {
|
|||||||
return rawUrl;
|
return rawUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||||
|
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||||
@@ -487,13 +491,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
messages: thread.messages.map((message) => {
|
messages: thread.messages.map((message) => {
|
||||||
const attachments = message.attachments?.map((attachment, index) => ({
|
const attachments = message.attachments?.map((attachment) => ({
|
||||||
type: "image" as const,
|
type: "image" as const,
|
||||||
id: `${message.id}:${index}`,
|
id: attachment.id,
|
||||||
name: attachment.name,
|
name: attachment.name,
|
||||||
mimeType: attachment.mimeType,
|
mimeType: attachment.mimeType,
|
||||||
sizeBytes: attachment.sizeBytes,
|
sizeBytes: attachment.sizeBytes,
|
||||||
previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
|
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||||
}));
|
}));
|
||||||
const normalizedMessage: ChatMessage = {
|
const normalizedMessage: ChatMessage = {
|
||||||
id: message.id,
|
id: message.id,
|
||||||
|
|||||||
@@ -88,16 +88,16 @@ describe("getOrphanedWorktreePathForThread", () => {
|
|||||||
describe("formatWorktreePathForDisplay", () => {
|
describe("formatWorktreePathForDisplay", () => {
|
||||||
it("shows only the last path segment for unix-like paths", () => {
|
it("shows only the last path segment for unix-like paths", () => {
|
||||||
const result = formatWorktreePathForDisplay(
|
const result = formatWorktreePathForDisplay(
|
||||||
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
|
"/Users/julius/.t3/worktrees/t3code-mvp/t3code-4e609bb8",
|
||||||
);
|
);
|
||||||
expect(result).toBe("codething-4e609bb8");
|
expect(result).toBe("t3code-4e609bb8");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes windows separators before selecting the final segment", () => {
|
it("normalizes windows separators before selecting the final segment", () => {
|
||||||
const result = formatWorktreePathForDisplay(
|
const result = formatWorktreePathForDisplay(
|
||||||
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
|
"C:\\Users\\julius\\.t3\\worktrees\\t3code-mvp\\t3code-4e609bb8",
|
||||||
);
|
);
|
||||||
expect(result).toBe("codething-4e609bb8");
|
expect(result).toBe("t3code-4e609bb8");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
||||||
|
|||||||
@@ -71,12 +71,10 @@
|
|||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"highlight.js": "^11.11.1",
|
|
||||||
"lucide-react": "^0.564.0",
|
"lucide-react": "^0.564.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
},
|
},
|
||||||
@@ -863,20 +861,14 @@
|
|||||||
|
|
||||||
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
"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-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-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=="],
|
"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=="],
|
"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=="],
|
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||||
|
|
||||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||||
@@ -983,8 +975,6 @@
|
|||||||
|
|
||||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
"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-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||||
|
|
||||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||||
@@ -1197,8 +1187,6 @@
|
|||||||
|
|
||||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
"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-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=="],
|
"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=="],
|
"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-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=="],
|
"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",
|
"opened_existing",
|
||||||
"skipped_not_requested",
|
"skipped_not_requested",
|
||||||
]);
|
]);
|
||||||
|
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||||
|
export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||||
|
|
||||||
export const GitBranch = Schema.Struct({
|
export const GitBranch = Schema.Struct({
|
||||||
name: TrimmedNonEmptyStringSchema,
|
name: TrimmedNonEmptyStringSchema,
|
||||||
@@ -91,6 +93,16 @@ export type GitInitInput = typeof GitInitInput.Type;
|
|||||||
|
|
||||||
// RPC Results
|
// 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({
|
export const GitStatusResult = Schema.Struct({
|
||||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||||
hasWorkingTreeChanges: Schema.Boolean,
|
hasWorkingTreeChanges: Schema.Boolean,
|
||||||
@@ -108,15 +120,7 @@ export const GitStatusResult = Schema.Struct({
|
|||||||
hasUpstream: Schema.Boolean,
|
hasUpstream: Schema.Boolean,
|
||||||
aheadCount: NonNegativeInt,
|
aheadCount: NonNegativeInt,
|
||||||
behindCount: NonNegativeInt,
|
behindCount: NonNegativeInt,
|
||||||
openPr: Schema.NullOr(
|
pr: Schema.NullOr(GitStatusPr),
|
||||||
Schema.Struct({
|
|
||||||
number: PositiveInt,
|
|
||||||
title: TrimmedNonEmptyStringSchema,
|
|
||||||
url: Schema.String,
|
|
||||||
baseBranch: TrimmedNonEmptyStringSchema,
|
|
||||||
headBranch: TrimmedNonEmptyStringSchema,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||||
|
|
||||||
|
|||||||
@@ -22,9 +22,14 @@ describe("normalizeModelSlug", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("resolveModelSlug", () => {
|
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(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", () => {
|
it("resolves only supported model options", () => {
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ export const MODEL_OPTIONS = [
|
|||||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||||
] as const;
|
] 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 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",
|
"5.3": "gpt-5.3-codex",
|
||||||
"gpt-5.3": "gpt-5.3-codex",
|
"gpt-5.3": "gpt-5.3-codex",
|
||||||
"5.3-spark": "gpt-5.3-codex-spark",
|
"5.3-spark": "gpt-5.3-codex-spark",
|
||||||
@@ -26,16 +27,12 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||||
const normalized = normalizeModelSlug(model);
|
const normalized = normalizeModelSlug(model);
|
||||||
if (!normalized) {
|
return normalized ?? DEFAULT_MODEL;
|
||||||
return DEFAULT_MODEL;
|
|
||||||
}
|
|
||||||
|
|
||||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||||
|
|||||||
@@ -60,12 +60,28 @@ export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
|||||||
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
||||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
||||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
|
export const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
|
||||||
|
export const CHAT_ATTACHMENT_ID_MAX_CHARS = 128;
|
||||||
|
|
||||||
// Correlation id is command id by design in this model.
|
// Correlation id is command id by design in this model.
|
||||||
export const CorrelationId = CommandId;
|
export const CorrelationId = CommandId;
|
||||||
export type CorrelationId = typeof CorrelationId.Type;
|
export type CorrelationId = typeof CorrelationId.Type;
|
||||||
|
|
||||||
|
export const ChatAttachmentId = TrimmedNonEmptyString.check(
|
||||||
|
Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),
|
||||||
|
Schema.isPattern(/^[a-z0-9_-]+$/i),
|
||||||
|
);
|
||||||
|
export type ChatAttachmentId = typeof ChatAttachmentId.Type;
|
||||||
|
|
||||||
export const ChatImageAttachment = Schema.Struct({
|
export const ChatImageAttachment = Schema.Struct({
|
||||||
|
type: Schema.Literal("image"),
|
||||||
|
id: ChatAttachmentId,
|
||||||
|
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||||
|
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
|
||||||
|
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
|
||||||
|
});
|
||||||
|
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
|
||||||
|
|
||||||
|
export const UploadChatImageAttachment = Schema.Struct({
|
||||||
type: Schema.Literal("image"),
|
type: Schema.Literal("image"),
|
||||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
|
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
|
||||||
@@ -74,10 +90,12 @@ export const ChatImageAttachment = Schema.Struct({
|
|||||||
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
|
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
|
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
|
||||||
|
|
||||||
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
|
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
|
||||||
export type ChatAttachment = typeof ChatAttachment.Type;
|
export type ChatAttachment = typeof ChatAttachment.Type;
|
||||||
|
export const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
|
||||||
|
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
|
||||||
|
|
||||||
export const ProjectScriptIcon = Schema.Literals([
|
export const ProjectScriptIcon = Schema.Literals([
|
||||||
"play",
|
"play",
|
||||||
@@ -307,6 +325,24 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
|||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const ClientThreadTurnStartCommand = Schema.Struct({
|
||||||
|
type: Schema.Literal("thread.turn.start"),
|
||||||
|
commandId: CommandId,
|
||||||
|
threadId: ThreadId,
|
||||||
|
message: Schema.Struct({
|
||||||
|
messageId: MessageId,
|
||||||
|
role: Schema.Literal("user"),
|
||||||
|
text: Schema.String,
|
||||||
|
attachments: Schema.Array(UploadChatAttachment),
|
||||||
|
}),
|
||||||
|
model: Schema.optional(TrimmedNonEmptyString),
|
||||||
|
effort: Schema.optional(TrimmedNonEmptyString),
|
||||||
|
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||||
|
approvalPolicy: ProviderApprovalPolicy,
|
||||||
|
sandboxMode: ProviderSandboxMode,
|
||||||
|
createdAt: IsoDateTime,
|
||||||
|
});
|
||||||
|
|
||||||
export const ThreadTurnInterruptCommand = Schema.Struct({
|
export const ThreadTurnInterruptCommand = Schema.Struct({
|
||||||
type: Schema.Literal("thread.turn.interrupt"),
|
type: Schema.Literal("thread.turn.interrupt"),
|
||||||
commandId: CommandId,
|
commandId: CommandId,
|
||||||
@@ -339,7 +375,7 @@ export const ThreadSessionStopCommand = Schema.Struct({
|
|||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ClientOrchestrationCommand = Schema.Union([
|
export const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||||
ProjectCreateCommand,
|
ProjectCreateCommand,
|
||||||
ProjectMetaUpdateCommand,
|
ProjectMetaUpdateCommand,
|
||||||
ProjectDeleteCommand,
|
ProjectDeleteCommand,
|
||||||
@@ -352,6 +388,22 @@ export const ClientOrchestrationCommand = Schema.Union([
|
|||||||
ThreadCheckpointRevertCommand,
|
ThreadCheckpointRevertCommand,
|
||||||
ThreadSessionStopCommand,
|
ThreadSessionStopCommand,
|
||||||
]);
|
]);
|
||||||
|
export type DispatchableClientOrchestrationCommand =
|
||||||
|
typeof DispatchableClientOrchestrationCommand.Type;
|
||||||
|
|
||||||
|
export const ClientOrchestrationCommand = Schema.Union([
|
||||||
|
ProjectCreateCommand,
|
||||||
|
ProjectMetaUpdateCommand,
|
||||||
|
ProjectDeleteCommand,
|
||||||
|
ThreadCreateCommand,
|
||||||
|
ThreadDeleteCommand,
|
||||||
|
ThreadMetaUpdateCommand,
|
||||||
|
ClientThreadTurnStartCommand,
|
||||||
|
ThreadTurnInterruptCommand,
|
||||||
|
ThreadApprovalRespondCommand,
|
||||||
|
ThreadCheckpointRevertCommand,
|
||||||
|
ThreadSessionStopCommand,
|
||||||
|
]);
|
||||||
export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
|
export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
|
||||||
|
|
||||||
export const ThreadSessionSetCommand = Schema.Struct({
|
export const ThreadSessionSetCommand = Schema.Struct({
|
||||||
@@ -422,7 +474,7 @@ export const InternalOrchestrationCommand = Schema.Union([
|
|||||||
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
|
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
|
||||||
|
|
||||||
export const OrchestrationCommand = Schema.Union([
|
export const OrchestrationCommand = Schema.Union([
|
||||||
ClientOrchestrationCommand,
|
DispatchableClientOrchestrationCommand,
|
||||||
InternalOrchestrationCommand,
|
InternalOrchestrationCommand,
|
||||||
]);
|
]);
|
||||||
export type OrchestrationCommand = typeof OrchestrationCommand.Type;
|
export type OrchestrationCommand = typeof OrchestrationCommand.Type;
|
||||||
|
|||||||
Reference in new issue
Block a user