Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a478a24002 | ||
|
|
0a5308042f | ||
|
|
dd1ab44137 | ||
|
|
ae27e0b57f |
No files matched your search
@@ -215,13 +215,14 @@ 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,
|
||||||
CheckpointStoreLive,
|
checkpointStoreLayer,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
|
|||||||
@@ -393,7 +393,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
pr: null,
|
openPr: null,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -297,7 +297,7 @@ function makeManager(input?: {
|
|||||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||||
|
|
||||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -324,56 +324,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-open-pr");
|
expect(status.branch).toBe("feature/status-open-pr");
|
||||||
expect(status.pr).toEqual({
|
expect(status.openPr).toEqual({
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/status-open-pr",
|
headBranch: "feature/status-open-pr",
|
||||||
state: "open",
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager({
|
|
||||||
ghScenario: {
|
|
||||||
prListSequence: [
|
|
||||||
JSON.stringify([
|
|
||||||
{
|
|
||||||
number: 22,
|
|
||||||
title: "Merged PR",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
|
||||||
baseRefName: "main",
|
|
||||||
headRefName: "feature/status-merged-pr",
|
|
||||||
state: "MERGED",
|
|
||||||
mergedAt: "2026-01-30T10:00:00Z",
|
|
||||||
updatedAt: "2026-01-30T10:00:00Z",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
|
||||||
expect(status.branch).toBe("feature/status-merged-pr");
|
|
||||||
expect(status.pr).toEqual({
|
|
||||||
number: 22,
|
|
||||||
title: "Merged PR",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/status-merged-pr",
|
|
||||||
state: "merged",
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -393,7 +354,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-no-gh");
|
expect(status.branch).toBe("feature/status-no-gh");
|
||||||
expect(status.pr).toBeNull();
|
expect(status.openPr).toBeNull();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -16,62 +16,6 @@ interface OpenPrInfo {
|
|||||||
headRefName: string;
|
headRefName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PullRequestInfo extends OpenPrInfo {
|
|
||||||
state: "open" | "closed" | "merged";
|
|
||||||
updatedAt: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
|
||||||
if (!Array.isArray(raw)) return [];
|
|
||||||
|
|
||||||
const parsed: PullRequestInfo[] = [];
|
|
||||||
for (const entry of raw) {
|
|
||||||
if (!entry || typeof entry !== "object") continue;
|
|
||||||
const record = entry as Record<string, unknown>;
|
|
||||||
const number = record.number;
|
|
||||||
const title = record.title;
|
|
||||||
const url = record.url;
|
|
||||||
const baseRefName = record.baseRefName;
|
|
||||||
const headRefName = record.headRefName;
|
|
||||||
const state = record.state;
|
|
||||||
const mergedAt = record.mergedAt;
|
|
||||||
const updatedAt = record.updatedAt;
|
|
||||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
typeof title !== "string" ||
|
|
||||||
typeof url !== "string" ||
|
|
||||||
typeof baseRefName !== "string" ||
|
|
||||||
typeof headRefName !== "string"
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let normalizedState: "open" | "closed" | "merged";
|
|
||||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
|
||||||
normalizedState = "merged";
|
|
||||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
|
||||||
normalizedState = "open";
|
|
||||||
} else if (state === "CLOSED") {
|
|
||||||
normalizedState = "closed";
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed.push({
|
|
||||||
number,
|
|
||||||
title,
|
|
||||||
url,
|
|
||||||
baseRefName,
|
|
||||||
headRefName,
|
|
||||||
state: normalizedState,
|
|
||||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||||
return new GitManagerError({
|
return new GitManagerError({
|
||||||
operation,
|
operation,
|
||||||
@@ -135,13 +79,12 @@ function extractBranchFromRef(ref: string): string {
|
|||||||
return normalized.slice(firstSlash + 1).trim();
|
return normalized.slice(firstSlash + 1).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toStatusPr(pr: PullRequestInfo): {
|
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
url: string;
|
||||||
baseBranch: string;
|
baseBranch: string;
|
||||||
headBranch: string;
|
headBranch: string;
|
||||||
state: "open" | "closed" | "merged";
|
|
||||||
} {
|
} {
|
||||||
return {
|
return {
|
||||||
number: pr.number,
|
number: pr.number,
|
||||||
@@ -149,7 +92,6 @@ function toStatusPr(pr: PullRequestInfo): {
|
|||||||
url: pr.url,
|
url: pr.url,
|
||||||
baseBranch: pr.baseRefName,
|
baseBranch: pr.baseRefName,
|
||||||
headBranch: pr.headRefName,
|
headBranch: pr.headRefName,
|
||||||
state: pr.state,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,51 +123,10 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
url: first.url,
|
url: first.url,
|
||||||
baseRefName: first.baseRefName,
|
baseRefName: first.baseRefName,
|
||||||
headRefName: first.headRefName,
|
headRefName: first.headRefName,
|
||||||
state: "open",
|
} satisfies OpenPrInfo;
|
||||||
updatedAt: null,
|
|
||||||
} satisfies PullRequestInfo;
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const findLatestPr = (cwd: string, branch: string) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const stdout = yield* gitHubCli
|
|
||||||
.execute({
|
|
||||||
cwd,
|
|
||||||
args: [
|
|
||||||
"pr",
|
|
||||||
"list",
|
|
||||||
"--head",
|
|
||||||
branch,
|
|
||||||
"--state",
|
|
||||||
"all",
|
|
||||||
"--limit",
|
|
||||||
"20",
|
|
||||||
"--json",
|
|
||||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
|
||||||
],
|
|
||||||
})
|
|
||||||
.pipe(Effect.map((result) => result.stdout));
|
|
||||||
|
|
||||||
const raw = stdout.trim();
|
|
||||||
if (raw.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsedJson = yield* Effect.try({
|
|
||||||
try: () => JSON.parse(raw) as unknown,
|
|
||||||
catch: (cause) =>
|
|
||||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
|
||||||
});
|
|
||||||
|
|
||||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
|
||||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
|
||||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
|
||||||
return right - left;
|
|
||||||
});
|
|
||||||
return parsed[0] ?? null;
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||||
@@ -357,10 +258,10 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||||
const details = yield* gitCore.statusDetails(input.cwd);
|
const details = yield* gitCore.statusDetails(input.cwd);
|
||||||
|
|
||||||
const pr =
|
const openPr =
|
||||||
details.branch !== null
|
details.branch && details.hasUpstream
|
||||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||||
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
Effect.catch(() => Effect.succeed(null)),
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
@@ -372,7 +273,7 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
pr,
|
openPr,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import type {
|
|||||||
|
|
||||||
import type { GitCommandError } from "../Errors.ts";
|
import type { GitCommandError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||||
upstreamRef: string | null;
|
upstreamRef: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -233,12 +233,11 @@ 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(CheckpointStoreLive),
|
Layer.provideMerge(checkpointStoreLayer),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
@@ -438,9 +437,7 @@ 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(
|
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
(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,11 +1,5 @@
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
||||||
import {
|
import { Effect, Layer, Option, Stream } from "effect";
|
||||||
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";
|
||||||
@@ -33,16 +27,10 @@ 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",
|
||||||
@@ -60,122 +48,9 @@ type ProjectorName =
|
|||||||
|
|
||||||
interface ProjectorDefinition {
|
interface ProjectorDefinition {
|
||||||
readonly name: ProjectorName;
|
readonly name: ProjectorName;
|
||||||
readonly apply: (
|
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||||
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;
|
||||||
@@ -288,138 +163,6 @@ function retainProjectionActivitiesAfterRevert(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toAttachmentRelativePath(dataUrl: string): string | null {
|
|
||||||
const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
|
|
||||||
if (!dataUrl.startsWith(prefix)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const relativePath = dataUrl.slice(prefix.length).replace(/^[/\\]+/, "");
|
|
||||||
if (relativePath.length === 0 || relativePath.startsWith("..")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return relativePath.replace(/\\/g, "/");
|
|
||||||
}
|
|
||||||
|
|
||||||
function collectThreadAttachmentRelativePaths(
|
|
||||||
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;
|
||||||
@@ -432,10 +175,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
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":
|
||||||
@@ -493,7 +233,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.created":
|
case "thread.created":
|
||||||
@@ -532,7 +272,6 @@ 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,
|
||||||
});
|
});
|
||||||
@@ -612,10 +351,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
event,
|
|
||||||
attachmentSideEffects,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.message-sent": {
|
case "thread.message-sent": {
|
||||||
@@ -631,24 +367,12 @@ 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,
|
||||||
@@ -682,10 +406,6 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -694,10 +414,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
event,
|
|
||||||
_attachmentSideEffects,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended":
|
case "thread.activity-appended":
|
||||||
@@ -745,10 +462,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
event,
|
|
||||||
_attachmentSideEffects,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
if (event.type !== "thread.session-set") {
|
if (event.type !== "thread.session-set") {
|
||||||
return;
|
return;
|
||||||
@@ -767,10 +481,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
event,
|
|
||||||
_attachmentSideEffects,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.turn-start-requested": {
|
case "thread.turn-start-requested": {
|
||||||
@@ -1003,10 +714,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
|
|
||||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||||
|
|
||||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||||
event,
|
|
||||||
_attachmentSideEffects,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended": {
|
case "thread.activity-appended": {
|
||||||
@@ -1129,40 +837,17 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
Effect.gen(function* () {
|
sql.withTransaction(
|
||||||
const attachmentSideEffects: AttachmentSideEffects = {
|
projector.apply(event).pipe(
|
||||||
writes: [],
|
Effect.flatMap(() =>
|
||||||
deletedThreadIds: new Set<string>(),
|
projectionStateRepository.upsert({
|
||||||
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,
|
||||||
sequence: event.sequence,
|
lastAppliedSequence: event.sequence,
|
||||||
eventType: event.type,
|
updatedAt: event.occurredAt,
|
||||||
cause,
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
),
|
||||||
});
|
);
|
||||||
|
|
||||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||||
projectionStateRepository
|
projectionStateRepository
|
||||||
@@ -1216,7 +901,6 @@ 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,5 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
ChatAttachment,
|
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
MessageId,
|
MessageId,
|
||||||
OrchestrationCheckpointFile,
|
OrchestrationCheckpointFile,
|
||||||
@@ -43,13 +42,12 @@ 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),
|
||||||
@@ -173,7 +171,6 @@ 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"
|
||||||
@@ -379,7 +376,6 @@ 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,
|
||||||
|
|||||||
@@ -1,106 +0,0 @@
|
|||||||
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,7 +1,6 @@
|
|||||||
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 {
|
||||||
@@ -15,7 +14,6 @@ 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))),
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -24,17 +22,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
|
|
||||||
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
||||||
Request: ProjectionThreadMessage,
|
Request: ProjectionThreadMessage,
|
||||||
execute: (row) => {
|
execute: (row) =>
|
||||||
const nextAttachmentsJson =
|
sql`
|
||||||
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
|
||||||
@@ -45,14 +40,6 @@ 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}
|
||||||
@@ -63,15 +50,10 @@ 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({
|
||||||
@@ -85,7 +67,6 @@ 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"
|
||||||
@@ -116,15 +97,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
Effect.map((rows) =>
|
Effect.map((rows) =>
|
||||||
rows.map((row) => ({
|
rows.map((row) => ({
|
||||||
messageId: row.messageId,
|
...row,
|
||||||
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,7 +18,6 @@ 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.
|
||||||
@@ -37,7 +36,6 @@ 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,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
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,7 +7,6 @@
|
|||||||
* @module ProjectionThreadMessageRepository
|
* @module ProjectionThreadMessageRepository
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
ChatAttachment,
|
|
||||||
OrchestrationMessageRole,
|
OrchestrationMessageRole,
|
||||||
MessageId,
|
MessageId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
@@ -25,7 +24,6 @@ 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,32 +2,6 @@ import fs from "node:fs";
|
|||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
|
||||||
|
|
||||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
|
||||||
"image/png": ".png",
|
|
||||||
"image/jpeg": ".jpg",
|
|
||||||
"image/jpg": ".jpg",
|
|
||||||
"image/gif": ".gif",
|
|
||||||
"image/webp": ".webp",
|
|
||||||
"image/svg+xml": ".svg",
|
|
||||||
"image/bmp": ".bmp",
|
|
||||||
"image/tiff": ".tiff",
|
|
||||||
"image/heic": ".heic",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
|
||||||
".jpg",
|
|
||||||
".jpeg",
|
|
||||||
".png",
|
|
||||||
".gif",
|
|
||||||
".webp",
|
|
||||||
".bmp",
|
|
||||||
".tiff",
|
|
||||||
".svg",
|
|
||||||
".ico",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||||
".png": "image/png",
|
".png": "image/png",
|
||||||
".jpg": "image/jpeg",
|
".jpg": "image/jpeg",
|
||||||
|
|||||||
@@ -378,7 +378,6 @@ it.effect(
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
cwd: "/tmp/project",
|
|
||||||
resumeThreadId: startedSession.threadId,
|
resumeThreadId: startedSession.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -466,7 +465,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
cwd: "/tmp/project",
|
|
||||||
resumeThreadId: initial.threadId,
|
resumeThreadId: initial.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -477,38 +475,6 @@ 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,18 +93,6 @@ 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 =
|
||||||
@@ -278,11 +266,8 @@ 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,7 +26,6 @@ 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,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -224,5 +223,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(CheckpointStoreLive),
|
Layer.provideMerge(checkpointStoreLayer),
|
||||||
);
|
);
|
||||||
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
CheckpointStoreLive,
|
checkpointStoreLayer,
|
||||||
checkpointDiffQueryLayer,
|
checkpointDiffQueryLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
|
|||||||
@@ -394,21 +394,6 @@ 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,9 +438,6 @@ 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, PlatformError, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, 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,14 +40,13 @@ 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, SqlError } from "effect/unstable/sql";
|
import { SqlClient } 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[];
|
||||||
@@ -297,36 +296,6 @@ 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) {
|
||||||
@@ -355,17 +324,13 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
async function createTestServer(
|
async function createTestServer(
|
||||||
options: {
|
options: {
|
||||||
persistenceLayer?: Layer.Layer<
|
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
|
||||||
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;
|
||||||
@@ -389,7 +354,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: options.staticDir,
|
staticDir: undefined,
|
||||||
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,
|
||||||
@@ -473,80 +438,6 @@ 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",
|
||||||
@@ -618,9 +509,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(path.join(stateDir, "state.sqlite")).pipe(
|
const persistenceLayer = makeSqlitePersistenceLive(
|
||||||
Layer.provide(NodeServices.layer),
|
path.join(stateDir, "state.sqlite"),
|
||||||
);
|
).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({
|
||||||
@@ -1521,7 +1412,7 @@ describe("WebSocket Server", () => {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
pr: null,
|
openPr: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||||
|
|||||||
+71
-165
@@ -6,10 +6,11 @@
|
|||||||
*
|
*
|
||||||
* @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,
|
||||||
@@ -24,20 +25,7 @@ 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 {
|
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
|
||||||
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";
|
||||||
@@ -54,7 +42,22 @@ import { clamp } from "effect/Number";
|
|||||||
import { Open } from "./open";
|
import { Open } from "./open";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig } from "./config";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -66,7 +69,7 @@ export interface ServerShape {
|
|||||||
readonly start: Effect.Effect<
|
readonly start: Effect.Effect<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
ServerLifecycleError,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -165,7 +168,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 | FileSystem.FileSystem | Path.Path
|
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||||
> {
|
> {
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
const {
|
const {
|
||||||
@@ -184,8 +187,6 @@ 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) =>
|
||||||
@@ -232,157 +233,62 @@ 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 respond = (
|
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||||
statusCode: number,
|
|
||||||
headers: Record<string, string>,
|
|
||||||
body?: string | Uint8Array,
|
|
||||||
) => {
|
|
||||||
res.writeHead(statusCode, headers);
|
|
||||||
res.end(body);
|
|
||||||
};
|
|
||||||
|
|
||||||
void Effect.runPromise(
|
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||||
Effect.gen(function* () {
|
return;
|
||||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
}
|
||||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
// In dev mode, redirect to Vite dev server
|
||||||
const attachmentsRoot = path.resolve(path.join(serverConfig.stateDir, "attachments"));
|
if (devUrl) {
|
||||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
res.writeHead(302, { Location: devUrl.href });
|
||||||
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
// Serve static files from the web app build
|
||||||
normalizedRelativePath.length === 0 ||
|
if (!staticDir) {
|
||||||
normalizedRelativePath.startsWith("..") ||
|
res.writeHead(503, { "Content-Type": "text/plain" });
|
||||||
normalizedRelativePath.includes("\0")
|
res.end("No static directory configured and no dev URL set.");
|
||||||
) {
|
return;
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
}
|
||||||
|
|
||||||
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
res.end(data);
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
});
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
return;
|
||||||
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");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
res.writeHead(200, { "Content-Type": contentType });
|
||||||
|
res.end(data);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -74,8 +74,6 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
|||||||
import {
|
import {
|
||||||
BotIcon,
|
BotIcon,
|
||||||
ChevronDownIcon,
|
ChevronDownIcon,
|
||||||
ChevronLeftIcon,
|
|
||||||
ChevronRightIcon,
|
|
||||||
CircleAlertIcon,
|
CircleAlertIcon,
|
||||||
FileIcon,
|
FileIcon,
|
||||||
FolderIcon,
|
FolderIcon,
|
||||||
@@ -113,7 +111,6 @@ 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);
|
||||||
@@ -168,36 +165,11 @@ interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"
|
|||||||
file: File;
|
file: File;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ExpandedImageItem {
|
interface ExpandedImagePreview {
|
||||||
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;
|
||||||
@@ -1098,53 +1070,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
};
|
};
|
||||||
}, [revokePreviewUrls]);
|
}, [revokePreviewUrls]);
|
||||||
|
|
||||||
const closeExpandedImage = useCallback(() => {
|
/**
|
||||||
setExpandedImage(null);
|
* Close expanded image on Escape key
|
||||||
}, []);
|
*/
|
||||||
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") {
|
if (event.key !== "Escape") return;
|
||||||
event.preventDefault();
|
setExpandedImage(null);
|
||||||
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);
|
||||||
}, [closeExpandedImage, expandedImage, navigateExpandedImage]);
|
}, [expandedImage]);
|
||||||
|
|
||||||
const activeWorktreePath = activeThread?.worktreePath;
|
const activeWorktreePath = activeThread?.worktreePath;
|
||||||
|
|
||||||
@@ -1781,10 +1722,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
[groupId]: !existing[groupId],
|
[groupId]: !existing[groupId],
|
||||||
}));
|
}));
|
||||||
}, []);
|
}, []);
|
||||||
const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
|
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
|
||||||
setExpandedImage(preview);
|
setExpandedImage(image);
|
||||||
}, []);
|
}, []);
|
||||||
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({
|
||||||
@@ -1884,8 +1824,6 @@ 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}
|
||||||
@@ -1947,11 +1885,9 @@ 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={() =>
|
||||||
const preview = buildExpandedImagePreview(composerImages, image.id);
|
setExpandedImage({ src: image.previewUrl, name: image.name })
|
||||||
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">
|
||||||
@@ -2175,29 +2111,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
|
|
||||||
{expandedImage && expandedImageItem && (
|
{expandedImage && (
|
||||||
<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={closeExpandedImage}
|
onClick={() => setExpandedImage(null)}
|
||||||
>
|
>
|
||||||
{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()}
|
||||||
@@ -2207,39 +2128,21 @@ 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={closeExpandedImage}
|
onClick={() => setExpandedImage(null)}
|
||||||
aria-label="Close image preview"
|
aria-label="Close image preview"
|
||||||
>
|
>
|
||||||
<XIcon />
|
<XIcon />
|
||||||
</Button>
|
</Button>
|
||||||
<img
|
<img
|
||||||
src={expandedImageItem.src}
|
src={expandedImage.src}
|
||||||
alt={expandedImageItem.name}
|
alt={expandedImage.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">
|
||||||
{expandedImageItem.name}
|
{expandedImage.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>
|
||||||
@@ -2433,7 +2336,13 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
|
|||||||
}, [text]);
|
}, [text]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Button type="button" size="xs" variant="outline" onClick={handleCopy} title="Copy message">
|
<Button
|
||||||
|
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>
|
||||||
);
|
);
|
||||||
@@ -2442,8 +2351,6 @@ 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;
|
||||||
@@ -2456,7 +2363,7 @@ interface MessagesTimelineProps {
|
|||||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||||
onRevertUserMessage: (messageId: MessageId) => void;
|
onRevertUserMessage: (messageId: MessageId) => void;
|
||||||
isRevertingCheckpoint: boolean;
|
isRevertingCheckpoint: boolean;
|
||||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
onImageExpand: (image: ExpandedImagePreview) => void;
|
||||||
markdownCwd: string | undefined;
|
markdownCwd: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2467,23 +2374,19 @@ 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; createdAt: string | null };
|
| { kind: "working"; id: string };
|
||||||
|
|
||||||
const MessagesTimeline = memo(function MessagesTimeline({
|
const MessagesTimeline = memo(function MessagesTimeline({
|
||||||
hasMessages,
|
hasMessages,
|
||||||
isWorking,
|
isWorking,
|
||||||
activeTurnInProgress,
|
|
||||||
activeTurnStartedAt,
|
|
||||||
scrollContainerRef,
|
scrollContainerRef,
|
||||||
timelineEntries,
|
timelineEntries,
|
||||||
completionDividerBeforeEntryId,
|
completionDividerBeforeEntryId,
|
||||||
@@ -2520,7 +2423,6 @@ 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;
|
||||||
@@ -2530,7 +2432,6 @@ 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" &&
|
||||||
@@ -2539,62 +2440,14 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isWorking) {
|
if (isWorking) {
|
||||||
nextRows.push({
|
nextRows.push({ kind: "working", id: "working-indicator-row" });
|
||||||
kind: "working",
|
|
||||||
id: "working-indicator-row",
|
|
||||||
createdAt: activeTurnStartedAt,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nextRows;
|
return nextRows;
|
||||||
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
|
}, [timelineEntries, completionDividerBeforeEntryId, isWorking]);
|
||||||
|
|
||||||
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: virtualizedRowCount,
|
count: rows.length,
|
||||||
getScrollElement: () => scrollContainerRef.current,
|
getScrollElement: () => scrollContainerRef.current,
|
||||||
estimateSize: (index: number) => {
|
estimateSize: (index: number) => {
|
||||||
const row = rows[index];
|
const row = rows[index];
|
||||||
@@ -2608,268 +2461,6 @@ 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 (
|
||||||
@@ -2882,31 +2473,291 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden">
|
<div
|
||||||
{virtualizedRowCount > 0 && (
|
className="relative mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
|
||||||
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}
|
||||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
>
|
||||||
const row = rows[virtualRow.index];
|
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||||
if (!row) return null;
|
const row = rows[virtualRow.index];
|
||||||
|
if (!row) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={`virtual-row:${row.id}`}
|
key={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)` }}
|
||||||
>
|
>
|
||||||
{renderRowContent(row)}
|
<div className="pb-4">
|
||||||
</div>
|
{row.kind === "work" &&
|
||||||
);
|
(() => {
|
||||||
})}
|
const groupId = row.id;
|
||||||
</div>
|
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})`;
|
||||||
|
|
||||||
{nonVirtualizedRows.map((row) => (
|
return (
|
||||||
<div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
|
<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={() =>
|
||||||
|
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>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
|||||||
hasUpstream: true,
|
hasUpstream: true,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
pr: null,
|
openPr: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -29,13 +29,12 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("resolveQuickAction opens the existing PR", () => {
|
it("resolveQuickAction opens the existing PR", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
pr: {
|
openPr: {
|
||||||
number: 10,
|
number: 10,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/10",
|
url: "https://example.com/pr/10",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -46,13 +45,12 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
pr: {
|
openPr: {
|
||||||
number: 11,
|
number: 11,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/11",
|
url: "https://example.com/pr/11",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -149,13 +147,12 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
aheadCount: 3,
|
aheadCount: 3,
|
||||||
pr: {
|
openPr: {
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/13",
|
url: "https://example.com/pr/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -167,13 +164,12 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
aheadCount: 2,
|
aheadCount: 2,
|
||||||
pr: {
|
openPr: {
|
||||||
number: 12,
|
number: 12,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/12",
|
url: "https://example.com/pr/12",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -208,7 +204,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
|
|
||||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||||
it("resolveQuickAction pushes and creates a PR", () => {
|
it("resolveQuickAction pushes and creates a PR", () => {
|
||||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
kind: "run_action",
|
kind: "run_action",
|
||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
@@ -217,7 +213,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||||
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -250,14 +246,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
|||||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||||
it("resolveQuickAction returns disabled no-action state", () => {
|
it("resolveQuickAction returns disabled no-action state", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -294,7 +290,7 @@ describe("when: branch is behind upstream", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables push and create PR", () => {
|
it("buildMenuItems disables push and create PR", () => {
|
||||||
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -350,13 +346,12 @@ describe("when: working tree has local changes", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
pr: {
|
openPr: {
|
||||||
number: 16,
|
number: 16,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/16",
|
url: "https://example.com/pr/16",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -416,7 +411,7 @@ describe("when: on default branch without open PR", () => {
|
|||||||
|
|
||||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
status({ branch: "main", aheadCount: 2, openPr: null }),
|
||||||
false,
|
false,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -516,7 +511,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
|||||||
describe("when: branch has no upstream configured", () => {
|
describe("when: branch has no upstream configured", () => {
|
||||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
@@ -531,13 +526,12 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
pr: {
|
openPr: {
|
||||||
number: 14,
|
number: 14,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/14",
|
url: "https://example.com/pr/14",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -554,13 +548,12 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 1,
|
aheadCount: 1,
|
||||||
pr: {
|
openPr: {
|
||||||
number: 15,
|
number: 15,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/15",
|
url: "https://example.com/pr/15",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
state: "open",
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -575,7 +568,7 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
|
|
||||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
const hasOpenPr = gitStatus.openPr !== null;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const canCommit = !isBusy && hasChanges;
|
const canCommit = !isBusy && hasChanges;
|
||||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
const hasOpenPr = gitStatus.openPr !== null;
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const isDiverged = isAhead && isBehind;
|
const isDiverged = isAhead && isBehind;
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ function getMenuActionDisabledReason(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
const hasOpenPr = gitStatus.openPr !== null;
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
|
|
||||||
@@ -219,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
||||||
if (!prUrl) {
|
if (!prUrl) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -236,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
data: threadToastData,
|
data: threadToastData,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
||||||
const runGitActionWithToast = useCallback(
|
const runGitActionWithToast = useCallback(
|
||||||
async ({
|
async ({
|
||||||
action,
|
action,
|
||||||
@@ -295,9 +295,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
stopProgressUpdates();
|
stopProgressUpdates();
|
||||||
const resultToast = summarizeGitResult(result);
|
const resultToast = summarizeGitResult(result);
|
||||||
|
|
||||||
const existingOpenPrUrl =
|
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
||||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
|
||||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
|
||||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||||
const shouldOfferOpenPrCta =
|
const shouldOfferOpenPrCta =
|
||||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||||
@@ -367,7 +365,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
[
|
[
|
||||||
gitStatusForActions?.branch,
|
gitStatusForActions?.branch,
|
||||||
gitStatusForActions?.hasWorkingTreeChanges,
|
gitStatusForActions?.hasWorkingTreeChanges,
|
||||||
gitStatusForActions?.pr,
|
gitStatusForActions?.openPr?.url,
|
||||||
isDefaultBranch,
|
isDefaultBranch,
|
||||||
maybeConfirmPushToDefaultBranch,
|
maybeConfirmPushToDefaultBranch,
|
||||||
runImmediateGitActionMutation,
|
runImmediateGitActionMutation,
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type GitStatusResult,
|
|
||||||
type ResolvedKeybindingsConfig,
|
type ResolvedKeybindingsConfig,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||||
import { useAppSettings } from "../appSettings";
|
import { useAppSettings } from "../appSettings";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
@@ -17,7 +16,7 @@ import { useStore } from "../store";
|
|||||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||||
import { type Thread } from "../types";
|
import { type Thread } from "../types";
|
||||||
import { derivePendingApprovals } from "../session-logic";
|
import { derivePendingApprovals } from "../session-logic";
|
||||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
import { toastManager } from "./ui/toast";
|
import { toastManager } from "./ui/toast";
|
||||||
@@ -64,13 +63,6 @@ interface TerminalStatusIndicator {
|
|||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PrStatusIndicator {
|
|
||||||
label: "PR open" | "PR closed" | "PR merged";
|
|
||||||
colorClass: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
|
||||||
|
|
||||||
function hasUnseenCompletion(thread: Thread): boolean {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurn?.completedAt) return false;
|
if (!thread.latestTurn?.completedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||||
@@ -133,28 +125,6 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
|
||||||
if (prState === "open") {
|
|
||||||
return {
|
|
||||||
label: "PR open",
|
|
||||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (prState === "closed") {
|
|
||||||
return {
|
|
||||||
label: "PR closed",
|
|
||||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (prState === "merged") {
|
|
||||||
return {
|
|
||||||
label: "PR merged",
|
|
||||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function T3Wordmark() {
|
function T3Wordmark() {
|
||||||
return (
|
return (
|
||||||
<svg
|
<svg
|
||||||
@@ -240,58 +210,6 @@ export default function Sidebar() {
|
|||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [state.threads]);
|
}, [state.threads]);
|
||||||
const projectCwdById = useMemo(
|
|
||||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
|
||||||
[state.projects],
|
|
||||||
);
|
|
||||||
const threadGitTargets = useMemo(
|
|
||||||
() =>
|
|
||||||
state.threads.map((thread) => ({
|
|
||||||
threadId: thread.id,
|
|
||||||
branch: thread.branch,
|
|
||||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
|
||||||
})),
|
|
||||||
[projectCwdById, state.threads],
|
|
||||||
);
|
|
||||||
const threadGitStatusCwds = useMemo(
|
|
||||||
() =>
|
|
||||||
[
|
|
||||||
...new Set(
|
|
||||||
threadGitTargets
|
|
||||||
.filter((target) => target.branch !== null)
|
|
||||||
.map((target) => target.cwd)
|
|
||||||
.filter((cwd): cwd is string => cwd !== null),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
[threadGitTargets],
|
|
||||||
);
|
|
||||||
const threadGitStatusQueries = useQueries({
|
|
||||||
queries: threadGitStatusCwds.map((cwd) => ({
|
|
||||||
...gitStatusQueryOptions(cwd),
|
|
||||||
staleTime: 30_000,
|
|
||||||
refetchInterval: 60_000,
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
const prStateByThreadId = useMemo(() => {
|
|
||||||
const statusByCwd = new Map<string, GitStatusResult>();
|
|
||||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
|
||||||
const cwd = threadGitStatusCwds[index];
|
|
||||||
if (!cwd) continue;
|
|
||||||
const status = threadGitStatusQueries[index]?.data;
|
|
||||||
if (status) {
|
|
||||||
statusByCwd.set(cwd, status);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const map = new Map<ThreadId, ThreadPrState>();
|
|
||||||
for (const target of threadGitTargets) {
|
|
||||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
|
||||||
const branchMatches =
|
|
||||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
|
||||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
|
||||||
|
|
||||||
const handleNewThread = useCallback(
|
const handleNewThread = useCallback(
|
||||||
(
|
(
|
||||||
@@ -714,7 +632,6 @@ export default function Sidebar() {
|
|||||||
thread,
|
thread,
|
||||||
pendingApprovalByThreadId.get(thread.id) === true,
|
pendingApprovalByThreadId.get(thread.id) === true,
|
||||||
);
|
);
|
||||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
|
||||||
const terminalStatus = terminalStatusIndicator(thread);
|
const terminalStatus = terminalStatusIndicator(thread);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -760,16 +677,6 @@ export default function Sidebar() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||||
{prStatus && (
|
|
||||||
<span
|
|
||||||
role="img"
|
|
||||||
aria-label={prStatus.label}
|
|
||||||
title={prStatus.label}
|
|
||||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
|
||||||
>
|
|
||||||
<GitPullRequestIcon className="size-3" />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{terminalStatus && (
|
{terminalStatus && (
|
||||||
<span
|
<span
|
||||||
role="img"
|
role="img"
|
||||||
|
|||||||
@@ -112,7 +112,6 @@ 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;
|
||||||
@@ -124,7 +123,6 @@ function TerminalViewport({
|
|||||||
terminalId,
|
terminalId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
runtimeEnv,
|
||||||
onSessionExited,
|
|
||||||
focusRequestId,
|
focusRequestId,
|
||||||
autoFocus,
|
autoFocus,
|
||||||
resizeEpoch,
|
resizeEpoch,
|
||||||
@@ -133,12 +131,6 @@ 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;
|
||||||
@@ -314,7 +306,6 @@ 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);
|
||||||
@@ -344,16 +335,6 @@ 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);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -802,7 +783,6 @@ 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}
|
||||||
@@ -820,7 +800,6 @@ 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}
|
||||||
|
|||||||
+1
-38
@@ -192,43 +192,6 @@ 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);
|
||||||
@@ -493,7 +456,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: toAttachmentPreviewUrl(attachment.dataUrl),
|
previewUrl: attachment.dataUrl,
|
||||||
}));
|
}));
|
||||||
const normalizedMessage: ChatMessage = {
|
const normalizedMessage: ChatMessage = {
|
||||||
id: message.id,
|
id: message.id,
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ export const GitPrStepStatus = Schema.Literals([
|
|||||||
"opened_existing",
|
"opened_existing",
|
||||||
"skipped_not_requested",
|
"skipped_not_requested",
|
||||||
]);
|
]);
|
||||||
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
|
||||||
export type GitStatusPrState = typeof GitStatusPrState.Type;
|
|
||||||
|
|
||||||
export const GitBranch = Schema.Struct({
|
export const GitBranch = Schema.Struct({
|
||||||
name: TrimmedNonEmptyStringSchema,
|
name: TrimmedNonEmptyStringSchema,
|
||||||
@@ -93,16 +91,6 @@ export type GitInitInput = typeof GitInitInput.Type;
|
|||||||
|
|
||||||
// RPC Results
|
// RPC Results
|
||||||
|
|
||||||
export const GitStatusPr = Schema.Struct({
|
|
||||||
number: PositiveInt,
|
|
||||||
title: TrimmedNonEmptyStringSchema,
|
|
||||||
url: Schema.String,
|
|
||||||
baseBranch: TrimmedNonEmptyStringSchema,
|
|
||||||
headBranch: TrimmedNonEmptyStringSchema,
|
|
||||||
state: GitStatusPrState,
|
|
||||||
});
|
|
||||||
export type GitStatusPr = typeof GitStatusPr.Type;
|
|
||||||
|
|
||||||
export const GitStatusResult = Schema.Struct({
|
export const GitStatusResult = Schema.Struct({
|
||||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||||
hasWorkingTreeChanges: Schema.Boolean,
|
hasWorkingTreeChanges: Schema.Boolean,
|
||||||
@@ -120,7 +108,15 @@ export const GitStatusResult = Schema.Struct({
|
|||||||
hasUpstream: Schema.Boolean,
|
hasUpstream: Schema.Boolean,
|
||||||
aheadCount: NonNegativeInt,
|
aheadCount: NonNegativeInt,
|
||||||
behindCount: NonNegativeInt,
|
behindCount: NonNegativeInt,
|
||||||
pr: Schema.NullOr(GitStatusPr),
|
openPr: Schema.NullOr(
|
||||||
|
Schema.Struct({
|
||||||
|
number: PositiveInt,
|
||||||
|
title: TrimmedNonEmptyStringSchema,
|
||||||
|
url: Schema.String,
|
||||||
|
baseBranch: TrimmedNonEmptyStringSchema,
|
||||||
|
headBranch: TrimmedNonEmptyStringSchema,
|
||||||
|
}),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"T3CODE_AUTH_TOKEN",
|
"T3CODE_AUTH_TOKEN",
|
||||||
"T3CODE_DESKTOP_WS_URL"
|
"T3CODE_DESKTOP_WS_URL"
|
||||||
],
|
],
|
||||||
|
"globalPassThroughEnv": ["OPENAI_API_KEY"],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"build": {
|
"build": {
|
||||||
"dependsOn": ["^build"],
|
"dependsOn": ["^build"],
|
||||||
|
|||||||
Reference in new issue
Block a user