Compare commits

..
Author SHA1 Message Date
Cursor Agent e0d6b2ab71 Remove duplicate clearThreadDraft in favor of clearDraftThread
clearThreadDraft was functionally identical to clearDraftThread after recent
changes. Remove the duplicate and update the single production caller in
Sidebar.tsx to use clearDraftThread instead.
2026-03-24 08:24:12 +00:00
Julius Marminge 657de3c173 Revoke draft image previews before clearing thread
- Clean up existing draft image object URLs when a thread is removed
- Prevent stale preview URLs from leaking after draft-thread resets
2026-03-24 01:14:01 -07:00
Julius Marminge 94491908fe Clear composer drafts when draft threads are removed
- Remove draft prompt state alongside draft thread cleanup
- Update tests for terminal context removal and new-thread shortcut
2026-03-24 01:08:28 -07:00
Julius Marminge 6fe23312a2 ignore 2026-03-24 00:37:19 -07:00
Julius Marminge 2069bdbe27 Fix chat.new shortcut by ignoring detached terminal focus
- Treat detached `xterm-helper-textarea` nodes as unfocused in `isTerminalFocused`
- Add unit tests for connected vs detached terminal focus behavior
- Harden ChatView shortcut test flow by waiting for keybindings/config and retrying route transition
2026-03-24 00:37:12 -07:00
Julius Marminge f152e3c53a Run project scripts in draft threads using resolved cwd
- use shared `projectScriptCwd` to choose worktree path or project root
- allow script execution from local draft threads with correct terminal env/cwd
- add ChatView and helper tests covering local and worktree draft cases
2026-03-24 00:36:58 -07:00
37 changed files with 565 additions and 2597 deletions

No files matched your search

