diff --git a/.gitignore b/.gitignore index f5c9ebb69b..471855de15 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,5 @@ apps/web/.playwright apps/web/playwright-report apps/web/src/components/__screenshots__ .vitest-* -__screenshots__/ \ No newline at end of file +__screenshots__/ +.tanstack diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index f7d9a4f300..8bb5844228 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -8,7 +8,12 @@ import { Layer, Option, Path, + PlatformError, + Ref, + Result, Schema, + Scope, + Semaphore, Stream, } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; @@ -16,11 +21,14 @@ 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; @@ -29,6 +37,11 @@ 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; @@ -40,6 +53,7 @@ interface ExecuteGitOptions { timeoutMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorMessage?: string | undefined; + progress?: ExecuteGitProgress | undefined; } function parseBranchAb(value: string): { ahead: number; behind: number } { @@ -257,14 +271,201 @@ function toGitCommandError( }); } +interface Trace2Monitor { + readonly env: NodeJS.ProcessEnv; + readonly flush: Effect.Effect; +} + +function trace2ChildKey(record: Record): 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, + 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(); + const traceTailState = yield* Ref.make({ + 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* ( input: Pick, stream: Stream.Stream, maxOutputBytes: number, + onLine: ((line: string) => Effect.Effect) | undefined, ): Effect.fn.Return { 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* () { @@ -277,11 +478,17 @@ const collectOutput = Effect.fn(function* ( detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, }); } - text += decoder.decode(chunk, { stream: true }); + const decoded = decoder.decode(chunk, { stream: true }); + text += decoded; + lineBuffer += decoded; + yield* emitCompleteLines(false); }), ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed."))); - text += decoder.decode(); + const remainder = decoder.decode(); + text += remainder; + lineBuffer += remainder; + yield* emitCompleteLines(true); return text; }); @@ -306,19 +513,38 @@ 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, - ...(input.env ? { env: input.env } : {}), + env: { + ...process.env, + ...input.env, + ...trace2Monitor.env, + }, }), ) .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); const [stdout, stderr, exitCode] = yield* Effect.all( [ - collectOutput(commandInput, child.stdout, maxOutputBytes), - collectOutput(commandInput, child.stderr, maxOutputBytes), + collectOutput( + commandInput, + child.stdout, + maxOutputBytes, + input.progress?.onStdoutLine, + ), + collectOutput( + commandInput, + child.stderr, + maxOutputBytes, + input.progress?.onStderrLine, + ), child.exitCode.pipe( Effect.map((value) => Number(value)), Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), @@ -326,6 +552,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" ], { concurrency: "unbounded" }, ); + yield* trace2Monitor.flush; if (!input.allowNonZeroExit && exitCode !== 0) { const trimmedStderr = stderr.trim(); @@ -376,6 +603,7 @@ 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) { @@ -947,14 +1175,37 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" }; }); - const commit: GitCoreShape["commit"] = (cwd, subject, body) => + const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) => Effect.gen(function* () { const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { args.push("-m", trimmedBody); } - yield* runGit("GitCore.commit.commit", cwd, args); + 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); const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ "rev-parse", "HEAD", diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index 57d8dfebd0..ce252f739f 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -6,6 +6,7 @@ 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"; @@ -449,12 +450,20 @@ function runStackedAction( input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr"; + actionId?: string; commitMessage?: string; featureBranch?: boolean; filePaths?: readonly string[]; }, + options?: Parameters[1], ) { - return manager.runStackedAction(input); + return manager.runStackedAction( + { + ...input, + actionId: input.actionId ?? "test-action-id", + }, + options, + ); } function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) { @@ -1941,4 +1950,117 @@ 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", + }), + ]), + ); + }), + ); }); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index 1a3cf2bb35..4f240e0044 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -2,6 +2,7 @@ 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, @@ -9,11 +10,21 @@ import { } from "@t3tools/shared/git"; import { GitManagerError } from "../Errors.ts"; -import { GitManager, type GitManagerShape } from "../Services/GitManager.ts"; +import { + GitManager, + type GitActionProgressReporter, + type GitManagerShape, + type GitRunStackedActionOptions, +} 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 extends any ? Omit : never; +type GitActionProgressPayload = StripProgressContext; + interface OpenPrInfo { number: number; title: string; @@ -200,6 +211,17 @@ 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; @@ -337,6 +359,29 @@ 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, @@ -680,27 +725,111 @@ 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 suggestion = - preResolvedSuggestion ?? - (yield* resolveCommitAndBranchSuggestion({ + 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({ cwd, branch, ...(commitMessage ? { commitMessage } : {}), ...(filePaths ? { filePaths } : {}), ...(model ? { model } : {}), - })); + }); + } if (!suggestion) { return { status: "skipped_no_changes" as const }; } - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body); + 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; + } return { status: "created" as const, commitSha, @@ -1010,66 +1139,135 @@ export const makeGitManager = Effect.gen(function* () { }); const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced( - function* (input) { - const wantsPush = input.action !== "commit"; - const wantsPr = input.action === "commit_push_pr"; + 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; - 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 runAction = Effect.gen(function* () { + yield* progress.emit({ + kind: "action_started", + phases, + }); - let branchStep: { status: "created" | "skipped_not_requested"; name?: string }; - let commitMessageForStep = input.commitMessage; - let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined; + const wantsPush = input.action !== "commit"; + const wantsPr = input.action === "commit_push_pr"; - if (input.featureBranch) { - const result = yield* runFeatureBranchStep( + 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( input.cwd, - initialStatus.branch, - input.commitMessage, + input.action, + currentBranch, + commitMessageForStep, + preResolvedCommitSuggestion, 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 currentBranch = branchStep.name ?? initialStatus.branch; + 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 commit = yield* runCommitStep( - input.cwd, - currentBranch, - commitMessageForStep, - preResolvedCommitSuggestion, - input.filePaths, - input.textGenerationModel, + 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 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, - }; }, ); diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index bcab916db4..b74c526897 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -32,6 +32,7 @@ export interface ExecuteGitInput { readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; readonly maxOutputBytes?: number; + readonly progress?: ExecuteGitProgress; } export interface ExecuteGitResult { @@ -49,6 +50,35 @@ export interface GitPreparedCommitContext { stagedPatch: string; } +export interface ExecuteGitProgress { + readonly onStdoutLine?: (line: string) => Effect.Effect; + readonly onStderrLine?: (line: string) => Effect.Effect; + readonly onHookStarted?: (hookName: string) => Effect.Effect; + readonly onHookFinished?: (input: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => Effect.Effect; +} + +export interface GitCommitProgress { + readonly onOutputLine?: (input: { + stream: "stdout" | "stderr"; + text: string; + }) => Effect.Effect; + readonly onHookStarted?: (hookName: string) => Effect.Effect; + readonly onHookFinished?: (input: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => Effect.Effect; +} + +export interface GitCommitOptions { + readonly timeoutMs?: number; + readonly progress?: GitCommitProgress; +} + export interface GitPushResult { status: "pushed" | "skipped_up_to_date"; branch: string; @@ -132,6 +162,7 @@ export interface GitCoreShape { cwd: string, subject: string, body: string, + options?: GitCommitOptions, ) => Effect.Effect<{ commitSha: string }, GitCommandError>; /** diff --git a/apps/server/src/git/Services/GitManager.ts b/apps/server/src/git/Services/GitManager.ts index 650581c716..2e83b78c3b 100644 --- a/apps/server/src/git/Services/GitManager.ts +++ b/apps/server/src/git/Services/GitManager.ts @@ -7,6 +7,7 @@ * @module GitManager */ import { + GitActionProgressEvent, GitPreparePullRequestThreadInput, GitPreparePullRequestThreadResult, GitPullRequestRefInput, @@ -20,6 +21,15 @@ import { ServiceMap } from "effect"; import type { Effect } from "effect"; import type { GitManagerServiceError } from "../Errors.ts"; +export interface GitActionProgressReporter { + readonly publish: (event: GitActionProgressEvent) => Effect.Effect; +} + +export interface GitRunStackedActionOptions { + readonly actionId?: string; + readonly progressReporter?: GitActionProgressReporter; +} + /** * GitManagerShape - Service API for high-level Git workflow actions. */ @@ -51,6 +61,7 @@ export interface GitManagerShape { */ readonly runStackedAction: ( input: GitRunStackedActionInput, + options?: GitRunStackedActionOptions, ) => Effect.Effect; } diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index e23148973e..cf91bf2d52 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -1153,6 +1153,73 @@ 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* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index acbee86053..c1b320860d 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -2258,6 +2258,9 @@ 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, ); diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 825bcbded3..53ee7d74f1 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -469,6 +469,89 @@ 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()); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 8c71834e9e..b5085220c2 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -254,6 +254,180 @@ 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, "_"); } @@ -378,6 +552,7 @@ export class TerminalManagerRuntime extends EventEmitter status: "starting", pid: null, history, + pendingHistoryControlSequence: "", exitCode: null, exitSignal: null, updatedAt: new Date().toISOString(), @@ -407,10 +582,12 @@ export class TerminalManagerRuntime extends EventEmitter 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; @@ -469,6 +646,7 @@ export class TerminalManagerRuntime extends EventEmitter 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({ @@ -497,6 +675,7 @@ export class TerminalManagerRuntime extends EventEmitter status: "starting", pid: null, history: "", + pendingHistoryControlSequence: "", exitCode: null, exitSignal: null, updatedAt: new Date().toISOString(), @@ -520,6 +699,7 @@ export class TerminalManagerRuntime extends EventEmitter 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); @@ -694,9 +874,16 @@ export class TerminalManagerRuntime extends EventEmitter } private onProcessData(session: TerminalSessionState, data: string): void { - session.history = capHistory(`${session.history}${data}`, this.historyLineLimit); + 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.updatedAt = new Date().toISOString(); - this.queuePersist(session.threadId, session.terminalId, session.history); this.emitEvent({ type: "output", threadId: session.threadId, @@ -713,6 +900,7 @@ export class TerminalManagerRuntime extends EventEmitter 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(); @@ -736,6 +924,7 @@ export class TerminalManagerRuntime extends EventEmitter 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(); diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index 8d8398c7ad..c2539da4b6 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -32,6 +32,7 @@ export interface TerminalSessionState { status: TerminalSessionStatus; pid: number | null; history: string; + pendingHistoryControlSequence: string; exitCode: number | null; exitSignal: number | null; updatedAt: string; diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index 14a773ab5c..ff95b54112 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -1835,15 +1835,94 @@ 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({ + 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", cwd: "/test", - action: "commit_push", + action: "commit", }); + 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 () => { diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 4255938d62..bcb3850e7a 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -710,7 +710,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]), ); - const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) { + const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) { switch (request.body._tag) { case ORCHESTRATION_WS_METHODS.getSnapshot: return yield* projectionReadModelQuery.getSnapshot(); @@ -799,7 +799,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< case WS_METHODS.gitRunStackedAction: { const body = stripRequestTag(request.body); - return yield* gitManager.runStackedAction(body); + return yield* gitManager.runStackedAction(body, { + actionId: body.actionId, + progressReporter: { + publish: (event) => + pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid), + }, + }); } case WS_METHODS.gitResolvePullRequest: { @@ -921,7 +927,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< }); } - const result = yield* Effect.exit(routeRequest(request.success)); + const result = yield* Effect.exit(routeRequest(ws, request.success)); if (Exit.isFailure(result)) { return yield* sendWsResponse({ id: request.success.id, diff --git a/apps/web/src/appSettings.ts b/apps/web/src/appSettings.ts index 99a62f663f..cb7b5fd9ca 100644 --- a/apps/web/src/appSettings.ts +++ b/apps/web/src/appSettings.ts @@ -56,6 +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)), timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)), customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])), diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 17d0bbb4de..4f6933a0f6 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -24,6 +24,7 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER, type TerminalContextDraft, + removeInlineTerminalContextPlaceholder, } from "../lib/terminalContext"; import { isMacPlatform } from "../lib/utils"; import { getRouter } from "../router"; @@ -333,6 +334,18 @@ function createDraftOnlySnapshot(): OrchestrationReadModel { }; } +function withProjectScripts( + snapshot: OrchestrationReadModel, + scripts: OrchestrationReadModel["projects"][number]["scripts"], +): OrchestrationReadModel { + return { + ...snapshot, + projects: snapshot.projects.map((project) => + project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project, + ), + }; +} + function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ targetMessageId: "msg-user-plan-target" as MessageId, @@ -584,6 +597,58 @@ async function waitForInteractionModeButton( ); } +async function waitForServerConfigToApply(): Promise { + await vi.waitFor( + () => { + expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + await waitForLayout(); +} + +function dispatchChatNewShortcut(): void { + const useMetaForMod = isMacPlatform(navigator.platform); + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "o", + shiftKey: true, + metaKey: useMetaForMod, + ctrlKey: !useMetaForMod, + bubbles: true, + cancelable: true, + }), + ); +} + +async function triggerChatNewShortcutUntilPath( + router: ReturnType, + predicate: (pathname: string) => boolean, + errorMessage: string, +): Promise { + let pathname = router.state.location.pathname; + const deadline = Date.now() + 8_000; + while (Date.now() < deadline) { + dispatchChatNewShortcut(); + await waitForLayout(); + pathname = router.state.location.pathname; + if (predicate(pathname)) { + return pathname; + } + } + throw new Error(`${errorMessage} Last path: ${pathname}`); +} + +async function waitForNewThreadShortcutLabel(): Promise { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + await newThreadButton.hover(); + const shortcutLabel = isMacPlatform(navigator.platform) + ? "New thread (⇧⌘O)" + : "New thread (Ctrl+Shift+O)"; + await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument(); +} + async function waitForImagesToLoad(scope: ParentNode): Promise { const images = Array.from(scope.querySelectorAll("img")); if (images.length === 0) { @@ -988,6 +1053,145 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("runs project scripts from local draft threads at the project cwd", async () => { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + envMode: "local", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "lint", + name: "Lint", + command: "bun run lint", + icon: "lint", + runOnWorktreeCreate: false, + }, + ]), + }); + + try { + const runButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.title === "Run Lint", + ) as HTMLButtonElement | null, + "Unable to find Run Lint button.", + ); + runButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + threadId: THREAD_ID, + cwd: "/repo/project", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await vi.waitFor( + () => { + const writeRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalWrite, + ); + expect(writeRequest).toMatchObject({ + _tag: WS_METHODS.terminalWrite, + threadId: THREAD_ID, + data: "bun run lint\r", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("runs project scripts from worktree draft threads at the worktree cwd", async () => { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feature/draft", + worktreePath: "/repo/worktrees/feature-draft", + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "test", + name: "Test", + command: "bun run test", + icon: "test", + runOnWorktreeCreate: false, + }, + ]), + }); + + try { + const runButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.title === "Run Test", + ) as HTMLButtonElement | null, + "Unable to find Run Test button.", + ); + runButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + threadId: THREAD_ID, + cwd: "/repo/worktrees/feature-draft", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft", + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("toggles plan mode with Shift+Tab only while the composer is focused", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, @@ -1053,7 +1257,7 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); - it("keeps backspaced terminal context pills removed when a new one is added", async () => { + it("keeps removed terminal context pills removed when a new one is added", async () => { const removedLabel = "Terminal 1 lines 1-2"; const addedLabel = "Terminal 2 lines 9-10"; useComposerDraftStore.getState().addTerminalContext( @@ -1083,15 +1287,11 @@ describe("ChatView timeline estimator parity (full app)", () => { { timeout: 8_000, interval: 16 }, ); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Backspace", - bubbles: true, - cancelable: true, - }), - ); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? ""; + const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0); + store.setPrompt(THREAD_ID, nextPrompt.prompt); + store.removeTerminalContext(THREAD_ID, "ctx-removed"); await vi.waitFor( () => { @@ -1519,19 +1719,12 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { - const useMetaForMod = isMacPlatform(navigator.platform); - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "o", - shiftKey: true, - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - - await waitForURL( + await waitForNewThreadShortcutLabel(); + await waitForServerConfigToApply(); + const composerEditor = await waitForComposerEditor(); + composerEditor.focus(); + await waitForLayout(); + await triggerChatNewShortcutUntilPath( mounted.router, (path) => UUID_ROUTE_RE.test(path), "Route should have changed to a new draft thread UUID from the shortcut.", @@ -1540,7 +1733,6 @@ describe("ChatView timeline estimator parity (full app)", () => { await mounted.cleanup(); } }); - it("creates a fresh draft after the previous draft thread is promoted", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, @@ -1575,6 +1767,8 @@ describe("ChatView timeline estimator parity (full app)", () => { try { const newThreadButton = page.getByTestId("new-thread-button"); await expect.element(newThreadButton).toBeInTheDocument(); + await waitForNewThreadShortcutLabel(); + await waitForServerConfigToApply(); await newThreadButton.click(); const promotedThreadPath = await waitForURL( @@ -1588,19 +1782,7 @@ describe("ChatView timeline estimator parity (full app)", () => { syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId)); useComposerDraftStore.getState().clearDraftThread(promotedThreadId); - const useMetaForMod = isMacPlatform(navigator.platform); - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "o", - shiftKey: true, - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - - const freshThreadPath = await waitForURL( + const freshThreadPath = await triggerChatNewShortcutUntilPath( mounted.router, (path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath, "Shortcut should create a fresh draft instead of reusing the promoted thread.", diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 81a34472c6..3cc253933c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -114,6 +114,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { commandForProjectScript, nextProjectScriptId, + projectScriptCwd, projectScriptRuntimeEnv, projectScriptIdFromCommand, setupProjectScript, @@ -1042,7 +1043,12 @@ export default function ChatView({ threadId }: ChatViewProps) { latestTurnSettled, timelineEntries, ]); - const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null; + const gitCwd = activeProject + ? projectScriptCwd({ + project: { cwd: activeProject.cwd }, + worktreePath: activeThread?.worktreePath ?? null, + }) + : null; const composerTriggerKind = composerTrigger?.kind ?? null; const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : ""; const isPathTrigger = composerTriggerKind === "path"; @@ -1161,6 +1167,10 @@ 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], @@ -1351,12 +1361,10 @@ export default function ChatView({ threadId }: ChatViewProps) { worktreePath?: string | null; preferNewTerminal?: boolean; rememberAsLastInvoked?: boolean; - allowLocalDraftThread?: boolean; }, ) => { const api = readNativeApi(); if (!api || !activeThreadId || !activeProject || !activeThread) return; - if (!isServerThread && !options?.allowLocalDraftThread) return; if (options?.rememberAsLastInvoked !== false) { setLastInvokedScriptByProjectId((current) => { if (current[activeProject.id] === script.id) return current; @@ -1425,7 +1433,6 @@ export default function ChatView({ threadId }: ChatViewProps) { activeThread, activeThreadId, gitCwd, - isServerThread, setTerminalOpen, setThreadError, storeNewTerminal, @@ -2626,7 +2633,6 @@ export default function ChatView({ threadId }: ChatViewProps) { const setupScriptOptions: Parameters[1] = { worktreePath: nextThreadWorktreePath, rememberAsLastInvoked: false, - allowLocalDraftThread: createdServerThreadForLocalDraft, }; if (nextThreadWorktreePath) { setupScriptOptions.cwd = nextThreadWorktreePath; @@ -3514,13 +3520,16 @@ export default function ChatView({ threadId }: ChatViewProps) { activeThreadTitle={activeThread.title} activeProjectName={activeProject?.name} isGitRepo={isGitRepo} - openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null} + openInCwd={gitCwd} activeProjectScripts={activeProject?.scripts} preferredScriptId={ activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null } keybindings={keybindings} availableEditors={availableEditors} + terminalAvailable={activeProject !== undefined} + terminalOpen={terminalState.terminalOpen} + terminalToggleShortcutLabel={terminalToggleShortcutLabel} diffToggleShortcutLabel={diffPanelShortcutLabel} gitCwd={gitCwd} diffOpen={diffOpen} @@ -3530,6 +3539,7 @@ export default function ChatView({ threadId }: ChatViewProps) { onAddProjectScript={saveProjectScript} onUpdateProjectScript={updateProjectScript} onDeleteProjectScript={deleteProjectScript} + onToggleTerminal={toggleTerminalVisibility} onToggleDiff={onToggleDiff} /> diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 34ad788814..96e0219872 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -3,7 +3,13 @@ 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 } from "lucide-react"; +import { + ChevronLeftIcon, + ChevronRightIcon, + Columns2Icon, + Rows3Icon, + TextWrapIcon, +} from "lucide-react"; import { type WheelEvent as ReactWheelEvent, useCallback, @@ -162,8 +168,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const { resolvedTheme } = useTheme(); const { settings } = useAppSettings(); const [diffRenderMode, setDiffRenderMode] = useState("stacked"); + const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap); const patchViewportRef = useRef(null); const turnStripRef = useRef(null); + const previousDiffOpenRef = useRef(false); const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false); const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false); const routeThreadId = useParams({ @@ -171,6 +179,7 @@ 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, @@ -293,6 +302,13 @@ 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; @@ -490,25 +506,39 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { ))} - { - const next = value[0]; - if (next === "stacked" || next === "split") { - setDiffRenderMode(next); - } - }} - > - - +
+ { + const next = value[0]; + if (next === "stacked" || next === "split") { + setDiffRenderMode(next); + } + }} + > + + + + + + + + { + setDiffWordWrap(Boolean(pressed)); + }} + > + - - - - +
); @@ -582,6 +612,7 @@ 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, @@ -595,7 +626,14 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {

{renderablePatch.reason}

-
+                  
                     {renderablePatch.text}
                   
diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 0771875135..afbc718147 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1,6 +1,11 @@ -import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts"; +import type { + GitActionProgressEvent, + GitStackedAction, + GitStatusResult, + ThreadId, +} from "@t3tools/contracts"; import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react"; import { GitHubIcon } from "./Icons"; import { @@ -43,6 +48,7 @@ import { gitStatusQueryOptions, invalidateGitQueries, } from "~/lib/gitReactQuery"; +import { randomUUID } from "~/lib/utils"; import { resolvePathLinkTarget } from "~/terminal-links"; import { readNativeApi } from "~/nativeApi"; @@ -63,6 +69,50 @@ interface PendingDefaultBranchAction { type GitActionToastId = ReturnType; +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, @@ -167,6 +217,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions const [isEditingFiles, setIsEditingFiles] = useState(false); const [pendingDefaultBranchAction, setPendingDefaultBranchAction] = useState(null); + const activeGitActionProgressRef = useRef(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)); @@ -232,6 +297,84 @@ 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) { @@ -259,9 +402,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions data: threadToastData, }); }); - }, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]); + }, [gitStatusForActions, threadToastData]); - const runGitActionWithToast = useCallback( + const runGitActionWithToast = useEffectEvent( async ({ action, commitMessage, @@ -273,18 +416,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions isDefaultBranchOverride, progressToastId, filePaths, - }: { - action: GitStackedAction; - commitMessage?: string; - forcePushOnlyProgress?: boolean; - onConfirmed?: () => void; - skipDefaultBranchPrompt?: boolean; - statusOverride?: GitStatusResult | null; - featureBranch?: boolean; - isDefaultBranchOverride?: boolean; - progressToastId?: GitActionToastId; - filePaths?: string[]; - }) => { + }: RunGitActionWithToastInput) => { const actionStatus = statusOverride ?? gitStatusForActions; const actionBranch = actionStatus?.branch ?? null; const actionIsDefaultBranch = @@ -319,40 +451,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 } : {}), @@ -361,7 +493,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions try { const result = await promise; - stopProgressUpdates(); + activeGitActionProgressRef.current = null; const resultToast = summarizeGitResult(result); const existingOpenPrUrl = @@ -437,7 +569,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions : {}), }); } catch (err) { - stopProgressUpdates(); + activeGitActionProgressRef.current = null; toastManager.update(resolvedProgressToastId, { type: "error", title: "Action failed", @@ -446,14 +578,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }); } }, - - [ - isDefaultBranch, - runImmediateGitActionMutation, - setPendingDefaultBranchAction, - threadToastData, - gitStatusForActions, - ], ); const continuePendingDefaultBranchAction = useCallback(() => { @@ -469,38 +593,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions ...(filePaths ? { filePaths } : {}), skipDefaultBranchPrompt: true, }); - }, [pendingDefaultBranchAction, runGitActionWithToast]); - - const checkoutNewBranchAndRunAction = useCallback( - (actionParams: { - action: GitStackedAction; - commitMessage?: string; - forcePushOnlyProgress?: boolean; - onConfirmed?: () => void; - filePaths?: string[]; - }) => { - void runGitActionWithToast({ - ...actionParams, - featureBranch: true, - skipDefaultBranchPrompt: true, - }); - }, - [runGitActionWithToast], - ); + }, [pendingDefaultBranchAction]); const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => { if (!pendingDefaultBranchAction) return; const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } = pendingDefaultBranchAction; setPendingDefaultBranchAction(null); - checkoutNewBranchAndRunAction({ + void runGitActionWithToast({ action, ...(commitMessage ? { commitMessage } : {}), forcePushOnlyProgress, ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), + featureBranch: true, + skipDefaultBranchPrompt: true, }); - }, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]); + }, [pendingDefaultBranchAction]); const runDialogActionOnNewBranch = useCallback(() => { if (!isCommitDialogOpen) return; @@ -511,18 +620,14 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions setExcludedFiles(new Set()); setIsEditingFiles(false); - checkoutNewBranchAndRunAction({ + void runGitActionWithToast({ action: "commit", ...(commitMessage ? { commitMessage } : {}), ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}), + featureBranch: true, + skipDefaultBranchPrompt: true, }); - }, [ - allSelected, - isCommitDialogOpen, - dialogCommitMessage, - checkoutNewBranchAndRunAction, - selectedFiles, - ]); + }, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]); const runQuickAction = useCallback(() => { if (quickAction.kind === "open_pr") { @@ -562,7 +667,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions if (quickAction.action) { void runGitActionWithToast({ action: quickAction.action }); } - }, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]); + }, [openExistingPr, pullMutation, quickAction, threadToastData]); const openDialogForMenuItem = useCallback( (item: GitActionMenuItem) => { @@ -583,7 +688,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions setIsEditingFiles(false); setIsCommitDialogOpen(true); }, - [openExistingPr, runGitActionWithToast, setIsCommitDialogOpen], + [openExistingPr, setIsCommitDialogOpen], ); const runDialogAction = useCallback(() => { @@ -602,7 +707,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions allSelected, dialogCommitMessage, isCommitDialogOpen, - runGitActionWithToast, selectedFiles, setDialogCommitMessage, setIsCommitDialogOpen, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 5b13cd89c1..6b00f11df1 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -258,7 +258,7 @@ export default function Sidebar() { const markThreadUnread = useStore((store) => store.markThreadUnread); const toggleProject = useStore((store) => store.toggleProject); const reorderProjects = useStore((store) => store.reorderProjects); - const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft); + const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const getDraftThreadByProjectId = useComposerDraftStore( (store) => store.getDraftThreadByProjectId, ); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index ea7f911bec..39a4f6eedc 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { memo } from "react"; import GitActionsControl from "../GitActionsControl"; -import { DiffIcon } from "lucide-react"; +import { DiffIcon, TerminalSquareIcon } from "lucide-react"; import { Badge } from "../ui/badge"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl"; @@ -24,6 +24,9 @@ interface ChatHeaderProps { preferredScriptId: string | null; keybindings: ResolvedKeybindingsConfig; availableEditors: ReadonlyArray; + terminalAvailable: boolean; + terminalOpen: boolean; + terminalToggleShortcutLabel: string | null; diffToggleShortcutLabel: string | null; gitCwd: string | null; diffOpen: boolean; @@ -31,6 +34,7 @@ interface ChatHeaderProps { onAddProjectScript: (input: NewProjectScriptInput) => Promise; onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise; onDeleteProjectScript: (scriptId: string) => Promise; + onToggleTerminal: () => void; onToggleDiff: () => void; } @@ -44,6 +48,9 @@ export const ChatHeader = memo(function ChatHeader({ preferredScriptId, keybindings, availableEditors, + terminalAvailable, + terminalOpen, + terminalToggleShortcutLabel, diffToggleShortcutLabel, gitCwd, diffOpen, @@ -51,6 +58,7 @@ export const ChatHeader = memo(function ChatHeader({ onAddProjectScript, onUpdateProjectScript, onDeleteProjectScript, + onToggleTerminal, onToggleDiff, }: ChatHeaderProps) { return ( @@ -94,6 +102,30 @@ export const ChatHeader = memo(function ChatHeader({ /> )} {activeProjectName && } + + + + + } + /> + + {!terminalAvailable + ? "Terminal is unavailable until this thread has an active project." + : terminalToggleShortcutLabel + ? `Toggle terminal drawer (${terminalToggleShortcutLabel})` + : "Toggle terminal drawer"} + + { it("clears draft registration independently", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectId, threadId); + store.setPrompt(threadId, "remove me"); store.clearDraftThread(threadId); expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull(); expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull(); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined(); }); it("updates branch context on an existing draft thread", () => { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 73ec289ec0..ec6189e8aa 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -216,7 +216,6 @@ interface ComposerDraftStoreState { attachments: PersistedComposerImageAttachment[], ) => void; clearComposerContent: (threadId: ThreadId) => void; - clearThreadDraft: (threadId: ThreadId) => void; } const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze({ @@ -1185,12 +1184,19 @@ export const useComposerDraftStore = create()( if (threadId.length === 0) { return; } + const existing = get().draftsByThreadId[threadId]; + if (existing) { + for (const image of existing.images) { + revokeObjectPreviewUrl(image.previewUrl); + } + } set((state) => { const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined; const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes( threadId, ); - if (!hasDraftThread && !hasProjectMapping) { + const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined; + if (!hasDraftThread && !hasProjectMapping && !hasComposerDraft) { return state; } const nextProjectDraftThreadIdByProjectId = Object.fromEntries( @@ -1200,7 +1206,10 @@ export const useComposerDraftStore = create()( ) as Record; const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } = state.draftThreadsByThreadId; + const { [threadId]: _removedComposerDraft, ...restDraftsByThreadId } = + state.draftsByThreadId; return { + draftsByThreadId: restDraftsByThreadId, draftThreadsByThreadId: restDraftThreadsByThreadId, projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId, }; @@ -1683,41 +1692,6 @@ export const useComposerDraftStore = create()( return { draftsByThreadId: nextDraftsByThreadId }; }); }, - clearThreadDraft: (threadId) => { - if (threadId.length === 0) { - return; - } - const existing = get().draftsByThreadId[threadId]; - if (existing) { - for (const image of existing.images) { - revokeObjectPreviewUrl(image.previewUrl); - } - } - set((state) => { - const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined; - const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined; - const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes( - threadId, - ); - if (!hasComposerDraft && !hasDraftThread && !hasProjectMapping) { - return state; - } - const { [threadId]: _removedComposerDraft, ...restComposerDraftsByThreadId } = - state.draftsByThreadId; - const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } = - state.draftThreadsByThreadId; - const nextProjectDraftThreadIdByProjectId = Object.fromEntries( - Object.entries(state.projectDraftThreadIdByProjectId).filter( - ([, draftThreadId]) => draftThreadId !== threadId, - ), - ) as Record; - return { - draftsByThreadId: restComposerDraftsByThreadId, - draftThreadsByThreadId: restDraftThreadsByThreadId, - projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId, - }; - }); - }, }), { name: COMPOSER_DRAFT_STORAGE_KEY, diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.ts index d520f73c1c..d6a72859f3 100644 --- a/apps/web/src/lib/gitReactQuery.ts +++ b/apps/web/src/lib/gitReactQuery.ts @@ -117,11 +117,13 @@ 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; @@ -130,6 +132,7 @@ 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 } : {}), diff --git a/apps/web/src/lib/terminalFocus.test.ts b/apps/web/src/lib/terminalFocus.test.ts new file mode 100644 index 0000000000..832324ff14 --- /dev/null +++ b/apps/web/src/lib/terminalFocus.test.ts @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import { isTerminalFocused } from "./terminalFocus"; + +class MockHTMLElement { + isConnected = false; + className = ""; + + readonly classList = { + contains: (value: string) => this.className.split(/\s+/).includes(value), + }; + + closest(selector: string): MockHTMLElement | null { + return selector === ".thread-terminal-drawer .xterm" && this.isConnected ? this : null; + } +} + +const originalDocument = globalThis.document; +const originalHTMLElement = globalThis.HTMLElement; + +afterEach(() => { + if (originalDocument === undefined) { + delete (globalThis as { document?: Document }).document; + } else { + globalThis.document = originalDocument; + } + + if (originalHTMLElement === undefined) { + delete (globalThis as { HTMLElement?: typeof HTMLElement }).HTMLElement; + } else { + globalThis.HTMLElement = originalHTMLElement; + } +}); + +describe("isTerminalFocused", () => { + it("returns false for detached xterm helper textareas", () => { + const detached = new MockHTMLElement(); + detached.className = "xterm-helper-textarea"; + + globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement; + globalThis.document = { activeElement: detached } as Document; + + expect(isTerminalFocused()).toBe(false); + }); + + it("returns true for connected xterm helper textareas", () => { + const attached = new MockHTMLElement(); + attached.className = "xterm-helper-textarea"; + attached.isConnected = true; + + globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement; + globalThis.document = { activeElement: attached } as Document; + + expect(isTerminalFocused()).toBe(true); + }); +}); diff --git a/apps/web/src/lib/terminalFocus.ts b/apps/web/src/lib/terminalFocus.ts index d24c9572a3..d4edd9b14e 100644 --- a/apps/web/src/lib/terminalFocus.ts +++ b/apps/web/src/lib/terminalFocus.ts @@ -1,6 +1,7 @@ export function isTerminalFocused(): boolean { const activeElement = document.activeElement; if (!(activeElement instanceof HTMLElement)) return false; + if (!activeElement.isConnected) return false; if (activeElement.classList.contains("xterm-helper-textarea")) return true; return activeElement.closest(".thread-terminal-drawer .xterm") !== null; } diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.ts index dadc22a471..08678f8730 100644 --- a/apps/web/src/projectScripts.test.ts +++ b/apps/web/src/projectScripts.test.ts @@ -4,6 +4,7 @@ import { commandForProjectScript, nextProjectScriptId, primaryProjectScript, + projectScriptCwd, projectScriptRuntimeEnv, projectScriptIdFromCommand, setupProjectScript, @@ -70,4 +71,19 @@ describe("projectScripts helpers", () => { expect(env.CUSTOM_FLAG).toBe("1"); expect(env.T3CODE_WORKTREE_PATH).toBeUndefined(); }); + + it("prefers the worktree path for script cwd resolution", () => { + expect( + projectScriptCwd({ + project: { cwd: "/repo" }, + worktreePath: "/repo/worktree-a", + }), + ).toBe("/repo/worktree-a"); + expect( + projectScriptCwd({ + project: { cwd: "/repo" }, + worktreePath: null, + }), + ).toBe("/repo"); + }); }); diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.ts index e4ff752dbb..c11c3923bc 100644 --- a/apps/web/src/projectScripts.ts +++ b/apps/web/src/projectScripts.ts @@ -63,6 +63,15 @@ interface ProjectScriptRuntimeEnvInput { extraEnv?: Record; } +export function projectScriptCwd(input: { + project: { + cwd: string; + }; + worktreePath?: string | null; +}): string { + return input.worktreePath ?? input.project.cwd; +} + export function projectScriptRuntimeEnv( input: ProjectScriptRuntimeEnvInput, ): Record { diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index 0fbff1cdad..05fd640d0f 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -252,6 +252,7 @@ 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"] : []), @@ -500,6 +501,34 @@ function SettingsRouteView() { } /> + + updateSettings({ + diffWordWrap: defaults.diffWordWrap, + }) + } + /> + ) : null + } + control={ + + updateSettings({ + diffWordWrap: Boolean(checked), + }) + } + aria-label="Wrap diff lines by default" + /> + } + /> + { 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", @@ -274,11 +276,28 @@ describe("wsNativeApi", () => { }, } satisfies Extract; 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 () => { @@ -323,6 +342,26 @@ 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"); diff --git a/apps/web/src/wsNativeApi.ts b/apps/web/src/wsNativeApi.ts index ddfffbde69..042875f6f7 100644 --- a/apps/web/src/wsNativeApi.ts +++ b/apps/web/src/wsNativeApi.ts @@ -1,4 +1,5 @@ import { + type GitActionProgressEvent, ORCHESTRATION_WS_CHANNELS, ORCHESTRATION_WS_METHODS, type ContextMenuItem, @@ -15,6 +16,7 @@ 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 @@ -87,6 +89,16 @@ 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: { @@ -135,7 +147,8 @@ 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), + runStackedAction: (input) => + transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }), listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input), createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input), removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input), @@ -145,6 +158,12 @@ 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 ( diff --git a/apps/web/src/wsTransport.test.ts b/apps/web/src/wsTransport.test.ts index d905bbcf9a..55ff2556e4 100644 --- a/apps/web/src/wsTransport.test.ts +++ b/apps/web/src/wsTransport.test.ts @@ -206,4 +206,51 @@ 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(); + }); }); diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/wsTransport.ts index 46c74d9090..12c9a6d958 100644 --- a/apps/web/src/wsTransport.ts +++ b/apps/web/src/wsTransport.ts @@ -14,13 +14,17 @@ type PushListener = (message: WsPushMessage) => void interface PendingRequest { resolve: (result: unknown) => void; reject: (error: Error) => void; - timeout: ReturnType; + timeout: ReturnType | null; } interface SubscribeOptions { readonly replayLatest?: boolean; } +interface RequestOptions { + readonly timeoutMs?: number | null; +} + type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed"; const REQUEST_TIMEOUT_MS = 60_000; @@ -72,7 +76,11 @@ export class WsTransport { this.connect(); } - async request(method: string, params?: unknown): Promise { + async request( + method: string, + params?: unknown, + options?: RequestOptions, + ): Promise { if (typeof method !== "string" || method.length === 0) { throw new Error("Request method is required"); } @@ -83,10 +91,14 @@ export class WsTransport { const encoded = JSON.stringify(message); return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`Request timed out: ${method}`)); - }, REQUEST_TIMEOUT_MS); + 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); this.pending.set(id, { resolve: resolve as (result: unknown) => void, @@ -146,7 +158,9 @@ export class WsTransport { this.reconnectTimer = null; } for (const pending of this.pending.values()) { - clearTimeout(pending.timeout); + if (pending.timeout !== null) { + clearTimeout(pending.timeout); + } pending.reject(new Error("Transport disposed")); } this.pending.clear(); @@ -177,6 +191,14 @@ 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"; @@ -224,7 +246,9 @@ export class WsTransport { return; } - clearTimeout(pending.timeout); + if (pending.timeout !== null) { + clearTimeout(pending.timeout); + } this.pending.delete(message.id); if (message.error) { diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index b3775504fb..afb79d3a7c 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -4,6 +4,7 @@ import { Schema } from "effect"; import { GitCreateWorktreeInput, GitPreparePullRequestThreadInput, + GitRunStackedActionInput, GitResolvePullRequestResult, } from "./git"; @@ -11,6 +12,7 @@ const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInpu const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync( GitPreparePullRequestThreadInput, ); +const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput); const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult); describe("GitCreateWorktreeInput", () => { @@ -56,3 +58,16 @@ 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"); + }); +}); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index e64ca13d72..b7eadce123 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -8,6 +8,20 @@ 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", @@ -58,6 +72,7 @@ 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))), @@ -211,3 +226,62 @@ 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; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index b9127fb176..ea73024de3 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1,5 +1,6 @@ import type { GitCheckoutInput, + GitActionProgressEvent, GitCreateBranchInput, GitPreparePullRequestThreadInput, GitPreparePullRequestThreadResult, @@ -149,6 +150,7 @@ export interface NativeApi { pull: (input: GitPullInput) => Promise; status: (input: GitStatusInput) => Promise; runStackedAction: (input: GitRunStackedActionInput) => Promise; + onActionProgress: (callback: (event: GitActionProgressEvent) => void) => () => void; }; contextMenu: { show: ( diff --git a/packages/contracts/src/ws.test.ts b/packages/contracts/src/ws.test.ts index d732242ecd..2030dad4e5 100644 --- a/packages/contracts/src/ws.test.ts +++ b/packages/contracts/src/ws.test.ts @@ -95,6 +95,30 @@ 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( diff --git a/packages/contracts/src/ws.ts b/packages/contracts/src/ws.ts index ebb76138b8..45ef0512da 100644 --- a/packages/contracts/src/ws.ts +++ b/packages/contracts/src/ws.ts @@ -12,6 +12,7 @@ import { OrchestrationReplayEventsInput, } from "./orchestration"; import { + GitActionProgressEvent, GitCheckoutInput, GitCreateBranchInput, GitPreparePullRequestThreadInput, @@ -80,6 +81,7 @@ export const WS_METHODS = { // ── Push Event Channels ────────────────────────────────────────────── export const WS_CHANNELS = { + gitActionProgress: "git.actionProgress", terminalEvent: "terminal.event", serverWelcome: "server.welcome", serverConfigUpdated: "server.configUpdated", @@ -172,6 +174,7 @@ 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; } @@ -195,6 +198,10 @@ 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, @@ -202,6 +209,7 @@ export const WsPushOrchestrationDomainEvent = makeWsPushSchema( ); export const WsPushChannelSchema = Schema.Literals([ + WS_CHANNELS.gitActionProgress, WS_CHANNELS.serverWelcome, WS_CHANNELS.serverConfigUpdated, WS_CHANNELS.terminalEvent, @@ -212,6 +220,7 @@ export type WsPushChannelSchema = typeof WsPushChannelSchema.Type; export const WsPush = Schema.Union([ WsPushServerWelcome, WsPushServerConfigUpdated, + WsPushGitActionProgress, WsPushTerminalEvent, WsPushOrchestrationDomainEvent, ]);