Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54f8aef6a2 | ||
|
|
bb4551a739 | ||
|
|
c2a588fd02 | ||
|
|
249cf8c03b | ||
|
|
d48b42c017 | ||
|
|
fb45896588 | ||
|
|
b52518f85f | ||
|
|
3e99019af8 | ||
|
|
7d4b02689e | ||
|
|
9962f57ad0 | ||
|
|
8b538e2802 | ||
|
|
a6c57e169a | ||
|
|
6f92f0a668 | ||
|
|
35817601ff | ||
|
|
2b154db938 | ||
|
|
b9ff7aa5cd | ||
|
|
b5188e8cea | ||
|
|
992db16586 | ||
|
|
2aad749e24 | ||
|
|
aa267ebb05 | ||
|
|
1a33f25970 | ||
|
|
21c823ecdc | ||
|
|
80498f1709 |
No files matched your search
@@ -0,0 +1,264 @@
|
|||||||
|
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.
|
||||||
@@ -215,14 +215,13 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
Layer.provide(providerSessionDirectoryLayer),
|
Layer.provide(providerSessionDirectoryLayer),
|
||||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
ProjectionCheckpointRepositoryLive,
|
ProjectionCheckpointRepositoryLive,
|
||||||
ProjectionPendingApprovalRepositoryLive,
|
ProjectionPendingApprovalRepositoryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
|
|||||||
@@ -233,11 +233,12 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
const layer = CheckpointReactorLive.pipe(
|
const layer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(checkpointStoreLayer),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
@@ -437,7 +438,9 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
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?.checkpoints).toHaveLength(0);
|
expect(midThread?.checkpoints).toHaveLength(0);
|
||||||
|
|
||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,11 @@
|
|||||||
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
import Mime from "@effect/platform-node/Mime";
|
||||||
import { Effect, Layer, Option, Stream } from "effect";
|
import {
|
||||||
|
ApprovalRequestId,
|
||||||
|
type ChatAttachment,
|
||||||
|
type OrchestrationEvent,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||||
@@ -27,10 +33,16 @@ import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/
|
|||||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import {
|
import {
|
||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
|
import {
|
||||||
|
ATTACHMENTS_ROUTE_PREFIX,
|
||||||
|
IMAGE_EXTENSION_BY_MIME_TYPE,
|
||||||
|
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||||
|
} from "../../projectFaviconRoute.ts";
|
||||||
|
|
||||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||||
projects: "projection.projects",
|
projects: "projection.projects",
|
||||||
@@ -48,9 +60,122 @@ type ProjectorName =
|
|||||||
|
|
||||||
interface ProjectorDefinition {
|
interface ProjectorDefinition {
|
||||||
readonly name: ProjectorName;
|
readonly name: ProjectorName;
|
||||||
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
readonly apply: (
|
||||||
|
event: OrchestrationEvent,
|
||||||
|
attachmentSideEffects: AttachmentSideEffects,
|
||||||
|
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PendingAttachmentWrite {
|
||||||
|
readonly absolutePath: string;
|
||||||
|
readonly bytes: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AttachmentSideEffects {
|
||||||
|
readonly writes: Array<PendingAttachmentWrite>;
|
||||||
|
readonly deletedThreadIds: Set<string>;
|
||||||
|
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||||
|
const segment = encodeURIComponent(threadId);
|
||||||
|
if (
|
||||||
|
segment.length === 0 ||
|
||||||
|
segment === "." ||
|
||||||
|
segment === ".." ||
|
||||||
|
segment.includes("/") ||
|
||||||
|
segment.includes("\\") ||
|
||||||
|
segment.includes("\0")
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return segment;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBase64DataUrl(
|
||||||
|
dataUrl: string,
|
||||||
|
): { readonly mimeType: string; readonly base64: string } | null {
|
||||||
|
const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
const mimeType = match[1]?.trim().toLowerCase();
|
||||||
|
const base64 = match[2]?.replace(/\s+/g, "");
|
||||||
|
if (!mimeType || !base64) return null;
|
||||||
|
|
||||||
|
return { mimeType, base64 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferImageExtension(attachment: Extract<ChatAttachment, { type: "image" }>): string {
|
||||||
|
const normalizedMimeType = attachment.mimeType.toLowerCase();
|
||||||
|
if (normalizedMimeType.startsWith("image/")) {
|
||||||
|
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[normalizedMimeType];
|
||||||
|
if (fromMime) return fromMime;
|
||||||
|
}
|
||||||
|
const ext = Mime.getExtension(attachment.mimeType);
|
||||||
|
if (ext && SAFE_IMAGE_FILE_EXTENSIONS.has(ext)) return ext;
|
||||||
|
return ".bin";
|
||||||
|
}
|
||||||
|
|
||||||
|
const materializeAttachmentsForProjection = Effect.fn(function* (input: {
|
||||||
|
readonly threadId: string;
|
||||||
|
readonly messageId: string;
|
||||||
|
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||||
|
readonly stageFileWrite: (pendingWrite: PendingAttachmentWrite) => void;
|
||||||
|
}) {
|
||||||
|
if (input.attachments.length === 0) return [];
|
||||||
|
|
||||||
|
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||||
|
if (Option.isNone(serverConfig)) return input.attachments;
|
||||||
|
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const attachmentsRootDir = path.join(serverConfig.value.stateDir, "attachments");
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment materialization for unsafe thread id", {
|
||||||
|
threadId: input.threadId,
|
||||||
|
messageId: input.messageId,
|
||||||
|
});
|
||||||
|
return input.attachments;
|
||||||
|
}
|
||||||
|
const messageSegment = encodeURIComponent(input.messageId);
|
||||||
|
|
||||||
|
return yield* Effect.forEach(
|
||||||
|
input.attachments,
|
||||||
|
(attachment, index) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
if (attachment.type !== "image" || !attachment.dataUrl.startsWith("data:")) {
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||||
|
if (!parsed) {
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
if (!parsed.mimeType.startsWith("image/")) {
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = Buffer.from(parsed.base64, "base64");
|
||||||
|
if (bytes.byteLength === 0) return attachment;
|
||||||
|
|
||||||
|
const fileName = `${index}${inferImageExtension({
|
||||||
|
...attachment,
|
||||||
|
mimeType: parsed.mimeType,
|
||||||
|
})}`;
|
||||||
|
const uniqueFileName = `${messageSegment}-${fileName}`;
|
||||||
|
const relativePath = `${threadSegment}/${uniqueFileName}`;
|
||||||
|
const absolutePath = path.join(attachmentsRootDir, threadSegment, uniqueFileName);
|
||||||
|
input.stageFileWrite({ absolutePath, bytes });
|
||||||
|
|
||||||
|
return {
|
||||||
|
...attachment,
|
||||||
|
dataUrl: `${ATTACHMENTS_ROUTE_PREFIX}/${relativePath}`,
|
||||||
|
} satisfies ChatAttachment;
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||||
if (typeof payload !== "object" || payload === null) {
|
if (typeof payload !== "object" || payload === null) {
|
||||||
return null;
|
return null;
|
||||||
@@ -163,6 +288,138 @@ function retainProjectionActivitiesAfterRevert(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toAttachmentRelativePath(dataUrl: string): string | null {
|
||||||
|
const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
|
||||||
|
if (!dataUrl.startsWith(prefix)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const relativePath = dataUrl.slice(prefix.length).replace(/^[/\\]+/, "");
|
||||||
|
if (relativePath.length === 0 || relativePath.startsWith("..")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return relativePath.replace(/\\/g, "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectThreadAttachmentRelativePaths(
|
||||||
|
threadId: string,
|
||||||
|
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||||
|
): Set<string> {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
const threadPrefix = `${threadSegment}/`;
|
||||||
|
const relativePaths = new Set<string>();
|
||||||
|
for (const message of messages) {
|
||||||
|
for (const attachment of message.attachments ?? []) {
|
||||||
|
if (attachment.type !== "image") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
||||||
|
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
||||||
|
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return relativePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||||
|
readonly sideEffects: AttachmentSideEffects;
|
||||||
|
readonly fileSystem: FileSystem.FileSystem;
|
||||||
|
readonly path: Path.Path;
|
||||||
|
}) {
|
||||||
|
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||||
|
if (Option.isNone(serverConfig)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
||||||
|
|
||||||
|
yield* Effect.forEach(
|
||||||
|
input.sideEffects.deletedThreadIds,
|
||||||
|
(threadId) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||||
|
threadId,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||||
|
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* Effect.forEach(
|
||||||
|
input.sideEffects.prunedThreadRelativePaths.entries(),
|
||||||
|
([threadId, keptThreadRelativePaths]) => {
|
||||||
|
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
||||||
|
return Effect.void;
|
||||||
|
}
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||||
|
const entries = yield* input.fileSystem
|
||||||
|
.readDirectory(threadDir, { recursive: true })
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
|
yield* Effect.forEach(
|
||||||
|
entries,
|
||||||
|
(entry) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
||||||
|
const fileInfo = yield* input.fileSystem
|
||||||
|
.stat(absolutePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
||||||
|
yield* input.fileSystem.remove(absolutePath, { force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const writesByPath = new Map<string, Uint8Array>();
|
||||||
|
for (const pendingWrite of input.sideEffects.writes) {
|
||||||
|
// Last write wins for a path so updated attachment contents replace stale bytes.
|
||||||
|
writesByPath.set(pendingWrite.absolutePath, pendingWrite.bytes);
|
||||||
|
}
|
||||||
|
yield* Effect.forEach(
|
||||||
|
writesByPath.entries(),
|
||||||
|
([absolutePath, bytes]) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* input.fileSystem.makeDirectory(input.path.dirname(absolutePath), {
|
||||||
|
recursive: true,
|
||||||
|
});
|
||||||
|
yield* input.fileSystem.writeFile(absolutePath, bytes);
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
const eventStore = yield* OrchestrationEventStore;
|
const eventStore = yield* OrchestrationEventStore;
|
||||||
@@ -175,7 +432,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||||
|
|
||||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "project.created":
|
case "project.created":
|
||||||
@@ -233,7 +493,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.created":
|
case "thread.created":
|
||||||
@@ -272,6 +532,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "thread.deleted": {
|
case "thread.deleted": {
|
||||||
|
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
const existingRow = yield* projectionThreadRepository.getById({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
});
|
});
|
||||||
@@ -351,7 +612,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.message-sent": {
|
case "thread.message-sent": {
|
||||||
@@ -367,12 +631,24 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
: existingMessage && event.payload.text.length === 0
|
: existingMessage && event.payload.text.length === 0
|
||||||
? existingMessage.text
|
? existingMessage.text
|
||||||
: event.payload.text;
|
: event.payload.text;
|
||||||
|
const nextAttachments =
|
||||||
|
event.payload.attachments !== undefined
|
||||||
|
? yield* materializeAttachmentsForProjection({
|
||||||
|
threadId: event.payload.threadId,
|
||||||
|
messageId: event.payload.messageId,
|
||||||
|
attachments: event.payload.attachments,
|
||||||
|
stageFileWrite: (pendingWrite) => {
|
||||||
|
attachmentSideEffects.writes.push(pendingWrite);
|
||||||
|
},
|
||||||
|
}).pipe(Effect.provideService(Path.Path, path))
|
||||||
|
: existingMessage?.attachments;
|
||||||
yield* projectionThreadMessageRepository.upsert({
|
yield* projectionThreadMessageRepository.upsert({
|
||||||
messageId: event.payload.messageId,
|
messageId: event.payload.messageId,
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
turnId: event.payload.turnId,
|
turnId: event.payload.turnId,
|
||||||
role: event.payload.role,
|
role: event.payload.role,
|
||||||
text: nextText,
|
text: nextText,
|
||||||
|
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||||
isStreaming: event.payload.streaming,
|
isStreaming: event.payload.streaming,
|
||||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||||
updatedAt: event.payload.updatedAt,
|
updatedAt: event.payload.updatedAt,
|
||||||
@@ -406,6 +682,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
}).pipe(Effect.asVoid);
|
}).pipe(Effect.asVoid);
|
||||||
|
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||||
|
event.payload.threadId,
|
||||||
|
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,7 +694,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended":
|
case "thread.activity-appended":
|
||||||
@@ -462,7 +745,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
if (event.type !== "thread.session-set") {
|
if (event.type !== "thread.session-set") {
|
||||||
return;
|
return;
|
||||||
@@ -481,7 +767,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.turn-start-requested": {
|
case "thread.turn-start-requested": {
|
||||||
@@ -714,7 +1003,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
|
|
||||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||||
|
|
||||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended": {
|
case "thread.activity-appended": {
|
||||||
@@ -837,17 +1129,40 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
sql.withTransaction(
|
Effect.gen(function* () {
|
||||||
projector.apply(event).pipe(
|
const attachmentSideEffects: AttachmentSideEffects = {
|
||||||
Effect.flatMap(() =>
|
writes: [],
|
||||||
projectionStateRepository.upsert({
|
deletedThreadIds: new Set<string>(),
|
||||||
|
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||||
|
};
|
||||||
|
|
||||||
|
yield* sql.withTransaction(
|
||||||
|
projector.apply(event, attachmentSideEffects).pipe(
|
||||||
|
Effect.flatMap(() =>
|
||||||
|
projectionStateRepository.upsert({
|
||||||
|
projector: projector.name,
|
||||||
|
lastAppliedSequence: event.sequence,
|
||||||
|
updatedAt: event.occurredAt,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* runAttachmentSideEffects({
|
||||||
|
sideEffects: attachmentSideEffects,
|
||||||
|
fileSystem,
|
||||||
|
path,
|
||||||
|
}).pipe(
|
||||||
|
Effect.catch((cause) =>
|
||||||
|
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||||
projector: projector.name,
|
projector: projector.name,
|
||||||
lastAppliedSequence: event.sequence,
|
sequence: event.sequence,
|
||||||
updatedAt: event.occurredAt,
|
eventType: event.type,
|
||||||
|
cause,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
);
|
||||||
);
|
});
|
||||||
|
|
||||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||||
projectionStateRepository
|
projectionStateRepository
|
||||||
@@ -901,6 +1216,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
|||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
makeOrchestrationProjectionPipeline,
|
makeOrchestrationProjectionPipeline,
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
ChatAttachment,
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
MessageId,
|
MessageId,
|
||||||
OrchestrationCheckpointFile,
|
OrchestrationCheckpointFile,
|
||||||
@@ -42,12 +43,13 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
|||||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
|
||||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
isStreaming: Schema.Number,
|
isStreaming: Schema.Number,
|
||||||
|
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
payload: Schema.fromJsonString(Schema.Unknown),
|
payload: Schema.fromJsonString(Schema.Unknown),
|
||||||
@@ -171,6 +173,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json AS "attachments",
|
||||||
is_streaming AS "isStreaming",
|
is_streaming AS "isStreaming",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -376,6 +379,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
id: row.messageId,
|
id: row.messageId,
|
||||||
role: row.role,
|
role: row.role,
|
||||||
text: row.text,
|
text: row.text,
|
||||||
|
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||||
turnId: row.turnId,
|
turnId: row.turnId,
|
||||||
streaming: row.isStreaming === 1,
|
streaming: row.isStreaming === 1,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||||
|
import { assert, it } from "@effect/vitest";
|
||||||
|
import { Effect, Layer } from "effect";
|
||||||
|
|
||||||
|
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
|
||||||
|
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
|
||||||
|
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||||
|
|
||||||
|
const layer = it.layer(
|
||||||
|
ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||||
|
);
|
||||||
|
|
||||||
|
layer("ProjectionThreadMessageRepository", (it) => {
|
||||||
|
it.effect("preserves existing attachments when upsert omits attachments", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repository = yield* ProjectionThreadMessageRepository;
|
||||||
|
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
|
||||||
|
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
|
||||||
|
const createdAt = "2026-02-28T19:00:00.000Z";
|
||||||
|
const updatedAt = "2026-02-28T19:00:01.000Z";
|
||||||
|
const persistedAttachments = [
|
||||||
|
{
|
||||||
|
type: "image" as const,
|
||||||
|
name: "example.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "user",
|
||||||
|
text: "initial",
|
||||||
|
attachments: persistedAttachments,
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "user",
|
||||||
|
text: "updated",
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:00:02.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = yield* repository.listByThreadId({ threadId });
|
||||||
|
assert.equal(rows.length, 1);
|
||||||
|
assert.equal(rows[0]?.text, "updated");
|
||||||
|
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repository = yield* ProjectionThreadMessageRepository;
|
||||||
|
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
|
||||||
|
const messageId = MessageId.makeUnsafe("message-clear-attachments");
|
||||||
|
const createdAt = "2026-02-28T19:10:00.000Z";
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "assistant",
|
||||||
|
text: "with attachment",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
name: "example.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:10:01.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "assistant",
|
||||||
|
text: "cleared",
|
||||||
|
attachments: [],
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:10:02.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = yield* repository.listByThreadId({ threadId });
|
||||||
|
assert.equal(rows.length, 1);
|
||||||
|
assert.equal(rows[0]?.text, "cleared");
|
||||||
|
assert.deepEqual(rows[0]?.attachments, []);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||||
import { Effect, Layer, Schema, Struct } from "effect";
|
import { Effect, Layer, Schema, Struct } from "effect";
|
||||||
|
import { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { toPersistenceSqlError } from "../Errors.ts";
|
import { toPersistenceSqlError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
@@ -14,6 +15,7 @@ import {
|
|||||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
isStreaming: Schema.Number,
|
isStreaming: Schema.Number,
|
||||||
|
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -22,14 +24,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
|
|
||||||
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
||||||
Request: ProjectionThreadMessage,
|
Request: ProjectionThreadMessage,
|
||||||
execute: (row) =>
|
execute: (row) => {
|
||||||
sql`
|
const nextAttachmentsJson =
|
||||||
|
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||||
|
return sql`
|
||||||
INSERT INTO projection_thread_messages (
|
INSERT INTO projection_thread_messages (
|
||||||
message_id,
|
message_id,
|
||||||
thread_id,
|
thread_id,
|
||||||
turn_id,
|
turn_id,
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json,
|
||||||
is_streaming,
|
is_streaming,
|
||||||
created_at,
|
created_at,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -40,6 +45,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
${row.turnId},
|
${row.turnId},
|
||||||
${row.role},
|
${row.role},
|
||||||
${row.text},
|
${row.text},
|
||||||
|
COALESCE(
|
||||||
|
${nextAttachmentsJson},
|
||||||
|
(
|
||||||
|
SELECT attachments_json
|
||||||
|
FROM projection_thread_messages
|
||||||
|
WHERE message_id = ${row.messageId}
|
||||||
|
)
|
||||||
|
),
|
||||||
${row.isStreaming ? 1 : 0},
|
${row.isStreaming ? 1 : 0},
|
||||||
${row.createdAt},
|
${row.createdAt},
|
||||||
${row.updatedAt}
|
${row.updatedAt}
|
||||||
@@ -50,10 +63,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
turn_id = excluded.turn_id,
|
turn_id = excluded.turn_id,
|
||||||
role = excluded.role,
|
role = excluded.role,
|
||||||
text = excluded.text,
|
text = excluded.text,
|
||||||
|
attachments_json = COALESCE(
|
||||||
|
excluded.attachments_json,
|
||||||
|
projection_thread_messages.attachments_json
|
||||||
|
),
|
||||||
is_streaming = excluded.is_streaming,
|
is_streaming = excluded.is_streaming,
|
||||||
created_at = excluded.created_at,
|
created_at = excluded.created_at,
|
||||||
updated_at = excluded.updated_at
|
updated_at = excluded.updated_at
|
||||||
`,
|
`;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
||||||
@@ -67,6 +85,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json AS "attachments",
|
||||||
is_streaming AS "isStreaming",
|
is_streaming AS "isStreaming",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -97,8 +116,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
Effect.map((rows) =>
|
Effect.map((rows) =>
|
||||||
rows.map((row) => ({
|
rows.map((row) => ({
|
||||||
...row,
|
messageId: row.messageId,
|
||||||
|
threadId: row.threadId,
|
||||||
|
turnId: row.turnId,
|
||||||
|
role: row.role,
|
||||||
|
text: row.text,
|
||||||
isStreaming: row.isStreaming === 1,
|
isStreaming: row.isStreaming === 1,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
updatedAt: row.updatedAt,
|
||||||
|
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||||
})),
|
})),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
|||||||
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||||
|
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Migration loader with all migrations defined inline.
|
* Migration loader with all migrations defined inline.
|
||||||
@@ -36,6 +37,7 @@ const loader = Migrator.fromRecord({
|
|||||||
"4_ProviderSessionRuntime": Migration0004,
|
"4_ProviderSessionRuntime": Migration0004,
|
||||||
"5_Projections": Migration0005,
|
"5_Projections": Migration0005,
|
||||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||||
|
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
|
||||||
|
export default Effect.gen(function* () {
|
||||||
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|
||||||
|
yield* sql`
|
||||||
|
ALTER TABLE projection_thread_messages
|
||||||
|
ADD COLUMN attachments_json TEXT
|
||||||
|
`;
|
||||||
|
});
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
* @module ProjectionThreadMessageRepository
|
* @module ProjectionThreadMessageRepository
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
|
ChatAttachment,
|
||||||
OrchestrationMessageRole,
|
OrchestrationMessageRole,
|
||||||
MessageId,
|
MessageId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
@@ -24,6 +25,7 @@ export const ProjectionThreadMessage = Schema.Struct({
|
|||||||
turnId: Schema.NullOr(TurnId),
|
turnId: Schema.NullOr(TurnId),
|
||||||
role: OrchestrationMessageRole,
|
role: OrchestrationMessageRole,
|
||||||
text: Schema.String,
|
text: Schema.String,
|
||||||
|
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||||
isStreaming: Schema.Boolean,
|
isStreaming: Schema.Boolean,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
|
|||||||
@@ -2,6 +2,32 @@ 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",
|
||||||
|
|||||||
@@ -378,6 +378,7 @@ it.effect(
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project",
|
||||||
resumeThreadId: startedSession.threadId,
|
resumeThreadId: startedSession.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -465,6 +466,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project",
|
||||||
resumeThreadId: initial.threadId,
|
resumeThreadId: initial.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -475,6 +477,38 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const provider = yield* ProviderService;
|
||||||
|
|
||||||
|
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||||
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project-send-turn",
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* provider.stopAll();
|
||||||
|
routing.codex.startSession.mockClear();
|
||||||
|
routing.codex.sendTurn.mockClear();
|
||||||
|
|
||||||
|
yield* provider.sendTurn({
|
||||||
|
sessionId: initial.sessionId,
|
||||||
|
input: "resume",
|
||||||
|
attachments: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project-send-turn",
|
||||||
|
resumeThreadId: initial.threadId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("stops all sessions and clears adapter runtime", () =>
|
it.effect("stops all sessions and clears adapter runtime", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
|
|||||||
@@ -93,6 +93,18 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readPersistedCwd(
|
||||||
|
runtimePayload: ProviderSessionBinding["runtimePayload"],
|
||||||
|
): string | undefined {
|
||||||
|
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
|
||||||
|
if (typeof rawCwd !== "string") return undefined;
|
||||||
|
const trimmed = rawCwd.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const canonicalEventLogger =
|
const canonicalEventLogger =
|
||||||
@@ -266,8 +278,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||||
|
|
||||||
const resumed = yield* adapter.startSession({
|
const resumed = yield* adapter.startSession({
|
||||||
provider: input.binding.provider,
|
provider: input.binding.provider,
|
||||||
|
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
|||||||
return Layer.mergeAll(
|
return Layer.mergeAll(
|
||||||
runtimeRepositoryLayer,
|
runtimeRepositoryLayer,
|
||||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||||
|
NodeServices.layer,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,5 +224,5 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
|||||||
}).pipe(Effect.provide(directoryLayer));
|
}).pipe(Effect.provide(directoryLayer));
|
||||||
|
|
||||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
}).pipe(Effect.provide(NodeServices.layer)));
|
}));
|
||||||
});
|
});
|
||||||
@@ -61,16 +61,16 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||||
Layer.provideMerge(checkpointStoreLayer),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
);
|
);
|
||||||
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
checkpointDiffQueryLayer,
|
checkpointDiffQueryLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
|
|||||||
@@ -394,6 +394,21 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores trailing writes after terminal exit", async () => {
|
||||||
|
const { manager, ptyAdapter } = makeManager();
|
||||||
|
await manager.open(openInput());
|
||||||
|
const process = ptyAdapter.processes[0];
|
||||||
|
expect(process).toBeDefined();
|
||||||
|
if (!process) return;
|
||||||
|
|
||||||
|
process.emitExit({ exitCode: 0, signal: 0 });
|
||||||
|
|
||||||
|
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
|
||||||
|
expect(process.writes).toEqual([]);
|
||||||
|
|
||||||
|
manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
it("emits subprocess activity events when child-process state changes", async () => {
|
it("emits subprocess activity events when child-process state changes", async () => {
|
||||||
let hasRunningSubprocess = false;
|
let hasRunningSubprocess = false;
|
||||||
const { manager } = makeManager(5, {
|
const { manager } = makeManager(5, {
|
||||||
|
|||||||
@@ -438,6 +438,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
const input = decodeTerminalWriteInput(raw);
|
const input = decodeTerminalWriteInput(raw);
|
||||||
const session = this.requireSession(input.threadId, input.terminalId);
|
const session = this.requireSession(input.threadId, input.terminalId);
|
||||||
if (!session.process || session.status !== "running") {
|
if (!session.process || session.status !== "running") {
|
||||||
|
if (session.status === "exited") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import os from "node:os";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||||
import { createServer } from "./wsServer";
|
import { createServer } from "./wsServer";
|
||||||
import WebSocket from "ws";
|
import WebSocket from "ws";
|
||||||
@@ -40,13 +40,14 @@ import type {
|
|||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
||||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||||
import { SqlClient } from "effect/unstable/sql";
|
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||||
import { Open, type OpenShape } from "./open";
|
import { Open, type OpenShape } from "./open";
|
||||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||||
|
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||||
|
|
||||||
interface PendingMessages {
|
interface PendingMessages {
|
||||||
queue: unknown[];
|
queue: unknown[];
|
||||||
@@ -296,6 +297,36 @@ async function waitForPush(
|
|||||||
return take(maxMessages);
|
return take(maxMessages);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function requestPath(
|
||||||
|
port: number,
|
||||||
|
requestPath: string,
|
||||||
|
): Promise<{ statusCode: number; body: string }> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = Http.request(
|
||||||
|
{
|
||||||
|
hostname: "127.0.0.1",
|
||||||
|
port,
|
||||||
|
path: requestPath,
|
||||||
|
method: "GET",
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on("data", (chunk) => {
|
||||||
|
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||||
|
});
|
||||||
|
res.on("end", () => {
|
||||||
|
resolve({
|
||||||
|
statusCode: res.statusCode ?? 0,
|
||||||
|
body: Buffer.concat(chunks).toString("utf8"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
req.once("error", reject);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||||
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
||||||
for (const binding of bindings) {
|
for (const binding of bindings) {
|
||||||
@@ -324,13 +355,17 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
async function createTestServer(
|
async function createTestServer(
|
||||||
options: {
|
options: {
|
||||||
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
|
persistenceLayer?: Layer.Layer<
|
||||||
|
SqlClient.SqlClient,
|
||||||
|
SqlError.SqlError | MigrationError | PlatformError.PlatformError
|
||||||
|
>;
|
||||||
cwd?: string;
|
cwd?: string;
|
||||||
autoBootstrapProjectFromCwd?: boolean;
|
autoBootstrapProjectFromCwd?: boolean;
|
||||||
logWebSocketEvents?: boolean;
|
logWebSocketEvents?: boolean;
|
||||||
devUrl?: string;
|
devUrl?: string;
|
||||||
authToken?: string;
|
authToken?: string;
|
||||||
stateDir?: string;
|
stateDir?: string;
|
||||||
|
staticDir?: string;
|
||||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||||
open?: OpenShape;
|
open?: OpenShape;
|
||||||
gitManager?: GitManagerShape;
|
gitManager?: GitManagerShape;
|
||||||
@@ -354,7 +389,7 @@ describe("WebSocket Server", () => {
|
|||||||
cwd: options.cwd ?? "/test/project",
|
cwd: options.cwd ?? "/test/project",
|
||||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||||
stateDir,
|
stateDir,
|
||||||
staticDir: undefined,
|
staticDir: options.staticDir,
|
||||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||||
noBrowser: true,
|
noBrowser: true,
|
||||||
authToken: options.authToken,
|
authToken: options.authToken,
|
||||||
@@ -438,6 +473,80 @@ describe("WebSocket Server", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("serves persisted attachments from stateDir", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-attachments-");
|
||||||
|
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
|
||||||
|
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||||
|
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("content-type")).toContain("image/png");
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer());
|
||||||
|
expect(bytes).toEqual(Buffer.from("hello-attachment"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serves persisted attachments for URL-encoded paths", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||||
|
const attachmentPath = path.join(
|
||||||
|
stateDir,
|
||||||
|
"attachments",
|
||||||
|
"thread%20folder",
|
||||||
|
"message%20folder",
|
||||||
|
"file%20name.png",
|
||||||
|
);
|
||||||
|
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||||
|
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`,
|
||||||
|
);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("content-type")).toContain("image/png");
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer());
|
||||||
|
expect(bytes).toEqual(Buffer.from("hello-encoded-attachment"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serves static index for root path", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-static-root-");
|
||||||
|
const staticDir = makeTempDir("t3code-static-root-");
|
||||||
|
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/`);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(await response.text()).toContain("static-root");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects static path traversal attempts", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-static-traversal-");
|
||||||
|
const staticDir = makeTempDir("t3code-static-traversal-");
|
||||||
|
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await requestPath(port, "/..%2f..%2fetc/passwd");
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
expect(response.body).toBe("Invalid static file path");
|
||||||
|
});
|
||||||
|
|
||||||
it("bootstraps the cwd project on startup when enabled", async () => {
|
it("bootstraps the cwd project on startup when enabled", async () => {
|
||||||
server = await createTestServer({
|
server = await createTestServer({
|
||||||
cwd: "/test/bootstrap-workspace",
|
cwd: "/test/bootstrap-workspace",
|
||||||
@@ -509,9 +618,9 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
||||||
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||||
const persistenceLayer = makeSqlitePersistenceLive(
|
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
|
||||||
path.join(stateDir, "state.sqlite"),
|
Layer.provide(NodeServices.layer),
|
||||||
).pipe(Layer.provide(NodeServices.layer)) as unknown as Layer.Layer<SqlClient.SqlClient, never>;
|
);
|
||||||
const cwd = "/test/bootstrap-existing";
|
const cwd = "/test/bootstrap-existing";
|
||||||
|
|
||||||
server = await createTestServer({
|
server = await createTestServer({
|
||||||
|
|||||||
+168
-74
@@ -6,11 +6,10 @@
|
|||||||
*
|
*
|
||||||
* @module Server
|
* @module Server
|
||||||
*/
|
*/
|
||||||
import fs from "node:fs";
|
|
||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import path from "node:path";
|
|
||||||
import type { Duplex } from "node:stream";
|
import type { Duplex } from "node:stream";
|
||||||
|
|
||||||
|
import Mime from "@effect/platform-node/Mime";
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
ORCHESTRATION_WS_CHANNELS,
|
ORCHESTRATION_WS_CHANNELS,
|
||||||
@@ -25,7 +24,20 @@ import {
|
|||||||
WsResponse,
|
WsResponse,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||||
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
|
import {
|
||||||
|
Cause,
|
||||||
|
Effect,
|
||||||
|
Exit,
|
||||||
|
FileSystem,
|
||||||
|
Layer,
|
||||||
|
Path,
|
||||||
|
Ref,
|
||||||
|
Schema,
|
||||||
|
Scope,
|
||||||
|
ServiceMap,
|
||||||
|
Stream,
|
||||||
|
Struct,
|
||||||
|
} from "effect";
|
||||||
import { WebSocketServer, type WebSocket } from "ws";
|
import { WebSocketServer, type WebSocket } from "ws";
|
||||||
|
|
||||||
import { createLogger } from "./logger";
|
import { createLogger } from "./logger";
|
||||||
@@ -42,22 +54,7 @@ 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 { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
|
|
||||||
const MIME_TYPES: Record<string, string> = {
|
|
||||||
".html": "text/html; charset=utf-8",
|
|
||||||
".js": "application/javascript; charset=utf-8",
|
|
||||||
".css": "text/css; charset=utf-8",
|
|
||||||
".json": "application/json; charset=utf-8",
|
|
||||||
".png": "image/png",
|
|
||||||
".jpg": "image/jpeg",
|
|
||||||
".svg": "image/svg+xml",
|
|
||||||
".ico": "image/x-icon",
|
|
||||||
".woff": "font/woff",
|
|
||||||
".woff2": "font/woff2",
|
|
||||||
".ttf": "font/ttf",
|
|
||||||
".map": "application/json",
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerShape - Service API for server lifecycle control.
|
* ServerShape - Service API for server lifecycle control.
|
||||||
@@ -69,7 +66,7 @@ export interface ServerShape {
|
|||||||
readonly start: Effect.Effect<
|
readonly start: Effect.Effect<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
ServerLifecycleError,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -168,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
|
|||||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
ServerLifecycleError,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||||
> {
|
> {
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
const {
|
const {
|
||||||
@@ -187,6 +184,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
const terminalManager = yield* TerminalManager;
|
const terminalManager = yield* TerminalManager;
|
||||||
const keybindingsManager = yield* Keybindings;
|
const keybindingsManager = yield* Keybindings;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
||||||
Effect.catch((error) =>
|
Effect.catch((error) =>
|
||||||
@@ -233,62 +232,157 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
// HTTP server — serves static files or redirects to Vite dev server
|
// HTTP server — serves static files or redirects to Vite dev server
|
||||||
const httpServer = http.createServer((req, res) => {
|
const httpServer = http.createServer((req, res) => {
|
||||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
const respond = (
|
||||||
|
statusCode: number,
|
||||||
|
headers: Record<string, string>,
|
||||||
|
body?: string | Uint8Array,
|
||||||
|
) => {
|
||||||
|
res.writeHead(statusCode, headers);
|
||||||
|
res.end(body);
|
||||||
|
};
|
||||||
|
|
||||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
void Effect.runPromise(
|
||||||
return;
|
Effect.gen(function* () {
|
||||||
}
|
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||||
|
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||||
// In dev mode, redirect to Vite dev server
|
|
||||||
if (devUrl) {
|
|
||||||
res.writeHead(302, { Location: devUrl.href });
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serve static files from the web app build
|
|
||||||
if (!staticDir) {
|
|
||||||
res.writeHead(503, { "Content-Type": "text/plain" });
|
|
||||||
res.end("No static directory configured and no dev URL set.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let filePath = path.join(staticDir, url.pathname);
|
|
||||||
|
|
||||||
// SPA fallback: if no file extension and not found, serve index.html
|
|
||||||
const ext = path.extname(filePath);
|
|
||||||
if (!ext) {
|
|
||||||
filePath = path.join(filePath, "index.html");
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.stat(filePath, (err, stats) => {
|
|
||||||
if (err || !stats?.isFile()) {
|
|
||||||
// SPA fallback
|
|
||||||
const indexPath = path.join(staticDir, "index.html");
|
|
||||||
fs.readFile(indexPath, (readErr, data) => {
|
|
||||||
if (readErr) {
|
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Not Found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
||||||
res.end(data);
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileExt = path.extname(filePath);
|
|
||||||
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
|
|
||||||
|
|
||||||
fs.readFile(filePath, (readErr, data) => {
|
|
||||||
if (readErr) {
|
|
||||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Internal Server Error");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
res.writeHead(200, { "Content-Type": contentType });
|
|
||||||
res.end(data);
|
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||||
});
|
const attachmentsRoot = path.resolve(path.join(serverConfig.stateDir, "attachments"));
|
||||||
|
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||||
|
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||||
|
|
||||||
|
if (
|
||||||
|
normalizedRelativePath.length === 0 ||
|
||||||
|
normalizedRelativePath.startsWith("..") ||
|
||||||
|
normalizedRelativePath.includes("\0")
|
||||||
|
) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
});
|
||||||
|
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
if (!res.destroyed) {
|
||||||
|
res.write(chunk);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
).pipe(Effect.exit);
|
||||||
|
if (streamExit._tag === "Failure") {
|
||||||
|
if (!res.destroyed) {
|
||||||
|
res.destroy();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!res.writableEnded) {
|
||||||
|
res.end();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In dev mode, redirect to Vite dev server
|
||||||
|
if (devUrl) {
|
||||||
|
respond(302, { Location: devUrl.href });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve static files from the web app build
|
||||||
|
if (!staticDir) {
|
||||||
|
respond(
|
||||||
|
503,
|
||||||
|
{ "Content-Type": "text/plain" },
|
||||||
|
"No static directory configured and no dev URL set.",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const staticRoot = path.resolve(staticDir);
|
||||||
|
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
|
||||||
|
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||||
|
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||||
|
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||||
|
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||||
|
if (
|
||||||
|
staticRelativePath.length === 0 ||
|
||||||
|
hasRawLeadingParentSegment ||
|
||||||
|
hasPathTraversalSegment ||
|
||||||
|
staticRelativePath.includes("\0")
|
||||||
|
) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isWithinStaticRoot = (candidate: string) =>
|
||||||
|
candidate === staticRoot ||
|
||||||
|
candidate.startsWith(
|
||||||
|
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||||
|
if (!isWithinStaticRoot(filePath)) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = path.extname(filePath);
|
||||||
|
if (!ext) {
|
||||||
|
filePath = path.resolve(filePath, "index.html");
|
||||||
|
if (!isWithinStaticRoot(filePath)) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
const indexPath = path.resolve(staticRoot, "index.html");
|
||||||
|
const indexData = yield* fileSystem
|
||||||
|
.readFile(indexPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!indexData) {
|
||||||
|
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||||
|
const data = yield* fileSystem
|
||||||
|
.readFile(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!data) {
|
||||||
|
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
respond(200, { "Content-Type": contentType }, data);
|
||||||
|
}),
|
||||||
|
).catch(() => {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -74,6 +74,8 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
|||||||
import {
|
import {
|
||||||
BotIcon,
|
BotIcon,
|
||||||
ChevronDownIcon,
|
ChevronDownIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
CircleAlertIcon,
|
CircleAlertIcon,
|
||||||
FileIcon,
|
FileIcon,
|
||||||
FolderIcon,
|
FolderIcon,
|
||||||
@@ -111,6 +113,7 @@ 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 { useAppSettings } from "../appSettings";
|
||||||
|
import { clamp } from "effect/Number";
|
||||||
|
|
||||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||||
if (!duration) return formatTimestamp(createdAt);
|
if (!duration) return formatTimestamp(createdAt);
|
||||||
@@ -165,11 +168,36 @@ interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"
|
|||||||
file: File;
|
file: File;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ExpandedImagePreview {
|
interface ExpandedImageItem {
|
||||||
src: string;
|
src: string;
|
||||||
name: string;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ExpandedImagePreview {
|
||||||
|
images: ExpandedImageItem[];
|
||||||
|
index: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildExpandedImagePreview(
|
||||||
|
images: ReadonlyArray<{ id: string; name: string; previewUrl?: string }>,
|
||||||
|
selectedImageId: string,
|
||||||
|
): ExpandedImagePreview | null {
|
||||||
|
const previewableImages = images.flatMap((image) =>
|
||||||
|
image.previewUrl ? [{ id: image.id, src: image.previewUrl, name: image.name }] : [],
|
||||||
|
);
|
||||||
|
if (previewableImages.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
|
||||||
|
if (selectedIndex < 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
images: previewableImages.map((image) => ({ src: image.src, name: image.name })),
|
||||||
|
index: selectedIndex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
type ComposerCommandItem =
|
type ComposerCommandItem =
|
||||||
| {
|
| {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -1070,22 +1098,53 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
};
|
};
|
||||||
}, [revokePreviewUrls]);
|
}, [revokePreviewUrls]);
|
||||||
|
|
||||||
/**
|
const closeExpandedImage = useCallback(() => {
|
||||||
* Close expanded image on Escape key
|
setExpandedImage(null);
|
||||||
*/
|
}, []);
|
||||||
|
const navigateExpandedImage = useCallback((direction: -1 | 1) => {
|
||||||
|
setExpandedImage((existing) => {
|
||||||
|
if (!existing || existing.images.length <= 1) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
const nextIndex =
|
||||||
|
(existing.index + direction + existing.images.length) % existing.images.length;
|
||||||
|
if (nextIndex === existing.index) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
return { ...existing, index: nextIndex };
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!expandedImage) {
|
if (!expandedImage) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||||
if (event.key !== "Escape") return;
|
if (event.key === "Escape") {
|
||||||
setExpandedImage(null);
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
closeExpandedImage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (expandedImage.images.length <= 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key === "ArrowLeft") {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
navigateExpandedImage(-1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key !== "ArrowRight") return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
navigateExpandedImage(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener("keydown", onKeyDown);
|
window.addEventListener("keydown", onKeyDown);
|
||||||
return () => window.removeEventListener("keydown", onKeyDown);
|
return () => window.removeEventListener("keydown", onKeyDown);
|
||||||
}, [expandedImage]);
|
}, [closeExpandedImage, expandedImage, navigateExpandedImage]);
|
||||||
|
|
||||||
const activeWorktreePath = activeThread?.worktreePath;
|
const activeWorktreePath = activeThread?.worktreePath;
|
||||||
|
|
||||||
@@ -1722,9 +1781,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
[groupId]: !existing[groupId],
|
[groupId]: !existing[groupId],
|
||||||
}));
|
}));
|
||||||
}, []);
|
}, []);
|
||||||
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
|
const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
|
||||||
setExpandedImage(image);
|
setExpandedImage(preview);
|
||||||
}, []);
|
}, []);
|
||||||
|
const expandedImageItem = expandedImage ? expandedImage.images[expandedImage.index] : null;
|
||||||
const onOpenTurnDiff = useCallback(
|
const onOpenTurnDiff = useCallback(
|
||||||
(turnId: TurnId, filePath?: string) => {
|
(turnId: TurnId, filePath?: string) => {
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -1824,6 +1884,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
<MessagesTimeline
|
<MessagesTimeline
|
||||||
hasMessages={timelineMessages.length > 0}
|
hasMessages={timelineMessages.length > 0}
|
||||||
isWorking={isWorking}
|
isWorking={isWorking}
|
||||||
|
activeTurnInProgress={!latestTurnSettled}
|
||||||
|
activeTurnStartedAt={activeLatestTurn?.startedAt ?? null}
|
||||||
scrollContainerRef={messagesScrollRef}
|
scrollContainerRef={messagesScrollRef}
|
||||||
timelineEntries={timelineEntries}
|
timelineEntries={timelineEntries}
|
||||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||||
@@ -1885,9 +1947,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
src={image.previewUrl}
|
src={image.previewUrl}
|
||||||
alt={image.name}
|
alt={image.name}
|
||||||
className="h-full w-full cursor-zoom-in object-cover"
|
className="h-full w-full cursor-zoom-in object-cover"
|
||||||
onClick={() =>
|
onClick={() => {
|
||||||
setExpandedImage({ src: image.previewUrl, name: image.name })
|
const preview = buildExpandedImagePreview(composerImages, image.id);
|
||||||
}
|
if (!preview) return;
|
||||||
|
setExpandedImage(preview);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||||
@@ -2111,14 +2175,29 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
|
|
||||||
{expandedImage && (
|
{expandedImage && expandedImageItem && (
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-label="Expanded image preview"
|
aria-label="Expanded image preview"
|
||||||
onClick={() => setExpandedImage(null)}
|
onClick={closeExpandedImage}
|
||||||
>
|
>
|
||||||
|
{expandedImage.images.length > 1 && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute left-2 top-1/2 z-10 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:left-6"
|
||||||
|
aria-label="Previous image"
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
navigateExpandedImage(-1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ChevronLeftIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<div
|
<div
|
||||||
className="relative isolate max-h-[92vh] max-w-[92vw]"
|
className="relative isolate max-h-[92vh] max-w-[92vw]"
|
||||||
onClick={(event) => event.stopPropagation()}
|
onClick={(event) => event.stopPropagation()}
|
||||||
@@ -2128,21 +2207,39 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
size="icon-xs"
|
size="icon-xs"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="absolute right-2 top-2"
|
className="absolute right-2 top-2"
|
||||||
onClick={() => setExpandedImage(null)}
|
onClick={closeExpandedImage}
|
||||||
aria-label="Close image preview"
|
aria-label="Close image preview"
|
||||||
>
|
>
|
||||||
<XIcon />
|
<XIcon />
|
||||||
</Button>
|
</Button>
|
||||||
<img
|
<img
|
||||||
src={expandedImage.src}
|
src={expandedImageItem.src}
|
||||||
alt={expandedImage.name}
|
alt={expandedImageItem.name}
|
||||||
className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
|
className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
/>
|
/>
|
||||||
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
|
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
|
||||||
{expandedImage.name}
|
{expandedImageItem.name}
|
||||||
|
{expandedImage.images.length > 1
|
||||||
|
? ` (${expandedImage.index + 1}/${expandedImage.images.length})`
|
||||||
|
: ""}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
{expandedImage.images.length > 1 && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute right-2 top-1/2 z-10 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:right-6"
|
||||||
|
aria-label="Next image"
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
navigateExpandedImage(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ChevronRightIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -2336,13 +2433,7 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
|
|||||||
}, [text]);
|
}, [text]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Button
|
<Button type="button" size="xs" variant="outline" onClick={handleCopy} title="Copy message">
|
||||||
type="button"
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
onClick={handleCopy}
|
|
||||||
title="Copy message"
|
|
||||||
>
|
|
||||||
{copied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
{copied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
@@ -2351,6 +2442,8 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
|
|||||||
interface MessagesTimelineProps {
|
interface MessagesTimelineProps {
|
||||||
hasMessages: boolean;
|
hasMessages: boolean;
|
||||||
isWorking: boolean;
|
isWorking: boolean;
|
||||||
|
activeTurnInProgress: boolean;
|
||||||
|
activeTurnStartedAt: string | null;
|
||||||
scrollContainerRef: React.RefObject<HTMLDivElement | null>;
|
scrollContainerRef: React.RefObject<HTMLDivElement | null>;
|
||||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||||
completionDividerBeforeEntryId: string | null;
|
completionDividerBeforeEntryId: string | null;
|
||||||
@@ -2363,7 +2456,7 @@ interface MessagesTimelineProps {
|
|||||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||||
onRevertUserMessage: (messageId: MessageId) => void;
|
onRevertUserMessage: (messageId: MessageId) => void;
|
||||||
isRevertingCheckpoint: boolean;
|
isRevertingCheckpoint: boolean;
|
||||||
onImageExpand: (image: ExpandedImagePreview) => void;
|
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||||
markdownCwd: string | undefined;
|
markdownCwd: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2374,19 +2467,23 @@ type TimelineRow =
|
|||||||
| {
|
| {
|
||||||
kind: "work";
|
kind: "work";
|
||||||
id: string;
|
id: string;
|
||||||
|
createdAt: string;
|
||||||
groupedEntries: TimelineWorkEntry[];
|
groupedEntries: TimelineWorkEntry[];
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
kind: "message";
|
kind: "message";
|
||||||
id: string;
|
id: string;
|
||||||
|
createdAt: string;
|
||||||
message: TimelineMessage;
|
message: TimelineMessage;
|
||||||
showCompletionDivider: boolean;
|
showCompletionDivider: boolean;
|
||||||
}
|
}
|
||||||
| { kind: "working"; id: string };
|
| { kind: "working"; id: string; createdAt: string | null };
|
||||||
|
|
||||||
const MessagesTimeline = memo(function MessagesTimeline({
|
const MessagesTimeline = memo(function MessagesTimeline({
|
||||||
hasMessages,
|
hasMessages,
|
||||||
isWorking,
|
isWorking,
|
||||||
|
activeTurnInProgress,
|
||||||
|
activeTurnStartedAt,
|
||||||
scrollContainerRef,
|
scrollContainerRef,
|
||||||
timelineEntries,
|
timelineEntries,
|
||||||
completionDividerBeforeEntryId,
|
completionDividerBeforeEntryId,
|
||||||
@@ -2423,6 +2520,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
nextRows.push({
|
nextRows.push({
|
||||||
kind: "work",
|
kind: "work",
|
||||||
id: timelineEntry.id,
|
id: timelineEntry.id,
|
||||||
|
createdAt: timelineEntry.createdAt,
|
||||||
groupedEntries,
|
groupedEntries,
|
||||||
});
|
});
|
||||||
index = cursor - 1;
|
index = cursor - 1;
|
||||||
@@ -2432,6 +2530,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
nextRows.push({
|
nextRows.push({
|
||||||
kind: "message",
|
kind: "message",
|
||||||
id: timelineEntry.id,
|
id: timelineEntry.id,
|
||||||
|
createdAt: timelineEntry.createdAt,
|
||||||
message: timelineEntry.message,
|
message: timelineEntry.message,
|
||||||
showCompletionDivider:
|
showCompletionDivider:
|
||||||
timelineEntry.message.role === "assistant" &&
|
timelineEntry.message.role === "assistant" &&
|
||||||
@@ -2440,14 +2539,62 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isWorking) {
|
if (isWorking) {
|
||||||
nextRows.push({ kind: "working", id: "working-indicator-row" });
|
nextRows.push({
|
||||||
|
kind: "working",
|
||||||
|
id: "working-indicator-row",
|
||||||
|
createdAt: activeTurnStartedAt,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return nextRows;
|
return nextRows;
|
||||||
}, [timelineEntries, completionDividerBeforeEntryId, isWorking]);
|
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
|
||||||
|
|
||||||
|
const firstUnvirtualizedRowIndex = useMemo(() => {
|
||||||
|
if (!activeTurnInProgress) return rows.length;
|
||||||
|
|
||||||
|
const turnStartedAtMs =
|
||||||
|
typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
|
||||||
|
let firstCurrentTurnRowIndex = -1;
|
||||||
|
if (!Number.isNaN(turnStartedAtMs)) {
|
||||||
|
firstCurrentTurnRowIndex = rows.findIndex((row) => {
|
||||||
|
if (row.kind === "working") return true;
|
||||||
|
if (!row.createdAt) return false;
|
||||||
|
const rowCreatedAtMs = Date.parse(row.createdAt);
|
||||||
|
return !Number.isNaN(rowCreatedAtMs) && rowCreatedAtMs >= turnStartedAtMs;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstCurrentTurnRowIndex < 0) {
|
||||||
|
firstCurrentTurnRowIndex = rows.findIndex(
|
||||||
|
(row) => row.kind === "message" && row.message.streaming,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstCurrentTurnRowIndex < 0) {
|
||||||
|
return rows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
|
||||||
|
const previousRow = rows[index];
|
||||||
|
if (!previousRow || previousRow.kind !== "message") continue;
|
||||||
|
if (previousRow.message.role === "user") {
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return firstCurrentTurnRowIndex;
|
||||||
|
}, [activeTurnInProgress, activeTurnStartedAt, rows]);
|
||||||
|
|
||||||
|
const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
|
||||||
|
minimum: 0,
|
||||||
|
maximum: rows.length,
|
||||||
|
});
|
||||||
|
|
||||||
const rowVirtualizer = useVirtualizer({
|
const rowVirtualizer = useVirtualizer({
|
||||||
count: rows.length,
|
count: virtualizedRowCount,
|
||||||
getScrollElement: () => scrollContainerRef.current,
|
getScrollElement: () => scrollContainerRef.current,
|
||||||
estimateSize: (index: number) => {
|
estimateSize: (index: number) => {
|
||||||
const row = rows[index];
|
const row = rows[index];
|
||||||
@@ -2461,6 +2608,268 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||||
|
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||||
|
|
||||||
|
const renderRowContent = (row: TimelineRow) => (
|
||||||
|
<div className="pb-4">
|
||||||
|
{row.kind === "work" &&
|
||||||
|
(() => {
|
||||||
|
const groupId = row.id;
|
||||||
|
const groupedEntries = row.groupedEntries;
|
||||||
|
const isExpanded = expandedWorkGroups[groupId] ?? false;
|
||||||
|
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||||
|
const visibleEntries =
|
||||||
|
hasOverflow && !isExpanded
|
||||||
|
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
||||||
|
: groupedEntries;
|
||||||
|
const hiddenCount = groupedEntries.length - visibleEntries.length;
|
||||||
|
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
|
||||||
|
const groupLabel = onlyToolEntries
|
||||||
|
? groupedEntries.length === 1
|
||||||
|
? "Tool call"
|
||||||
|
: `Tool calls (${groupedEntries.length})`
|
||||||
|
: groupedEntries.length === 1
|
||||||
|
? "Work event"
|
||||||
|
: `Work log (${groupedEntries.length})`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
|
||||||
|
<div className="mb-1.5 flex items-center justify-between gap-3">
|
||||||
|
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||||
|
{groupLabel}
|
||||||
|
</p>
|
||||||
|
{hasOverflow && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||||
|
onClick={() => onToggleWorkGroup(groupId)}
|
||||||
|
>
|
||||||
|
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{visibleEntries.map((workEntry) => (
|
||||||
|
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
|
||||||
|
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||||
|
<p
|
||||||
|
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
||||||
|
>
|
||||||
|
{workEntry.detail ? (
|
||||||
|
<>
|
||||||
|
{workEntry.label}
|
||||||
|
<span
|
||||||
|
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||||
|
title={workEntry.detail}
|
||||||
|
>
|
||||||
|
{workEntry.detail}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
workEntry.label
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{row.kind === "message" &&
|
||||||
|
row.message.role === "user" &&
|
||||||
|
(() => {
|
||||||
|
const userImages = row.message.attachments ?? [];
|
||||||
|
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
||||||
|
return (
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||||
|
{userImages.length > 0 && (
|
||||||
|
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||||
|
{userImages.map(
|
||||||
|
(image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||||
|
<div
|
||||||
|
key={image.id}
|
||||||
|
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||||
|
>
|
||||||
|
{image.previewUrl ? (
|
||||||
|
<img
|
||||||
|
src={image.previewUrl}
|
||||||
|
alt={image.name}
|
||||||
|
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
|
||||||
|
onClick={() => {
|
||||||
|
const preview = buildExpandedImagePreview(userImages, image.id);
|
||||||
|
if (!preview) return;
|
||||||
|
onImageExpand(preview);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||||
|
{image.name}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{row.message.text && (
|
||||||
|
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||||
|
{row.message.text}
|
||||||
|
</pre>
|
||||||
|
)}
|
||||||
|
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||||
|
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||||
|
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||||
|
{canRevertAgentWork && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="xs"
|
||||||
|
variant="outline"
|
||||||
|
disabled={isRevertingCheckpoint || isWorking}
|
||||||
|
onClick={() => onRevertUserMessage(row.message.id)}
|
||||||
|
title="Revert to this message"
|
||||||
|
>
|
||||||
|
<Undo2Icon className="size-3" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-right text-[10px] text-muted-foreground/30">
|
||||||
|
{formatTimestamp(row.message.createdAt)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{row.kind === "message" &&
|
||||||
|
row.message.role === "assistant" &&
|
||||||
|
(() => {
|
||||||
|
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{row.showCompletionDivider && (
|
||||||
|
<div className="my-3 flex items-center gap-3">
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||||
|
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||||
|
</span>
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 px-1 py-0.5">
|
||||||
|
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
||||||
|
{(() => {
|
||||||
|
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||||
|
if (!turnSummary) return null;
|
||||||
|
const checkpointFiles = turnSummary.files;
|
||||||
|
if (checkpointFiles.length === 0) return null;
|
||||||
|
const summaryStat = checkpointFiles.reduce(
|
||||||
|
(acc, file) => {
|
||||||
|
if (
|
||||||
|
typeof file.additions !== "number" ||
|
||||||
|
typeof file.deletions !== "number"
|
||||||
|
) {
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
additions: acc.additions + file.additions,
|
||||||
|
deletions: acc.deletions + file.deletions,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ additions: 0, deletions: 0 },
|
||||||
|
);
|
||||||
|
const changedFileCountLabel = String(checkpointFiles.length);
|
||||||
|
return (
|
||||||
|
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||||
|
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||||
|
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||||
|
<span>Changed files ({changedFileCountLabel})</span>
|
||||||
|
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||||
|
<>
|
||||||
|
<span className="mx-1">•</span>
|
||||||
|
<span className="text-success">+{summaryStat.additions}</span>
|
||||||
|
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||||
|
<span className="text-destructive">-{summaryStat.deletions}</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="xs"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
View diff
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{checkpointFiles.map((file) => (
|
||||||
|
<button
|
||||||
|
key={`${turnSummary.turnId}:${file.path}`}
|
||||||
|
type="button"
|
||||||
|
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
||||||
|
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
||||||
|
>
|
||||||
|
{(() => {
|
||||||
|
const stat =
|
||||||
|
typeof file.additions === "number" &&
|
||||||
|
typeof file.deletions === "number"
|
||||||
|
? {
|
||||||
|
additions: file.additions,
|
||||||
|
deletions: file.deletions,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
if (!stat) {
|
||||||
|
return file.path;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<span>{file.path}</span>
|
||||||
|
<span className="ml-1 text-muted-foreground/70">(</span>
|
||||||
|
<span className="text-success">+{stat.additions}</span>
|
||||||
|
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||||
|
<span className="text-destructive">-{stat.deletions}</span>
|
||||||
|
<span className="text-muted-foreground/70">)</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||||
|
{formatMessageMeta(
|
||||||
|
row.message.createdAt,
|
||||||
|
row.message.streaming
|
||||||
|
? formatElapsed(row.message.createdAt, nowIso)
|
||||||
|
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{row.kind === "working" && (
|
||||||
|
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||||
|
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||||
|
<div className="flex items-center pt-1">
|
||||||
|
<span className="inline-flex items-center gap-[3px]">
|
||||||
|
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||||
|
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||||
|
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
if (!hasMessages && !isWorking) {
|
if (!hasMessages && !isWorking) {
|
||||||
return (
|
return (
|
||||||
@@ -2473,291 +2882,31 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden">
|
||||||
className="relative mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
|
{virtualizedRowCount > 0 && (
|
||||||
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}
|
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
||||||
>
|
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
const row = rows[virtualRow.index];
|
||||||
const row = rows[virtualRow.index];
|
if (!row) return null;
|
||||||
if (!row) return null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={row.id}
|
key={`virtual-row:${row.id}`}
|
||||||
data-index={virtualRow.index}
|
data-index={virtualRow.index}
|
||||||
ref={rowVirtualizer.measureElement}
|
ref={rowVirtualizer.measureElement}
|
||||||
className="absolute left-0 top-0 w-full"
|
className="absolute left-0 top-0 w-full"
|
||||||
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
||||||
>
|
>
|
||||||
<div className="pb-4">
|
{renderRowContent(row)}
|
||||||
{row.kind === "work" &&
|
</div>
|
||||||
(() => {
|
);
|
||||||
const groupId = row.id;
|
})}
|
||||||
const groupedEntries = row.groupedEntries;
|
</div>
|
||||||
const isExpanded = expandedWorkGroups[groupId] ?? false;
|
)}
|
||||||
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
|
||||||
const visibleEntries =
|
|
||||||
hasOverflow && !isExpanded
|
|
||||||
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
|
||||||
: groupedEntries;
|
|
||||||
const hiddenCount = groupedEntries.length - visibleEntries.length;
|
|
||||||
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
|
|
||||||
const groupLabel = onlyToolEntries
|
|
||||||
? groupedEntries.length === 1
|
|
||||||
? "Tool call"
|
|
||||||
: `Tool calls (${groupedEntries.length})`
|
|
||||||
: groupedEntries.length === 1
|
|
||||||
? "Work event"
|
|
||||||
: `Work log (${groupedEntries.length})`;
|
|
||||||
|
|
||||||
return (
|
{nonVirtualizedRows.map((row) => (
|
||||||
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
|
<div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
|
||||||
<div className="mb-1.5 flex items-center justify-between gap-3">
|
))}
|
||||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
|
||||||
{groupLabel}
|
|
||||||
</p>
|
|
||||||
{hasOverflow && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
|
|
||||||
onClick={() => onToggleWorkGroup(groupId)}
|
|
||||||
>
|
|
||||||
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1">
|
|
||||||
{visibleEntries.map((workEntry) => (
|
|
||||||
<div
|
|
||||||
key={`work-row:${workEntry.id}`}
|
|
||||||
className="flex items-start gap-2 py-0.5"
|
|
||||||
>
|
|
||||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
|
||||||
<p
|
|
||||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
|
||||||
>
|
|
||||||
{workEntry.detail ? (
|
|
||||||
<>
|
|
||||||
{workEntry.label}
|
|
||||||
<span
|
|
||||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
|
||||||
title={workEntry.detail}
|
|
||||||
>
|
|
||||||
{workEntry.detail}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
workEntry.label
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
|
|
||||||
{row.kind === "message" &&
|
|
||||||
row.message.role === "user" &&
|
|
||||||
(() => {
|
|
||||||
const userImages = row.message.attachments ?? [];
|
|
||||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
|
||||||
return (
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
|
||||||
{userImages.length > 0 && (
|
|
||||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
|
||||||
{userImages.map(
|
|
||||||
(image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
|
||||||
<div
|
|
||||||
key={image.id}
|
|
||||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
|
||||||
>
|
|
||||||
{image.previewUrl ? (
|
|
||||||
<img
|
|
||||||
src={image.previewUrl}
|
|
||||||
alt={image.name}
|
|
||||||
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
|
|
||||||
onClick={() =>
|
|
||||||
onImageExpand({ src: image.previewUrl!, name: image.name })
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
|
||||||
{image.name}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{row.message.text && (
|
|
||||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
|
||||||
{row.message.text}
|
|
||||||
</pre>
|
|
||||||
)}
|
|
||||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
|
||||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
|
||||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
|
||||||
{canRevertAgentWork && (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
disabled={isRevertingCheckpoint || isWorking}
|
|
||||||
onClick={() => onRevertUserMessage(row.message.id)}
|
|
||||||
title="Revert to this message"
|
|
||||||
>
|
|
||||||
<Undo2Icon className="size-3" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-right text-[10px] text-muted-foreground/30">
|
|
||||||
{formatTimestamp(row.message.createdAt)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
|
|
||||||
{row.kind === "message" &&
|
|
||||||
row.message.role === "assistant" &&
|
|
||||||
(() => {
|
|
||||||
const messageText =
|
|
||||||
row.message.text || (row.message.streaming ? "" : "(empty response)");
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{row.showCompletionDivider && (
|
|
||||||
<div className="my-3 flex items-center gap-3">
|
|
||||||
<span className="h-px flex-1 bg-border" />
|
|
||||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
|
||||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
|
||||||
</span>
|
|
||||||
<span className="h-px flex-1 bg-border" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="min-w-0 px-1 py-0.5">
|
|
||||||
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
|
||||||
{(() => {
|
|
||||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(
|
|
||||||
row.message.id,
|
|
||||||
);
|
|
||||||
if (!turnSummary) return null;
|
|
||||||
const checkpointFiles = turnSummary.files;
|
|
||||||
if (checkpointFiles.length === 0) return null;
|
|
||||||
const summaryStat = checkpointFiles.reduce(
|
|
||||||
(acc, file) => {
|
|
||||||
if (
|
|
||||||
typeof file.additions !== "number" ||
|
|
||||||
typeof file.deletions !== "number"
|
|
||||||
) {
|
|
||||||
return acc;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
additions: acc.additions + file.additions,
|
|
||||||
deletions: acc.deletions + file.deletions,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{ additions: 0, deletions: 0 },
|
|
||||||
);
|
|
||||||
const changedFileCountLabel = String(checkpointFiles.length);
|
|
||||||
return (
|
|
||||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
|
||||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
|
||||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
|
||||||
<span>Changed files ({changedFileCountLabel})</span>
|
|
||||||
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
|
||||||
<>
|
|
||||||
<span className="mx-1">•</span>
|
|
||||||
<span className="text-success">+{summaryStat.additions}</span>
|
|
||||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
|
||||||
<span className="text-destructive">
|
|
||||||
-{summaryStat.deletions}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() =>
|
|
||||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
View diff
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{checkpointFiles.map((file) => (
|
|
||||||
<button
|
|
||||||
key={`${turnSummary.turnId}:${file.path}`}
|
|
||||||
type="button"
|
|
||||||
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
|
||||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
|
||||||
>
|
|
||||||
{(() => {
|
|
||||||
const stat =
|
|
||||||
typeof file.additions === "number" &&
|
|
||||||
typeof file.deletions === "number"
|
|
||||||
? {
|
|
||||||
additions: file.additions,
|
|
||||||
deletions: file.deletions,
|
|
||||||
}
|
|
||||||
: null;
|
|
||||||
if (!stat) {
|
|
||||||
return file.path;
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<span>{file.path}</span>
|
|
||||||
<span className="ml-1 text-muted-foreground/70">(</span>
|
|
||||||
<span className="text-success">+{stat.additions}</span>
|
|
||||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
|
||||||
<span className="text-destructive">
|
|
||||||
-{stat.deletions}
|
|
||||||
</span>
|
|
||||||
<span className="text-muted-foreground/70">)</span>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
|
||||||
{formatMessageMeta(
|
|
||||||
row.message.createdAt,
|
|
||||||
row.message.streaming
|
|
||||||
? formatElapsed(row.message.createdAt, nowIso)
|
|
||||||
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
|
|
||||||
{row.kind === "working" && (
|
|
||||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
|
||||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
|
||||||
<div className="flex items-center pt-1">
|
|
||||||
<span className="inline-flex items-center gap-[3px]">
|
|
||||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
|
||||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
|
||||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ interface TerminalViewportProps {
|
|||||||
terminalId: string;
|
terminalId: string;
|
||||||
cwd: string;
|
cwd: string;
|
||||||
runtimeEnv?: Record<string, string>;
|
runtimeEnv?: Record<string, string>;
|
||||||
|
onSessionExited: () => void;
|
||||||
focusRequestId: number;
|
focusRequestId: number;
|
||||||
autoFocus: boolean;
|
autoFocus: boolean;
|
||||||
resizeEpoch: number;
|
resizeEpoch: number;
|
||||||
@@ -123,6 +124,7 @@ function TerminalViewport({
|
|||||||
terminalId,
|
terminalId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
runtimeEnv,
|
||||||
|
onSessionExited,
|
||||||
focusRequestId,
|
focusRequestId,
|
||||||
autoFocus,
|
autoFocus,
|
||||||
resizeEpoch,
|
resizeEpoch,
|
||||||
@@ -131,6 +133,12 @@ function TerminalViewport({
|
|||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const terminalRef = useRef<Terminal | null>(null);
|
const terminalRef = useRef<Terminal | null>(null);
|
||||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||||
|
const onSessionExitedRef = useRef(onSessionExited);
|
||||||
|
const hasHandledExitRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onSessionExitedRef.current = onSessionExited;
|
||||||
|
}, [onSessionExited]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const mount = containerRef.current;
|
const mount = containerRef.current;
|
||||||
@@ -306,6 +314,7 @@ function TerminalViewport({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "started" || event.type === "restarted") {
|
if (event.type === "started" || event.type === "restarted") {
|
||||||
|
hasHandledExitRef.current = false;
|
||||||
activeTerminal.write("\u001bc");
|
activeTerminal.write("\u001bc");
|
||||||
if (event.snapshot.history.length > 0) {
|
if (event.snapshot.history.length > 0) {
|
||||||
activeTerminal.write(event.snapshot.history);
|
activeTerminal.write(event.snapshot.history);
|
||||||
@@ -335,6 +344,16 @@ function TerminalViewport({
|
|||||||
activeTerminal,
|
activeTerminal,
|
||||||
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
||||||
);
|
);
|
||||||
|
if (hasHandledExitRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hasHandledExitRef.current = true;
|
||||||
|
window.setTimeout(() => {
|
||||||
|
if (!hasHandledExitRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSessionExitedRef.current();
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -783,6 +802,7 @@ export default function ThreadTerminalDrawer({
|
|||||||
terminalId={terminalId}
|
terminalId={terminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||||
|
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
@@ -800,6 +820,7 @@ export default function ThreadTerminalDrawer({
|
|||||||
terminalId={resolvedActiveTerminalId}
|
terminalId={resolvedActiveTerminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||||
|
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus
|
autoFocus
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
|
|||||||
+38
-1
@@ -192,6 +192,43 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
|||||||
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveWsHttpOrigin(): string {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||||
|
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||||
|
const wsCandidate =
|
||||||
|
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||||
|
? bridgeWsUrl
|
||||||
|
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||||
|
? envWsUrl
|
||||||
|
: null;
|
||||||
|
if (!wsCandidate) {
|
||||||
|
return window.location.origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const wsUrl = new URL(wsCandidate);
|
||||||
|
const protocol =
|
||||||
|
wsUrl.protocol === "wss:"
|
||||||
|
? "https:"
|
||||||
|
: wsUrl.protocol === "ws:"
|
||||||
|
? "http:"
|
||||||
|
: wsUrl.protocol;
|
||||||
|
return `${protocol}//${wsUrl.host}`;
|
||||||
|
} catch {
|
||||||
|
return window.location.origin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||||
|
if (rawUrl.startsWith("/")) {
|
||||||
|
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||||
|
}
|
||||||
|
return rawUrl;
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
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);
|
||||||
@@ -456,7 +493,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
name: attachment.name,
|
name: attachment.name,
|
||||||
mimeType: attachment.mimeType,
|
mimeType: attachment.mimeType,
|
||||||
sizeBytes: attachment.sizeBytes,
|
sizeBytes: attachment.sizeBytes,
|
||||||
previewUrl: attachment.dataUrl,
|
previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
|
||||||
}));
|
}));
|
||||||
const normalizedMessage: ChatMessage = {
|
const normalizedMessage: ChatMessage = {
|
||||||
id: message.id,
|
id: message.id,
|
||||||
|
|||||||
Reference in new issue
Block a user