+7 -258
View File
@@ -8,12 +8,7 @@ import {
Layer,
Option,
Path,
PlatformError,
Ref,
Result,
Schema,
Scope,
Semaphore,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -21,14 +16,11 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
GitCore,
type ExecuteGitProgress,
type GitCommitOptions,
type GitCoreShape,
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -37,11 +29,6 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
type TraceTailState = {
processedChars: number;
remainder: string;
};
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
upstreamRef: string;
@@ -53,7 +40,6 @@ interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
progress?: ExecuteGitProgress | undefined;
}
function parseBranchAb(value: string): { ahead: number; behind: number } {
@@ -271,201 +257,14 @@ function toGitCommandError(
});
}
interface Trace2Monitor {
readonly env: NodeJS.ProcessEnv;
readonly flush: Effect.Effect<void, never>;
}
function trace2ChildKey(record: Record<string, unknown>): string | null {
const childId = record.child_id;
if (typeof childId === "number" || typeof childId === "string") {
return String(childId);
}
const hookName = record.hook_name;
return typeof hookName === "string" && hookName.trim().length > 0 ? hookName.trim() : null;
}
const Trace2Record = Schema.Record(Schema.String, Schema.Unknown);
const createTrace2Monitor = Effect.fn(function* (
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
progress: ExecuteGitProgress | undefined,
): Effect.fn.Return<
Trace2Monitor,
PlatformError.PlatformError,
Scope.Scope | FileSystem.FileSystem | Path.Path
> {
if (!progress?.onHookStarted && !progress?.onHookFinished) {
return {
env: {},
flush: Effect.void,
};
}
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const traceFilePath = yield* fs.makeTempFileScoped({
prefix: `t3code-git-trace2-${process.pid}-`,
suffix: ".json",
});
const hookStartByChildKey = new Map<string, { hookName: string; startedAtMs: number }>();
const traceTailState = yield* Ref.make<TraceTailState>({
processedChars: 0,
remainder: "",
});
const handleTraceLine = (line: string) =>
Effect.gen(function* () {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
return;
}
const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine);
if (Result.isFailure(traceRecord)) {
yield* Effect.logDebug(
`GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`,
traceRecord.failure,
);
return;
}
if (traceRecord.success.child_class !== "hook") {
return;
}
const event = traceRecord.success.event;
const childKey = trace2ChildKey(traceRecord.success);
if (childKey === null) {
return;
}
const started = hookStartByChildKey.get(childKey);
const hookNameFromEvent =
typeof traceRecord.success.hook_name === "string"
? traceRecord.success.hook_name.trim()
: "";
const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? "");
if (hookName.length === 0) {
return;
}
if (event === "child_start") {
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
if (progress.onHookStarted) {
yield* progress.onHookStarted(hookName);
}
return;
}
if (event === "child_exit") {
hookStartByChildKey.delete(childKey);
if (progress.onHookFinished) {
const code = traceRecord.success.code;
yield* progress.onHookFinished({
hookName: started?.hookName ?? hookName,
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
});
}
}
});
const deltaMutex = yield* Semaphore.make(1);
const readTraceDelta = deltaMutex.withPermit(
fs.readFileString(traceFilePath).pipe(
Effect.flatMap((contents) =>
Effect.uninterruptible(
Ref.modify(traceTailState, ({ processedChars, remainder }) => {
if (contents.length <= processedChars) {
return [[], { processedChars, remainder }];
}
const appended = contents.slice(processedChars);
const combined = remainder + appended;
const lines = combined.split("\n");
const nextRemainder = lines.pop() ?? "";
return [
lines.map((line) => line.replace(/\r$/, "")),
{
processedChars: contents.length,
remainder: nextRemainder,
},
];
}).pipe(
Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })),
),
),
),
Effect.ignore({ log: true }),
),
);
const traceFileName = path.basename(traceFilePath);
yield* Stream.runForEach(fs.watch(traceFilePath), (event) => {
const eventPath = event.path;
const isTargetTraceEvent =
eventPath === traceFilePath ||
eventPath === traceFileName ||
path.basename(eventPath) === traceFileName;
if (!isTargetTraceEvent) return Effect.void;
return readTraceDelta;
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
yield* readTraceDelta;
const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [
remainder.trim(),
{
processedChars,
remainder: "",
},
]);
if (finalLine.length > 0) {
yield* handleTraceLine(finalLine);
}
}),
);
return {
env: {
GIT_TRACE2_EVENT: traceFilePath,
},
flush: readTraceDelta,
};
});
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
let lineBuffer = "";
const emitCompleteLines = (flush: boolean) =>
Effect.gen(function* () {
let newlineIndex = lineBuffer.indexOf("\n");
while (newlineIndex >= 0) {
const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
lineBuffer = lineBuffer.slice(newlineIndex + 1);
if (line.length > 0 && onLine) {
yield* onLine(line);
}
newlineIndex = lineBuffer.indexOf("\n");
}
if (flush) {
const trailing = lineBuffer.replace(/\r$/, "");
lineBuffer = "";
if (trailing.length > 0 && onLine) {
yield* onLine(trailing);
}
}
});
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
@@ -478,17 +277,11 @@ const collectOutput = Effect.fn(function* <E>(
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
const decoded = decoder.decode(chunk, { stream: true });
text += decoded;
lineBuffer += decoded;
yield* emitCompleteLines(false);
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
const remainder = decoder.decode();
text += remainder;
lineBuffer += remainder;
yield* emitCompleteLines(true);
text += decoder.decode();
return text;
});
@@ -513,38 +306,19 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
Effect.provideService(Path.Path, path),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")),
);
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
env: {
...process.env,
...input.env,
...trace2Monitor.env,
},
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(
commandInput,
child.stdout,
maxOutputBytes,
input.progress?.onStdoutLine,
),
collectOutput(
commandInput,
child.stderr,
maxOutputBytes,
input.progress?.onStderrLine,
),
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
@@ -552,7 +326,6 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
],
{ concurrency: "unbounded" },
);
yield* trace2Monitor.flush;
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
@@ -603,7 +376,6 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
args,
allowNonZeroExit: true,
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options.progress ? { progress: options.progress } : {}),
}).pipe(
Effect.flatMap((result) => {
if (options.allowNonZeroExit || result.code === 0) {
@@ -1175,37 +947,14 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
};
});
const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) =>
const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
Effect.gen(function* () {
const args = ["commit", "-m", subject];
const trimmedBody = body.trim();
if (trimmedBody.length > 0) {
args.push("-m", trimmedBody);
}
const progress = options?.progress
? {
...(options.progress.onOutputLine
? {
onStdoutLine: (line: string) =>
options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ??
Effect.void,
onStderrLine: (line: string) =>
options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ??
Effect.void,
}
: {}),
...(options.progress.onHookStarted
? { onHookStarted: options.progress.onHookStarted }
: {}),
...(options.progress.onHookFinished
? { onHookFinished: options.progress.onHookFinished }
: {}),
}
: null;
yield* executeGit("GitCore.commit.commit", cwd, args, {
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(progress ? { progress } : {}),
}).pipe(Effect.asVoid);
yield* runGit("GitCore.commit.commit", cwd, args);
const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
"rev-parse",
"HEAD",
+1 -123
View File
@@ -6,7 +6,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import type { GitActionProgressEvent } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -450,20 +449,12 @@ function runStackedAction(
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
actionId?: string;
commitMessage?: string;
featureBranch?: boolean;
filePaths?: readonly string[];
},
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
) {
return manager.runStackedAction(
{
...input,
actionId: input.actionId ?? "test-action-id",
},
options,
);
return manager.runStackedAction(input);
}
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
@@ -1950,117 +1941,4 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(errorMessage).toContain("already checked out in the main repo");
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-1",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
);
expect(result.commit.status).toBe("created");
expect(events.map((event) => event.kind)).toContain("action_started");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "phase_started",
phase: "commit",
}),
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: start",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: end",
}),
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_finished",
}),
]),
);
}),
);
it.effect("emits action_failed when a commit hook rejects", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const errorMessage = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-2",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("hook: fail");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_failed",
phase: "commit",
}),
]),
);
}),
);
});
+56 -254
View File
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import type { GitActionProgressEvent, GitActionProgressPhase } from "@t3tools/contracts";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -10,21 +9,11 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
interface OpenPrInfo {
number: number;
title: string;
@@ -211,17 +200,6 @@ function sanitizeCommitMessage(generated: {
};
}
function sanitizeProgressText(value: string): string | null {
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
return trimmed;
}
return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
@@ -359,29 +337,6 @@ export const makeGitManager = Effect.gen(function* () {
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const createProgressEmitter = (
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
options?: GitRunStackedActionOptions,
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
@@ -725,111 +680,27 @@ export const makeGitManager = Effect.gen(function* () {
const runCommitStep = (
cwd: string,
action: "commit" | "commit_push" | "commit_push_pr",
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
model?: string,
progressReporter?: GitActionProgressReporter,
actionId?: string,
) =>
Effect.gen(function* () {
const emit = (event: GitActionProgressPayload) =>
progressReporter && actionId
? progressReporter.publish({
actionId,
cwd,
action,
...event,
} as GitActionProgressEvent)
: Effect.void;
let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
if (!suggestion) {
const needsGeneration = !commitMessage?.trim();
if (needsGeneration) {
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Generating commit message...",
});
}
suggestion = yield* resolveCommitAndBranchSuggestion({
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
...(model ? { model } : {}),
});
}
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
let currentHookName: string | null = null;
const commitProgress =
progressReporter && actionId
? {
onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
const sanitized = sanitizeProgressText(text);
if (!sanitized) {
return Effect.void;
}
return emit({
kind: "hook_output",
hookName: currentHookName,
stream,
text: sanitized,
});
},
onHookStarted: (hookName: string) => {
currentHookName = hookName;
return emit({
kind: "hook_started",
hookName,
});
},
onHookFinished: ({
hookName,
exitCode,
durationMs,
}: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => {
if (currentHookName === hookName) {
currentHookName = null;
}
return emit({
kind: "hook_finished",
hookName,
exitCode,
durationMs,
});
},
}
: null;
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
timeoutMs: COMMIT_TIMEOUT_MS,
...(commitProgress ? { progress: commitProgress } : {}),
});
if (currentHookName !== null) {
yield* emit({
kind: "hook_finished",
hookName: currentHookName,
exitCode: 0,
durationMs: null,
});
currentHookName = null;
}
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
return {
status: "created" as const,
commitSha,
@@ -1139,135 +1010,66 @@ export const makeGitManager = Effect.gen(function* () {
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input, options) {
const progress = createProgressEmitter(input, options);
const phases: GitActionProgressPhase[] = [
...(input.featureBranch ? (["branch"] as const) : []),
"commit",
...(input.action !== "commit" ? (["push"] as const) : []),
...(input.action === "commit_push_pr" ? (["pr"] as const) : []),
];
let currentPhase: GitActionProgressPhase | null = null;
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const runAction = Effect.gen(function* () {
yield* progress.emit({
kind: "action_started",
phases,
});
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
currentPhase = "branch";
yield* progress.emit({
kind: "phase_started",
phase: "branch",
label: "Preparing feature branch...",
});
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
currentPhase = "commit";
const commit = yield* runCommitStep(
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
input.action,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
options?.progressReporter,
progress.actionId,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const push = wantsPush
? yield* progress
.emit({
kind: "phase_started",
phase: "push",
label: "Pushing...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "push";
return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch);
}),
),
)
: { status: "skipped_not_requested" as const };
const currentBranch = branchStep.name ?? initialStatus.branch;
const pr = wantsPr
? yield* progress
.emit({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "pr";
return yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel);
}),
),
)
: { status: "skipped_not_requested" as const };
const result = {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
yield* progress.emit({
kind: "action_finished",
result,
});
return result;
});
return yield* runAction.pipe(
Effect.catch((error) =>
progress
.emit({
kind: "action_failed",
phase: currentPhase,
message: error.message,
})
.pipe(Effect.flatMap(() => Effect.fail(error))),
),
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
input.textGenerationModel,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
},
);
-31
View File
@@ -32,7 +32,6 @@ export interface ExecuteGitInput {
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
@@ -50,35 +49,6 @@ export interface GitPreparedCommitContext {
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
@@ -162,7 +132,6 @@ export interface GitCoreShape {
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
@@ -7,7 +7,6 @@
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
@@ -21,15 +20,6 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "../Errors.ts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
@@ -61,7 +51,6 @@ export interface GitManagerShape {
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
@@ -1153,73 +1153,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
// The SDK consumes user messages via `for await (... of prompt)`.
// Stopping a session must end that loop cleanly — not throw an error.
//
// FakeClaudeQuery.close() masks this by resolving pending iterators
// before the shutdown propagates. Override it to match real SDK behavior
// where close() does not resolve the prompt consumer.
const query = new FakeClaudeQuery();
(query as { close: () => void }).close = () => {
query.closeCalls += 1;
};
let promptConsumerError: unknown = undefined;
const layer = makeClaudeAdapterLive({
createQuery: (input) => {
// Simulate the SDK consuming the prompt iterable
(async () => {
try {
for await (const _message of input.prompt) {
/* SDK processes user messages */
}
} catch (error) {
promptConsumerError = error;
}
})();
return query;
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = Effect.runFork(
Stream.runForEach(adapter.streamEvents, () => Effect.void),
);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.stopSession(THREAD_ID);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50)));
runtimeEventsFiber.interruptUnsafe();
assert.equal(
promptConsumerError,
undefined,
`Prompt consumer should not receive a thrown error on session stop, ` +
`but got: "${promptConsumerError instanceof Error ? promptConsumerError.message : String(promptConsumerError)}"`,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("forwards Claude task progress summaries for subagent updates", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -2258,9 +2258,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const prompt = Stream.fromQueue(promptQueue).pipe(
Stream.filter((item) => item.type === "message"),
Stream.map((item) => item.message),
Stream.catchCause((cause) =>
Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
),
Stream.toAsyncIterable,
);
@@ -469,89 +469,6 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
process.emitData("\u001b[32mok\u001b[0m ");
process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007");
process.emitData("\u001b[1;1R");
process.emitData("done\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n");
manager.dispose();
});
it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before clear\n");
process.emitData("\u001b[H\u001b[2J");
process.emitData("prompt ");
process.emitData("\u001b]11;");
process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1");
process.emitData("R\u001b[36mdone\u001b[0m\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe(
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
);
manager.dispose();
});
it("does not leak final bytes from ESC sequences with intermediate bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(B");
process.emitData("after\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(");
process.emitData("Bafter\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
+2 -191
View File
@@ -254,180 +254,6 @@ function capHistory(history: string, maxLines: number): string {
return hasTrailingNewline ? `${capped}\n` : capped;
}
function isCsiFinalByte(codePoint: number): boolean {
return codePoint >= 0x40 && codePoint <= 0x7e;
}
function shouldStripCsiSequence(body: string, finalByte: string): boolean {
if (finalByte === "n") {
return true;
}
if (finalByte === "R" && /^[0-9;?]*$/.test(body)) {
return true;
}
if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) {
return true;
}
return false;
}
function shouldStripOscSequence(content: string): boolean {
return /^(10|11|12);(?:\?|rgb:)/.test(content);
}
function stripStringTerminator(value: string): string {
if (value.endsWith("\u001b\\")) {
return value.slice(0, -2);
}
const lastCharacter = value.at(-1);
if (lastCharacter === "\u0007" || lastCharacter === "\u009c") {
return value.slice(0, -1);
}
return value;
}
function findStringTerminatorIndex(input: string, start: number): number | null {
for (let index = start; index < input.length; index += 1) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x07 || codePoint === 0x9c) {
return index + 1;
}
if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {
return index + 2;
}
}
return null;
}
function isEscapeIntermediateByte(codePoint: number): boolean {
return codePoint >= 0x20 && codePoint <= 0x2f;
}
function isEscapeFinalByte(codePoint: number): boolean {
return codePoint >= 0x30 && codePoint <= 0x7e;
}
function findEscapeSequenceEndIndex(input: string, start: number): number | null {
let cursor = start;
while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {
cursor += 1;
}
if (cursor >= input.length) {
return null;
}
return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;
}
function sanitizeTerminalHistoryChunk(
pendingControlSequence: string,
data: string,
): { visibleText: string; pendingControlSequence: string } {
const input = `${pendingControlSequence}${data}`;
let visibleText = "";
let index = 0;
const append = (value: string) => {
visibleText += value;
};
while (index < input.length) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x1b) {
const nextCodePoint = input.charCodeAt(index + 1);
if (Number.isNaN(nextCodePoint)) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
if (nextCodePoint === 0x5b) {
let cursor = index + 2;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 2, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (
nextCodePoint === 0x5d ||
nextCodePoint === 0x50 ||
nextCodePoint === 0x5e ||
nextCodePoint === 0x5f
) {
const terminatorIndex = findStringTerminatorIndex(input, index + 2);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));
if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);
if (escapeSequenceEndIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
append(input.slice(index, escapeSequenceEndIndex));
index = escapeSequenceEndIndex;
continue;
}
if (codePoint === 0x9b) {
let cursor = index + 1;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 1, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {
const terminatorIndex = findStringTerminatorIndex(input, index + 1);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));
if (codePoint !== 0x9d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
append(input[index] ?? "");
index += 1;
}
return { visibleText, pendingControlSequence: "" };
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
@@ -552,7 +378,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history,
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -582,12 +407,10 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
existing.cwd = input.cwd;
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
existing.runtimeEnv = nextRuntimeEnv;
@@ -646,7 +469,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
@@ -675,7 +497,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history: "",
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -699,7 +520,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const rows = input.rows ?? session.rows;
session.history = "";
session.pendingHistoryControlSequence = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
@@ -874,16 +694,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private onProcessData(session: TerminalSessionState, data: string): void {
const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data);
session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
if (sanitized.visibleText.length > 0) {
session.history = capHistory(
`${session.history}${sanitized.visibleText}`,
this.historyLineLimit,
);
this.queuePersist(session.threadId, session.terminalId, session.history);
}
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
@@ -900,7 +713,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
@@ -924,7 +736,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
this.killProcessWithEscalation(process, session.threadId, session.terminalId);
this.evictInactiveSessionsIfNeeded();
@@ -32,7 +32,6 @@ export interface TerminalSessionState {
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
+2 -81
View File
@@ -1811,94 +1811,15 @@ describe("WebSocket Server", () => {
connections.push(ws);
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(runStackedAction).toHaveBeenCalledWith(
{
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
},
expect.objectContaining({
actionId: "client-action-1",
progressReporter: expect.any(Object),
}),
);
});
it("publishes git action progress only to the initiating websocket", async () => {
const runStackedAction = vi.fn(
(_input, options) =>
options?.progressReporter
?.publish({
actionId: options.actionId ?? "action-1",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
})
.pipe(
Effect.flatMap(() =>
Effect.succeed({
action: "commit" as const,
branch: { status: "skipped_not_requested" as const },
commit: {
status: "created" as const,
commitSha: "abc1234",
subject: "Test commit",
},
push: { status: "skipped_not_requested" as const },
pr: { status: "skipped_not_requested" as const },
}),
),
) ?? Effect.void,
);
const gitManager: GitManagerShape = {
status: vi.fn(() => Effect.void as any),
resolvePullRequest: vi.fn(() => Effect.void as any),
preparePullRequestThread: vi.fn(() => Effect.void as any),
runStackedAction,
};
server = await createTestServer({ cwd: "/test", gitManager });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [initiatingWs] = await connectAndAwaitWelcome(port);
const [otherWs] = await connectAndAwaitWelcome(port);
connections.push(initiatingWs, otherWs);
const responsePromise = sendRequest(initiatingWs, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-2",
expect(runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit",
action: "commit_push",
});
const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress);
expect(progressPush.data).toEqual({
actionId: "client-action-2",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
await expect(
waitForPush(otherWs, WS_CHANNELS.gitActionProgress, undefined, 10, 100),
).rejects.toThrow("Timed out waiting for WebSocket message after 100ms");
await expect(responsePromise).resolves.toEqual(
expect.objectContaining({
result: expect.objectContaining({
action: "commit",
}),
}),
);
});
it("rejects websocket connections without a valid auth token", async () => {
+3 -9
View File
@@ -704,7 +704,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
);
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
switch (request.body._tag) {
case ORCHESTRATION_WS_METHODS.getSnapshot:
return yield* projectionReadModelQuery.getSnapshot();
@@ -793,13 +793,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitRunStackedAction: {
const body = stripRequestTag(request.body);
return yield* gitManager.runStackedAction(body, {
actionId: body.actionId,
progressReporter: {
publish: (event) =>
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
},
});
return yield* gitManager.runStackedAction(body);
}
case WS_METHODS.gitResolvePullRequest: {
@@ -921,7 +915,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
}
const result = yield* Effect.exit(routeRequest(ws, request.success));
const result = yield* Effect.exit(routeRequest(request.success));
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
-1
View File
@@ -19,7 +19,6 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@formkit/auto-animate": "^0.9.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
-14
View File
@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";
import {
AppSettingsSchema,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
DEFAULT_TIMESTAMP_FORMAT,
getAppModelOptions,
getCustomModelOptionsByProvider,
@@ -113,16 +111,6 @@ describe("timestamp format defaults", () => {
});
});
describe("sidebar sort defaults", () => {
it("defaults project sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER).toBe("updated_at");
});
it("defaults thread sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_THREAD_SORT_ORDER).toBe("updated_at");
});
});
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
@@ -257,8 +245,6 @@ describe("AppSettingsSchema", () => {
defaultThreadEnvMode: "local",
confirmThreadDelete: false,
enableAssistantStreaming: false,
sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
sidebarThreadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
customCodexModels: [],
customClaudeModels: [],
-13
View File
@@ -21,12 +21,6 @@ export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
export type ProviderCustomModelConfig = {
provider: ProviderKind;
@@ -62,14 +56,7 @@ export const AppSettingsSchema = Schema.Struct({
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
-8
View File
@@ -1119,10 +1119,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeProjectCwd, activeThreadWorktreePath]);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const terminalToggleShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
[keybindings],
);
const splitTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.split"),
[keybindings],
@@ -3478,9 +3474,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalState.terminalOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
diffOpen={diffOpen}
@@ -3490,7 +3483,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
onToggleTerminal={toggleTerminalVisibility}
onToggleDiff={onToggleDiff}
/>
</header>
+20 -58
View File
@@ -3,13 +3,7 @@ import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/reac
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import {
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
Rows3Icon,
TextWrapIcon,
} from "lucide-react";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import {
type WheelEvent as ReactWheelEvent,
useCallback,
@@ -168,10 +162,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const { resolvedTheme } = useTheme();
const { settings } = useAppSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const previousDiffOpenRef = useRef(false);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const routeThreadId = useParams({
@@ -179,7 +171,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const diffOpen = diffSearch.diff === "1";
const activeThreadId = routeThreadId;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
@@ -302,13 +293,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
);
}, [renderablePatch]);
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffWordWrap]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
return;
@@ -506,39 +490,25 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
))}
</div>
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
<ToggleGroup
className="shrink-0"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Toggle
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
>
<TextWrapIcon className="size-3" />
<ToggleGroup
className="shrink-0 [-webkit-app-region:no-drag]"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
</div>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
</>
);
@@ -612,7 +582,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
overflow: diffWordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
@@ -626,14 +595,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div className="h-full overflow-auto p-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre
className={cn(
"max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
diffWordWrap
? "overflow-auto whitespace-pre-wrap wrap-break-word"
: "overflow-auto",
)}
>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
{renderablePatch.text}
</pre>
</div>
+72 -176
View File
@@ -1,11 +1,6 @@
import type {
GitActionProgressEvent,
GitStackedAction,
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
import {
@@ -48,7 +43,6 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
@@ -69,50 +63,6 @@ interface PendingDefaultBranchAction {
type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
toastId: GitActionToastId;
actionId: string;
title: string;
phaseStartedAtMs: number | null;
hookStartedAtMs: number | null;
hookName: string | null;
lastOutputLine: string | null;
currentPhaseLabel: string | null;
}
interface RunGitActionWithToastInput {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
}
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000));
if (elapsedSeconds < 60) {
return `Running for ${elapsedSeconds}s`;
}
const minutes = Math.floor(elapsedSeconds / 60);
const seconds = elapsedSeconds % 60;
return `Running for ${minutes}m ${seconds}s`;
}
function resolveProgressDescription(progress: ActiveGitActionProgress): string | undefined {
if (progress.lastOutputLine) {
return progress.lastOutputLine;
}
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
}
function getMenuActionDisabledReason({
item,
gitStatus,
@@ -217,21 +167,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const [isEditingFiles, setIsEditingFiles] = useState(false);
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
const updateActiveProgressToast = useCallback(() => {
const progress = activeGitActionProgressRef.current;
if (!progress) {
return;
}
toastManager.update(progress.toastId, {
type: "loading",
title: progress.title,
description: resolveProgressDescription(progress),
timeout: 0,
data: threadToastData,
});
}, [threadToastData]);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
@@ -297,84 +232,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
})
: null;
useEffect(() => {
const api = readNativeApi();
if (!api) {
return;
}
const applyProgressEvent = (event: GitActionProgressEvent) => {
const progress = activeGitActionProgressRef.current;
if (!progress) {
return;
}
if (gitCwd && event.cwd !== gitCwd) {
return;
}
if (progress.actionId !== event.actionId) {
return;
}
const now = Date.now();
switch (event.kind) {
case "action_started":
progress.phaseStartedAtMs = now;
progress.hookStartedAtMs = null;
progress.hookName = null;
progress.lastOutputLine = null;
break;
case "phase_started":
progress.title = event.label;
progress.currentPhaseLabel = event.label;
progress.phaseStartedAtMs = now;
progress.hookStartedAtMs = null;
progress.hookName = null;
progress.lastOutputLine = null;
break;
case "hook_started":
progress.title = `Running ${event.hookName}...`;
progress.hookName = event.hookName;
progress.hookStartedAtMs = now;
progress.lastOutputLine = null;
break;
case "hook_output":
progress.lastOutputLine = event.text;
break;
case "hook_finished":
progress.title = progress.currentPhaseLabel ?? "Committing...";
progress.hookName = null;
progress.hookStartedAtMs = null;
progress.lastOutputLine = null;
break;
case "action_finished":
progress.phaseStartedAtMs = null;
progress.hookStartedAtMs = null;
break;
case "action_failed":
progress.phaseStartedAtMs = null;
progress.hookStartedAtMs = null;
break;
}
updateActiveProgressToast();
};
return api.git.onActionProgress(applyProgressEvent);
}, [gitCwd, updateActiveProgressToast]);
useEffect(() => {
const interval = window.setInterval(() => {
if (!activeGitActionProgressRef.current) {
return;
}
updateActiveProgressToast();
}, 1000);
return () => {
window.clearInterval(interval);
};
}, [updateActiveProgressToast]);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
if (!api) {
@@ -402,9 +259,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
data: threadToastData,
});
});
}, [gitStatusForActions, threadToastData]);
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
const runGitActionWithToast = useEffectEvent(
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
@@ -416,7 +273,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
isDefaultBranchOverride,
progressToastId,
filePaths,
}: RunGitActionWithToastInput) => {
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch =
@@ -451,40 +319,40 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
forcePushOnly: forcePushOnlyProgress,
featureBranch,
});
const actionId = randomUUID();
const resolvedProgressToastId =
progressToastId ??
toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
});
activeGitActionProgressRef.current = {
toastId: resolvedProgressToastId,
actionId,
title: progressStages[0] ?? "Running git action...",
phaseStartedAtMs: null,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
currentPhaseLabel: progressStages[0] ?? "Running git action...",
};
if (progressToastId) {
toastManager.update(progressToastId, {
type: "loading",
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
});
}
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(resolvedProgressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
data: threadToastData,
});
}, 1100);
const stopProgressUpdates = () => {
clearInterval(stageInterval);
};
const promise = runImmediateGitActionMutation.mutateAsync({
actionId,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
@@ -493,7 +361,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
try {
const result = await promise;
activeGitActionProgressRef.current = null;
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =
@@ -569,7 +437,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
: {}),
});
} catch (err) {
activeGitActionProgressRef.current = null;
stopProgressUpdates();
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
@@ -578,6 +446,14 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}
},
[
isDefaultBranch,
runImmediateGitActionMutation,
setPendingDefaultBranchAction,
threadToastData,
gitStatusForActions,
],
);
const continuePendingDefaultBranchAction = useCallback(() => {
@@ -593,23 +469,38 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
}, [pendingDefaultBranchAction, runGitActionWithToast]);
const checkoutNewBranchAndRunAction = useCallback(
(actionParams: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
filePaths?: string[];
}) => {
void runGitActionWithToast({
...actionParams,
featureBranch: true,
skipDefaultBranchPrompt: true,
});
},
[runGitActionWithToast],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
checkoutNewBranchAndRunAction({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
const runDialogActionOnNewBranch = useCallback(() => {
if (!isCommitDialogOpen) return;
@@ -620,14 +511,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
setExcludedFiles(new Set());
setIsEditingFiles(false);
void runGitActionWithToast({
checkoutNewBranchAndRunAction({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
}, [
allSelected,
isCommitDialogOpen,
dialogCommitMessage,
checkoutNewBranchAndRunAction,
selectedFiles,
]);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
@@ -667,7 +562,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
@@ -688,7 +583,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
},
[openExistingPr, setIsCommitDialogOpen],
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
);
const runDialogAction = useCallback(() => {
@@ -707,6 +602,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
allSelected,
dialogCommitMessage,
isCommitDialogOpen,
runGitActionWithToast,
selectedFiles,
setDialogCommitMessage,
setIsCommitDialogOpen,
@@ -1,23 +1,13 @@
import { describe, expect, it } from "vitest";
import {
getProjectSortTimestamp,
hasUnseenCompletion,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
} from "./Sidebar.logic";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type Project,
type Thread,
} from "../types";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
@@ -291,238 +281,3 @@ describe("resolveProjectStatusIndicator", () => {
).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
});
});
function makeProject(overrides: Partial<Project> = {}): Project {
return {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.4",
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5.4",
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
session: null,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
latestTurn: null,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
...overrides,
};
}
describe("sortThreadsForSidebar", () => {
it("sorts threads by the latest user message in recency mode", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
messages: [
{
id: "message-1" as never,
role: "user",
text: "older",
createdAt: "2026-03-09T10:01:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:01:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [
{
id: "message-2" as never,
role: "user",
text: "newer",
createdAt: "2026-03-09T10:06:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:06:00.000Z",
},
],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
]);
});
it("falls back to thread timestamps when there is no user message", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
messages: [
{
id: "message-1" as never,
role: "assistant",
text: "assistant only",
createdAt: "2026-03-09T10:02:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:02:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
]);
});
it("can sort threads by createdAt when configured", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
}),
],
"created_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
]);
});
});
describe("sortProjectsForSidebar", () => {
it("sorts projects by the most recent user message across their threads", () => {
const projects = [
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "Older project" }),
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Newer project" }),
];
const threads = [
makeThread({
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:20:00.000Z",
messages: [
{
id: "message-1" as never,
role: "user",
text: "older project user message",
createdAt: "2026-03-09T10:01:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:01:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-2"),
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [
{
id: "message-2" as never,
role: "user",
text: "newer project user message",
createdAt: "2026-03-09T10:05:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:05:00.000Z",
},
],
}),
];
const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("falls back to project timestamps when a project has no threads", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Older project",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Newer project",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("preserves manual project ordering", () => {
const projects = [
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),
];
const sorted = sortProjectsForSidebar(projects, [], "manual");
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("falls back to project timestamps when a project has no threads", () => {
const timestamp = getProjectSortTimestamp(
makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
[],
"updated_at",
);
expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
});
});
-96
View File
@@ -1,4 +1,3 @@
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
import {
@@ -9,13 +8,6 @@ import {
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
name: string;
createdAt?: string | undefined;
updatedAt?: string | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
export interface ThreadStatusPill {
label:
@@ -186,91 +178,3 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
function toSortableTimestamp(iso: string | undefined): number {
if (!iso) return Number.NEGATIVE_INFINITY;
const ms = Date.parse(iso);
return Number.isFinite(ms) ? ms : Number.NEGATIVE_INFINITY;
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
let latestUserMessageTimestamp = Number.NEGATIVE_INFINITY;
for (const message of thread.messages) {
if (message.role !== "user") continue;
latestUserMessageTimestamp = Math.max(
latestUserMessageTimestamp,
toSortableTimestamp(message.createdAt),
);
}
if (latestUserMessageTimestamp !== Number.NEGATIVE_INFINITY) {
return latestUserMessageTimestamp;
}
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt);
}
export function getThreadSortTimestamp(
thread: SidebarThreadSortInput,
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (sortOrder === "created_at") {
return toSortableTimestamp(thread.createdAt);
}
return getLatestUserMessageTimestamp(thread);
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const byTimestamp =
getThreadSortTimestamp(right, sortOrder) - getThreadSortTimestamp(left, sortOrder);
if (byTimestamp !== 0) return byTimestamp;
return right.id.localeCompare(left.id);
});
}
export function getProjectSortTimestamp(
project: SidebarProject,
projectThreads: readonly SidebarThreadSortInput[],
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (projectThreads.length > 0) {
return projectThreads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
}
if (sortOrder === "created_at") {
return toSortableTimestamp(project.createdAt);
}
return toSortableTimestamp(project.updatedAt ?? project.createdAt);
}
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
): TProject[] {
if (sortOrder === "manual") {
return [...projects];
}
const threadsByProjectId = new Map<string, TThread[]>();
for (const thread of threads) {
const existing = threadsByProjectId.get(thread.projectId) ?? [];
existing.push(thread);
threadsByProjectId.set(thread.projectId, existing);
}
return [...projects].toSorted((left, right) => {
const byTimestamp =
getProjectSortTimestamp(right, threadsByProjectId.get(right.id) ?? [], sortOrder) -
getProjectSortTimestamp(left, threadsByProjectId.get(left.id) ?? [], sortOrder);
if (byTimestamp !== 0 && !Number.isNaN(byTimestamp)) return byTimestamp;
return left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
});
}
File diff suppressed because it is too large. Load diff
+1 -33
View File
@@ -6,7 +6,7 @@ import {
} from "@t3tools/contracts";
import { memo } from "react";
import GitActionsControl from "../GitActionsControl";
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
import { DiffIcon } from "lucide-react";
import { Badge } from "../ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
@@ -24,9 +24,6 @@ interface ChatHeaderProps {
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
terminalAvailable: boolean;
terminalOpen: boolean;
terminalToggleShortcutLabel: string | null;
diffToggleShortcutLabel: string | null;
gitCwd: string | null;
diffOpen: boolean;
@@ -34,7 +31,6 @@ interface ChatHeaderProps {
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onDeleteProjectScript: (scriptId: string) => Promise<void>;
onToggleTerminal: () => void;
onToggleDiff: () => void;
}
@@ -48,9 +44,6 @@ export const ChatHeader = memo(function ChatHeader({
preferredScriptId,
keybindings,
availableEditors,
terminalAvailable,
terminalOpen,
terminalToggleShortcutLabel,
diffToggleShortcutLabel,
gitCwd,
diffOpen,
@@ -58,7 +51,6 @@ export const ChatHeader = memo(function ChatHeader({
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
onToggleTerminal,
onToggleDiff,
}: ChatHeaderProps) {
return (
@@ -102,30 +94,6 @@ export const ChatHeader = memo(function ChatHeader({
/>
)}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
variant="outline"
size="xs"
disabled={!terminalAvailable}
>
<TerminalSquareIcon className="size-3" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{!terminalAvailable
? "Terminal is unavailable until this thread has an active project."
: terminalToggleShortcutLabel
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
-3
View File
@@ -117,13 +117,11 @@ export function gitRunStackedActionMutationOptions(input: {
return mutationOptions({
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
mutationFn: async ({
actionId,
action,
commitMessage,
featureBranch,
filePaths,
}: {
actionId: string;
action: GitStackedAction;
commitMessage?: string;
featureBranch?: boolean;
@@ -132,7 +130,6 @@ export function gitRunStackedActionMutationOptions(input: {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git action is unavailable.");
return api.git.runStackedAction({
actionId,
cwd: input.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
-29
View File
@@ -252,7 +252,6 @@ function SettingsRouteView() {
const changedSettingLabels = [
...(theme !== "system" ? ["Theme"] : []),
...(settings.timestampFormat !== defaults.timestampFormat ? ["Time format"] : []),
...(settings.diffWordWrap !== defaults.diffWordWrap ? ["Diff line wrapping"] : []),
...(settings.enableAssistantStreaming !== defaults.enableAssistantStreaming
? ["Assistant output"]
: []),
@@ -501,34 +500,6 @@ function SettingsRouteView() {
}
/>
<SettingsRow
title="Diff line wrapping"
description="Set the default wrap state when the diff panel opens. The in-panel wrap toggle only affects the current diff session."
resetAction={
settings.diffWordWrap !== defaults.diffWordWrap ? (
<SettingResetButton
label="diff line wrapping"
onClick={() =>
updateSettings({
diffWordWrap: defaults.diffWordWrap,
})
}
/>
) : null
}
control={
<Switch
checked={settings.diffWordWrap}
onCheckedChange={(checked) =>
updateSettings({
diffWordWrap: Boolean(checked),
})
}
aria-label="Wrap diff lines by default"
/>
}
/>
<SettingsRow
title="Assistant output"
description="Show token-by-token output while a response is in progress."
-14
View File
@@ -226,20 +226,6 @@ describe("store read model sync", () => {
expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");
});
it("preserves project and thread updatedAt timestamps from the read model", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
makeReadModelThread({
updatedAt: "2026-02-27T00:05:00.000Z",
}),
);
const next = syncServerReadModel(initialState, readModel);
expect(next.projects[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
});
it("preserves the current project order when syncing incoming read model updates", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
-3
View File
@@ -145,8 +145,6 @@ function mapProjectsFromReadModel(
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.workspaceRoot)
: true),
createdAt: project.createdAt,
updatedAt: project.updatedAt,
scripts: project.scripts.map((script) => ({ ...script })),
} satisfies Project;
});
@@ -306,7 +304,6 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
})),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
-3
View File
@@ -82,8 +82,6 @@ export interface Project {
cwd: string;
model: string;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
}
@@ -100,7 +98,6 @@ export interface Thread {
proposedPlans: ProposedPlan[];
error: string | null;
createdAt: string;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
branch: string | null;
-39
View File
@@ -239,11 +239,9 @@ describe("wsNativeApi", () => {
const api = createWsNativeApi();
const onTerminalEvent = vi.fn();
const onDomainEvent = vi.fn();
const onActionProgress = vi.fn();
api.terminal.onEvent(onTerminalEvent);
api.orchestration.onDomainEvent(onDomainEvent);
api.git.onActionProgress(onActionProgress);
const terminalEvent = {
threadId: "thread-1",
@@ -276,28 +274,11 @@ describe("wsNativeApi", () => {
},
} satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
emitPush(WS_CHANNELS.gitActionProgress, {
actionId: "action-1",
cwd: "/repo",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
expect(onTerminalEvent).toHaveBeenCalledTimes(1);
expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
expect(onDomainEvent).toHaveBeenCalledTimes(1);
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
expect(onActionProgress).toHaveBeenCalledTimes(1);
expect(onActionProgress).toHaveBeenCalledWith({
actionId: "action-1",
cwd: "/repo",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
});
it("wraps orchestration dispatch commands in the command envelope", async () => {
@@ -339,26 +320,6 @@ describe("wsNativeApi", () => {
});
});
it("uses no client timeout for git.runStackedAction", async () => {
requestMock.mockResolvedValue({
action: "commit",
branch: { status: "skipped_not_requested" },
commit: { status: "created", commitSha: "abc1234", subject: "Test" },
push: { status: "skipped_not_requested" },
pr: { status: "skipped_not_requested" },
});
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
await api.git.runStackedAction({ actionId: "action-1", cwd: "/repo", action: "commit" });
expect(requestMock).toHaveBeenCalledWith(
WS_METHODS.gitRunStackedAction,
{ actionId: "action-1", cwd: "/repo", action: "commit" },
{ timeoutMs: null },
);
});
it("forwards full-thread diff requests to the orchestration websocket method", async () => {
requestMock.mockResolvedValue({ diff: "patch" });
const { createWsNativeApi } = await import("./wsNativeApi");
+1 -20
View File
@@ -1,5 +1,4 @@
import {
type GitActionProgressEvent,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type ContextMenuItem,
@@ -16,7 +15,6 @@ import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>();
/**
* Subscribe to the server welcome message. If a welcome was already received
@@ -89,16 +87,6 @@ export function createWsNativeApi(): NativeApi {
}
}
});
transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => {
const payload = message.data;
for (const listener of gitActionProgressListeners) {
try {
listener(payload);
} catch {
// Swallow listener errors
}
}
});
const api: NativeApi = {
dialogs: {
@@ -147,8 +135,7 @@ export function createWsNativeApi(): NativeApi {
git: {
pull: (input) => transport.request(WS_METHODS.gitPull, input),
status: (input) => transport.request(WS_METHODS.gitStatus, input),
runStackedAction: (input) =>
transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }),
runStackedAction: (input) => transport.request(WS_METHODS.gitRunStackedAction, input),
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
@@ -158,12 +145,6 @@ export function createWsNativeApi(): NativeApi {
resolvePullRequest: (input) => transport.request(WS_METHODS.gitResolvePullRequest, input),
preparePullRequestThread: (input) =>
transport.request(WS_METHODS.gitPreparePullRequestThread, input),
onActionProgress: (callback) => {
gitActionProgressListeners.add(callback);
return () => {
gitActionProgressListeners.delete(callback);
};
},
},
contextMenu: {
show: async <T extends string>(
-47
View File
@@ -206,51 +206,4 @@ describe("WsTransport", () => {
await expect(requestPromise).resolves.toEqual({ projects: [] });
transport.dispose();
});
it("does not create a timeout for requests with timeoutMs null", async () => {
const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
const transport = new WsTransport("ws://localhost:3020");
const socket = getSocket();
socket.open();
const requestPromise = transport.request(
"git.runStackedAction",
{ cwd: "/repo" },
{ timeoutMs: null },
);
const sent = socket.sent.at(-1);
if (!sent) {
throw new Error("Expected request envelope to be sent");
}
const requestEnvelope = JSON.parse(sent) as { id: string };
socket.serverMessage(
JSON.stringify({
id: requestEnvelope.id,
result: { ok: true },
}),
);
await expect(requestPromise).resolves.toEqual({ ok: true });
expect(timeoutSpy.mock.calls.some(([callback]) => typeof callback === "function")).toBe(false);
transport.dispose();
});
it("rejects pending requests when the websocket closes", async () => {
const transport = new WsTransport("ws://localhost:3020");
const socket = getSocket();
socket.open();
const requestPromise = transport.request(
"git.runStackedAction",
{ cwd: "/repo" },
{ timeoutMs: null },
);
socket.close();
await expect(requestPromise).rejects.toThrow("WebSocket connection closed.");
transport.dispose();
});
});
+8 -32
View File
@@ -14,17 +14,13 @@ type PushListener<C extends WsPushChannel> = (message: WsPushMessage<C>) => void
interface PendingRequest {
resolve: (result: unknown) => void;
reject: (error: Error) => void;
timeout: ReturnType<typeof setTimeout> | null;
timeout: ReturnType<typeof setTimeout>;
}
interface SubscribeOptions {
readonly replayLatest?: boolean;
}
interface RequestOptions {
readonly timeoutMs?: number | null;
}
type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed";
const REQUEST_TIMEOUT_MS = 60_000;
@@ -76,11 +72,7 @@ export class WsTransport {
this.connect();
}
async request<T = unknown>(
method: string,
params?: unknown,
options?: RequestOptions,
): Promise<T> {
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
if (typeof method !== "string" || method.length === 0) {
throw new Error("Request method is required");
}
@@ -91,14 +83,10 @@ export class WsTransport {
const encoded = JSON.stringify(message);
return new Promise<T>((resolve, reject) => {
const timeoutMs = options?.timeoutMs === undefined ? REQUEST_TIMEOUT_MS : options.timeoutMs;
const timeout =
timeoutMs === null
? null
: setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Request timed out: ${method}`));
}, timeoutMs);
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Request timed out: ${method}`));
}, REQUEST_TIMEOUT_MS);
this.pending.set(id, {
resolve: resolve as (result: unknown) => void,
@@ -158,9 +146,7 @@ export class WsTransport {
this.reconnectTimer = null;
}
for (const pending of this.pending.values()) {
if (pending.timeout !== null) {
clearTimeout(pending.timeout);
}
clearTimeout(pending.timeout);
pending.reject(new Error("Transport disposed"));
}
this.pending.clear();
@@ -191,14 +177,6 @@ export class WsTransport {
ws.addEventListener("close", () => {
if (this.ws === ws) {
this.ws = null;
this.outboundQueue.length = 0;
for (const [id, pending] of this.pending.entries()) {
if (pending.timeout !== null) {
clearTimeout(pending.timeout);
}
this.pending.delete(id);
pending.reject(new Error("WebSocket connection closed."));
}
}
if (this.disposed) {
this.state = "disposed";
@@ -246,9 +224,7 @@ export class WsTransport {
return;
}
if (pending.timeout !== null) {
clearTimeout(pending.timeout);
}
clearTimeout(pending.timeout);
this.pending.delete(message.id);
if (message.error) {
-3
View File
@@ -80,7 +80,6 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@formkit/auto-animate": "^0.9.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
@@ -359,8 +358,6 @@
"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@formkit/auto-animate": ["@formkit/[email protected]", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="],
"@hapi/address": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="],
"@hapi/formula": ["@hapi/[email protected]", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="],
-15
View File
@@ -4,7 +4,6 @@ import { Schema } from "effect";
import {
GitCreateWorktreeInput,
GitPreparePullRequestThreadInput,
GitRunStackedActionInput,
GitResolvePullRequestResult,
} from "./git";
@@ -12,7 +11,6 @@ const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInpu
const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
GitPreparePullRequestThreadInput,
);
const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput);
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
describe("GitCreateWorktreeInput", () => {
@@ -58,16 +56,3 @@ describe("GitResolvePullRequestResult", () => {
expect(parsed.pullRequest.headBranch).toBe("feature/pr-threads");
});
});
describe("GitRunStackedActionInput", () => {
it("requires a client-provided actionId for progress correlation", () => {
const parsed = decodeRunStackedActionInput({
actionId: "action-1",
cwd: "/repo",
action: "commit",
});
expect(parsed.actionId).toBe("action-1");
expect(parsed.action).toBe("commit");
});
});
-74
View File
@@ -8,20 +8,6 @@ const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
export const GitStackedAction = Schema.Literals(["commit", "commit_push", "commit_push_pr"]);
export type GitStackedAction = typeof GitStackedAction.Type;
export const GitActionProgressPhase = Schema.Literals(["branch", "commit", "push", "pr"]);
export type GitActionProgressPhase = typeof GitActionProgressPhase.Type;
export const GitActionProgressKind = Schema.Literals([
"action_started",
"phase_started",
"hook_started",
"hook_output",
"hook_finished",
"action_finished",
"action_failed",
]);
export type GitActionProgressKind = typeof GitActionProgressKind.Type;
export const GitActionProgressStream = Schema.Literals(["stdout", "stderr"]);
export type GitActionProgressStream = typeof GitActionProgressStream.Type;
const GitCommitStepStatus = Schema.Literals(["created", "skipped_no_changes"]);
const GitPushStepStatus = Schema.Literals([
"pushed",
@@ -72,7 +58,6 @@ export const GitPullInput = Schema.Struct({
export type GitPullInput = typeof GitPullInput.Type;
export const GitRunStackedActionInput = Schema.Struct({
actionId: TrimmedNonEmptyStringSchema,
cwd: TrimmedNonEmptyStringSchema,
action: GitStackedAction,
commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),
@@ -226,62 +211,3 @@ export const GitPullResult = Schema.Struct({
upstreamBranch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
});
export type GitPullResult = typeof GitPullResult.Type;
const GitActionProgressBase = Schema.Struct({
actionId: TrimmedNonEmptyStringSchema,
cwd: TrimmedNonEmptyStringSchema,
action: GitStackedAction,
});
const GitActionStartedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("action_started"),
phases: Schema.Array(GitActionProgressPhase),
});
const GitActionPhaseStartedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("phase_started"),
phase: GitActionProgressPhase,
label: TrimmedNonEmptyStringSchema,
});
const GitActionHookStartedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("hook_started"),
hookName: TrimmedNonEmptyStringSchema,
});
const GitActionHookOutputEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("hook_output"),
hookName: Schema.NullOr(TrimmedNonEmptyStringSchema),
stream: GitActionProgressStream,
text: TrimmedNonEmptyStringSchema,
});
const GitActionHookFinishedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("hook_finished"),
hookName: TrimmedNonEmptyStringSchema,
exitCode: Schema.NullOr(Schema.Int),
durationMs: Schema.NullOr(NonNegativeInt),
});
const GitActionFinishedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("action_finished"),
result: GitRunStackedActionResult,
});
const GitActionFailedEvent = Schema.Struct({
...GitActionProgressBase.fields,
kind: Schema.Literal("action_failed"),
phase: Schema.NullOr(GitActionProgressPhase),
message: TrimmedNonEmptyStringSchema,
});
export const GitActionProgressEvent = Schema.Union([
GitActionStartedEvent,
GitActionPhaseStartedEvent,
GitActionHookStartedEvent,
GitActionHookOutputEvent,
GitActionHookFinishedEvent,
GitActionFinishedEvent,
GitActionFailedEvent,
]);
export type GitActionProgressEvent = typeof GitActionProgressEvent.Type;
-2
View File
@@ -1,6 +1,5 @@
import type {
GitCheckoutInput,
GitActionProgressEvent,
GitCreateBranchInput,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
@@ -150,7 +149,6 @@ export interface NativeApi {
pull: (input: GitPullInput) => Promise<GitPullResult>;
status: (input: GitStatusInput) => Promise<GitStatusResult>;
runStackedAction: (input: GitRunStackedActionInput) => Promise<GitRunStackedActionResult>;
onActionProgress: (callback: (event: GitActionProgressEvent) => void) => () => void;
};
contextMenu: {
show: <T extends string>(
-24
View File
@@ -95,30 +95,6 @@ it.effect("accepts typed websocket push envelopes with sequence", () =>
}),
);
it.effect("accepts git.actionProgress push envelopes", () =>
Effect.gen(function* () {
const parsed = yield* decodeWsResponse({
type: "push",
sequence: 3,
channel: WS_CHANNELS.gitActionProgress,
data: {
actionId: "action-1",
cwd: "/repo",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
},
});
if (!("type" in parsed) || parsed.type !== "push") {
assert.fail("expected websocket response to decode as a push envelope");
}
assert.strictEqual(parsed.channel, WS_CHANNELS.gitActionProgress);
}),
);
it.effect("rejects push envelopes when channel payload does not match the channel schema", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
-9
View File
@@ -12,7 +12,6 @@ import {
OrchestrationReplayEventsInput,
} from "./orchestration";
import {
GitActionProgressEvent,
GitCheckoutInput,
GitCreateBranchInput,
GitPreparePullRequestThreadInput,
@@ -81,7 +80,6 @@ export const WS_METHODS = {
// ── Push Event Channels ──────────────────────────────────────────────
export const WS_CHANNELS = {
gitActionProgress: "git.actionProgress",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
serverConfigUpdated: "server.configUpdated",
@@ -174,7 +172,6 @@ export type WsWelcomePayload = typeof WsWelcomePayload.Type;
export interface WsPushPayloadByChannel {
readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload;
readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type;
readonly [WS_CHANNELS.gitActionProgress]: typeof GitActionProgressEvent.Type;
readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type;
readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent;
}
@@ -198,10 +195,6 @@ export const WsPushServerConfigUpdated = makeWsPushSchema(
WS_CHANNELS.serverConfigUpdated,
ServerConfigUpdatedPayload,
);
export const WsPushGitActionProgress = makeWsPushSchema(
WS_CHANNELS.gitActionProgress,
GitActionProgressEvent,
);
export const WsPushTerminalEvent = makeWsPushSchema(WS_CHANNELS.terminalEvent, TerminalEvent);
export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
ORCHESTRATION_WS_CHANNELS.domainEvent,
@@ -209,7 +202,6 @@ export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
);
export const WsPushChannelSchema = Schema.Literals([
WS_CHANNELS.gitActionProgress,
WS_CHANNELS.serverWelcome,
WS_CHANNELS.serverConfigUpdated,
WS_CHANNELS.terminalEvent,
@@ -220,7 +212,6 @@ export type WsPushChannelSchema = typeof WsPushChannelSchema.Type;
export const WsPush = Schema.Union([
WsPushServerWelcome,
WsPushServerConfigUpdated,
WsPushGitActionProgress,
WsPushTerminalEvent,
WsPushOrchestrationDomainEvent,
]);