Add Review Sweep: one-click agentic review of unsettled work
Adds a sidebar-v2 button that reviews every unsettled thread across all connected environments: an LLM summarizes each thread, suggests a corrected title when the current one is misleading, and recommends settling threads whose work has concluded. Results stream into a new /review-sweep page with per-item Apply buttons and Apply All — nothing applies without a click. - contracts: ReviewThreadSummaryInput/Result, review.summarizeThread WS RPC, reviewSweep capability flag (old servers are skipped) - server: generateThreadReview TextGeneration op across all five providers, conservative prompt with transcript capping, and ReviewService.summarizeThread reading the projection - client-runtime: summarizeThread RPC command atom - web: reviewSweepStore runner (concurrency 3, runId-guarded, survives navigation), /review-sweep view, SidebarV2 entry button Settle recommendations are blocked for active threads at four layers: prompt rules, normalizeThreadReview, a server-side projection re-check (never trusts the client's canSettleNow), and a client canSettle re-check at apply time. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
67a7b1a1d3
commit
f8aa8450d1
26 files changed
+1457
-13
No files matched your search
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
reviewSweep: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -365,6 +365,7 @@ function createTextGeneration(
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateThreadReview: () => Effect.die("generateThreadReview is not used by GitManager tests"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,17 +3,59 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import {
|
||||
ThreadId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as ReviewService from "./ReviewService.ts";
|
||||
|
||||
function makeShellFromThread(
|
||||
thread: OrchestrationThread,
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly baseDir: string;
|
||||
readonly detectCalls?: Array<{ readonly cwd: string }>;
|
||||
readonly thread?: OrchestrationThread;
|
||||
readonly shellOverrides?: Partial<OrchestrationThreadShell>;
|
||||
readonly generateThreadReview?: TextGeneration.TextGeneration["Service"]["generateThreadReview"];
|
||||
readonly reviewCalls?: Array<TextGeneration.ThreadReviewGenerationInput>;
|
||||
}) {
|
||||
return ReviewService.layer.pipe(
|
||||
Layer.provide(
|
||||
@@ -28,11 +70,92 @@ function makeLayer(input: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
|
||||
getThreadDetailById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.thread && input.thread.id === threadId
|
||||
? Option.some(input.thread)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.thread && input.thread.id === threadId
|
||||
? Option.some(makeShellFromThread(input.thread, input.shellOverrides))
|
||||
: Option.none(),
|
||||
),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadReview: (reviewInput) => {
|
||||
input.reviewCalls?.push(reviewInput);
|
||||
return (
|
||||
input.generateThreadReview?.(reviewInput) ??
|
||||
Effect.succeed({
|
||||
summary: "Did the thing.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Work concluded.",
|
||||
})
|
||||
);
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerSettings.layerTest()),
|
||||
Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<OrchestrationThread> = {}): OrchestrationThread {
|
||||
return {
|
||||
id: ThreadId.make("thread_review_1"),
|
||||
projectId: "project_1" as OrchestrationThread["projectId"],
|
||||
title: "New thread",
|
||||
modelSelection: {
|
||||
instanceId: "codex" as OrchestrationThread["modelSelection"]["instanceId"],
|
||||
model: "gpt-5",
|
||||
options: [],
|
||||
},
|
||||
runtimeMode: "local",
|
||||
interactionMode: "chat",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-07-20T00:00:00.000Z",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...overrides,
|
||||
} as OrchestrationThread;
|
||||
}
|
||||
|
||||
function makeMessage(input: {
|
||||
readonly id: string;
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly streaming?: boolean;
|
||||
}): OrchestrationThread["messages"][number] {
|
||||
return {
|
||||
id: input.id as OrchestrationThread["messages"][number]["id"],
|
||||
role: input.role,
|
||||
text: input.text,
|
||||
turnId: null,
|
||||
streaming: input.streaming ?? false,
|
||||
createdAt: "2026-07-20T00:00:00.000Z",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("ReviewService", () => {
|
||||
it.effect("rejects diff preview cwd outside the configured workspace roots", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -97,4 +220,153 @@ describe("ReviewService", () => {
|
||||
assert.deepStrictEqual(detectCalls, []);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread fails with ReviewThreadNotFoundError for unknown threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review
|
||||
.summarizeThread({ threadId: ThreadId.make("thread_missing"), canSettleNow: true })
|
||||
.pipe(Effect.flip);
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir })));
|
||||
|
||||
assert.strictEqual(error._tag, "ReviewThreadNotFoundError");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread passes transcript context and returns the review", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({
|
||||
messages: [
|
||||
makeMessage({ id: "msg_1", role: "user", text: "Fix the settle default" }),
|
||||
makeMessage({ id: "msg_2", role: "assistant", text: "Done, merged in PR #1" }),
|
||||
makeMessage({ id: "msg_3", role: "assistant", text: "streaming...", streaming: true }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Bumped the settle default; PR merged.",
|
||||
suggestedTitle: "Bump settle default",
|
||||
recommendSettle: true,
|
||||
settleReason: "PR merged, nothing pending.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.threadId, thread.id);
|
||||
assert.strictEqual(result.summary, "Bumped the settle default; PR merged.");
|
||||
assert.strictEqual(result.suggestedTitle, "Bump settle default");
|
||||
assert.strictEqual(result.recommendSettle, true);
|
||||
assert.strictEqual(result.settleReason, "PR merged, nothing pending.");
|
||||
|
||||
assert.strictEqual(reviewCalls.length, 1);
|
||||
const call = reviewCalls[0]!;
|
||||
assert.strictEqual(call.title, "New thread");
|
||||
assert.strictEqual(call.isActive, false);
|
||||
assert.strictEqual(call.firstUserMessage, "Fix the settle default");
|
||||
// Streaming messages are excluded from the transcript.
|
||||
assert.deepStrictEqual(
|
||||
call.recentMessages.map((message) => message.text),
|
||||
["Fix the settle default", "Done, merged in PR #1"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread never recommends settling when canSettleNow is false", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: false });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
// Model misbehaves and recommends settle anyway.
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Still working.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Looks done to me.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
assert.strictEqual(result.settleReason, null);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"summarizeThread overrides a stale client canSettleNow when the projection shows activity",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-review-workspace-",
|
||||
});
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
// Client believed the thread was settleable, but the server-side
|
||||
// shell says approvals are pending.
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
shellOverrides: { hasPendingApprovals: true },
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Looks finished.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Done.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
assert.strictEqual(result.settleReason, null);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -3,17 +3,27 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import {
|
||||
ReviewThreadNotFoundError,
|
||||
TextGenerationError,
|
||||
VcsRepositoryDetectionError,
|
||||
VcsUnsupportedOperationError,
|
||||
type ReviewDiffPreviewError,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
type ReviewThreadSummaryError,
|
||||
type ReviewThreadSummaryInput,
|
||||
type ReviewThreadSummaryResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
@@ -23,6 +33,9 @@ export class ReviewService extends Context.Service<
|
||||
readonly getDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
|
||||
readonly summarizeThread: (
|
||||
input: ReviewThreadSummaryInput,
|
||||
) => Effect.Effect<ReviewThreadSummaryResult, ReviewThreadSummaryError>;
|
||||
}
|
||||
>()("t3/review/ReviewService") {}
|
||||
|
||||
@@ -32,6 +45,9 @@ export const make = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
|
||||
const canonicalizePath = (value: string) => {
|
||||
const resolvedPath = path.resolve(value);
|
||||
@@ -106,8 +122,90 @@ export const make = Effect.gen(function* () {
|
||||
return yield* getDriverDiffPreview(input);
|
||||
});
|
||||
|
||||
const summarizeThread: ReviewService["Service"]["summarizeThread"] = Effect.fn(
|
||||
"ReviewService.summarizeThread",
|
||||
)(function* (input) {
|
||||
const mapProjectionError = (cause: unknown) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: "Failed to read the thread projection for review.",
|
||||
cause,
|
||||
});
|
||||
|
||||
const threadOption = yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
if (Option.isNone(threadOption)) {
|
||||
return yield* new ReviewThreadNotFoundError({ threadId: input.threadId });
|
||||
}
|
||||
const thread = threadOption.value;
|
||||
|
||||
const projectOption = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(thread.projectId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
const cwd =
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: Option.isSome(projectOption) ? [projectOption.value] : [],
|
||||
}) ?? process.cwd();
|
||||
|
||||
const settled = thread.messages.filter((message) => !message.streaming);
|
||||
const firstUserMessage = settled.find((message) => message.role === "user")?.text ?? null;
|
||||
const recentMessages = settled.map((message) => ({
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
}));
|
||||
// Never trust the client's canSettleNow alone: re-derive activity from the
|
||||
// server's own projection so a session that started (or approval/input
|
||||
// that appeared) after the client read its shell still blocks settling.
|
||||
const shellOption = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
const shell = Option.isSome(shellOption) ? shellOption.value : null;
|
||||
const serverSideActive =
|
||||
shell === null ||
|
||||
shell.hasPendingApprovals ||
|
||||
shell.hasPendingUserInput ||
|
||||
shell.session?.status === "starting" ||
|
||||
shell.session?.status === "running";
|
||||
const canSettleNow = input.canSettleNow && !serverSideActive;
|
||||
const isActive = !canSettleNow;
|
||||
|
||||
const { textGenerationModelSelection: modelSelection } = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: "Failed to load server settings for review generation.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const generated = yield* textGeneration.generateThreadReview({
|
||||
cwd,
|
||||
title: thread.title,
|
||||
isActive,
|
||||
firstUserMessage,
|
||||
recentMessages,
|
||||
modelSelection,
|
||||
});
|
||||
|
||||
// Belt and braces on top of prompt rules + normalizeThreadReview: an
|
||||
// active thread must never carry a settle recommendation.
|
||||
const recommendSettle = generated.recommendSettle && canSettleNow;
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
summary: generated.summary,
|
||||
suggestedTitle: generated.suggestedTitle,
|
||||
recommendSettle,
|
||||
settleReason: recommendSettle ? generated.settleReason : null,
|
||||
};
|
||||
});
|
||||
|
||||
return ReviewService.of({
|
||||
getDiffPreview,
|
||||
summarizeThread,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -87,6 +87,7 @@ import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/provid
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
|
||||
import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
@@ -522,6 +523,19 @@ const buildAppUnderTest = (options?: {
|
||||
: ReviewService.layer.pipe(
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadReview: () => Effect.die("TextGeneration not stubbed in this test"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerSettings.layerTest()),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
|
||||
|
||||
@@ -222,6 +222,7 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
|
||||
const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provide(TextGeneration.layer),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
|
||||
@@ -23,10 +23,12 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -85,7 +87,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
value: unknown,
|
||||
detail: string,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
@@ -115,7 +118,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -355,10 +359,31 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("ClaudeTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -21,10 +21,12 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -98,7 +100,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
value: unknown,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
encodeJsonString(value).pipe(
|
||||
@@ -117,7 +120,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
attachments: TextGeneration.BranchNameGenerationInput["attachments"],
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
@@ -159,7 +163,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -398,10 +403,32 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("CodexTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths: [],
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -15,9 +15,11 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -54,7 +56,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -255,10 +258,31 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("CursorTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -16,9 +16,11 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -52,7 +54,8 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -247,10 +250,31 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("GrokTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -22,10 +22,12 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -39,6 +41,7 @@ const OpenCodeTextGenerationOperation = Schema.Literals([
|
||||
"generatePrContent",
|
||||
"generateBranchName",
|
||||
"generateThreadTitle",
|
||||
"generateThreadReview",
|
||||
]);
|
||||
|
||||
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
|
||||
@@ -253,7 +256,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
}) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
@@ -611,10 +615,31 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("OpenCodeTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
});
|
||||
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -21,6 +21,8 @@ const makeStubTextGeneration = (
|
||||
generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),
|
||||
generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),
|
||||
generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),
|
||||
generateThreadReview: () =>
|
||||
Effect.die("generateThreadReview stub not configured for this test"),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
|
||||
@@ -67,6 +67,26 @@ export interface ThreadTitleGenerationResult {
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationInput {
|
||||
cwd: string;
|
||||
title: string;
|
||||
/** Active threads (running session or awaiting the user) never get a settle
|
||||
recommendation. */
|
||||
isActive: boolean;
|
||||
firstUserMessage: string | null;
|
||||
recentMessages: ReadonlyArray<{ role: "user" | "assistant" | "system"; text: string }>;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationResult {
|
||||
summary: string;
|
||||
/** Null when the current title is still accurate. */
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
@@ -74,6 +94,7 @@ export interface TextGenerationService {
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
|
||||
generateThreadReview(input: ThreadReviewGenerationInput): Promise<ThreadReviewGenerationResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,6 +130,14 @@ export class TextGeneration extends Context.Service<
|
||||
readonly generateThreadTitle: (
|
||||
input: ThreadTitleGenerationInput,
|
||||
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Review a thread transcript for the work-review sweep: summary,
|
||||
* optional corrected title, and a settle recommendation.
|
||||
*/
|
||||
readonly generateThreadReview: (
|
||||
input: ThreadReviewGenerationInput,
|
||||
) => Effect.Effect<ThreadReviewGenerationResult, TextGenerationError>;
|
||||
}
|
||||
>()("t3/textGeneration/TextGeneration") {}
|
||||
|
||||
@@ -119,7 +148,8 @@ type TextGenerationOp =
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
|
||||
const resolveInstance = (
|
||||
registry: ProviderInstanceRegistry.ProviderInstanceRegistry["Service"],
|
||||
@@ -159,6 +189,10 @@ export const makeTextGenerationFromRegistry = (
|
||||
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
|
||||
),
|
||||
generateThreadReview: (input) =>
|
||||
resolveInstance(registry, "generateThreadReview", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadReview(input)),
|
||||
),
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
|
||||
@@ -4,9 +4,14 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
@@ -136,6 +141,89 @@ describe("buildThreadTitlePrompt", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadReviewPrompt", () => {
|
||||
it("includes title, first user message, and transcript", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "New thread",
|
||||
isActive: false,
|
||||
firstUserMessage: "Fix the settle default",
|
||||
recentMessages: [
|
||||
{ role: "user", text: "Fix the settle default" },
|
||||
{ role: "assistant", text: "Done, merged." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Current title: New thread");
|
||||
expect(result.prompt).toContain("Fix the settle default");
|
||||
expect(result.prompt).toContain("[assistant] Done, merged.");
|
||||
expect(result.prompt).not.toContain("ACTIVE");
|
||||
});
|
||||
|
||||
it("adds the never-settle rule for active threads", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "Working thread",
|
||||
isActive: true,
|
||||
firstUserMessage: "Do a thing",
|
||||
recentMessages: [],
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("recommendSettle must be false");
|
||||
expect(result.prompt).toContain("(no messages)");
|
||||
});
|
||||
|
||||
it("caps the transcript to the most recent 20 messages", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "Long thread",
|
||||
isActive: false,
|
||||
firstUserMessage: "start",
|
||||
recentMessages: Array.from({ length: 30 }, (_, index) => ({
|
||||
role: "assistant" as const,
|
||||
text: `message-${index}`,
|
||||
})),
|
||||
});
|
||||
|
||||
expect(result.prompt).not.toContain("message-9\n");
|
||||
expect(result.prompt).toContain("message-10");
|
||||
expect(result.prompt).toContain("message-29");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeThreadReview", () => {
|
||||
const raw = {
|
||||
summary: " Work finished. ",
|
||||
suggestedTitle: '"Ship settle default"',
|
||||
recommendSettle: true,
|
||||
settleReason: " PR merged. ",
|
||||
};
|
||||
|
||||
it("sanitizes fields and keeps settle recommendation for inactive threads", () => {
|
||||
expect(normalizeThreadReview(raw, false)).toEqual({
|
||||
summary: "Work finished.",
|
||||
suggestedTitle: "Ship settle default",
|
||||
recommendSettle: true,
|
||||
settleReason: "PR merged.",
|
||||
});
|
||||
});
|
||||
|
||||
it("forces recommendSettle off for active threads even if the model says settle", () => {
|
||||
const result = normalizeThreadReview(raw, true);
|
||||
expect(result.recommendSettle).toBe(false);
|
||||
expect(result.settleReason).toBeNull();
|
||||
});
|
||||
|
||||
it("drops empty and placeholder title suggestions", () => {
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: " " }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: "New thread" }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: null }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeThreadTitle", () => {
|
||||
it("truncates long titles with the shared sidebar-safe limit", () => {
|
||||
expect(
|
||||
|
||||
@@ -216,3 +216,67 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread review (work-review sweep)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ThreadReviewMessage {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ThreadReviewPromptInput {
|
||||
title: string;
|
||||
/** True when the thread has a running session or pending approvals/input.
|
||||
Active threads must never get a settle recommendation. */
|
||||
isActive: boolean;
|
||||
firstUserMessage: string | null;
|
||||
recentMessages: ReadonlyArray<ThreadReviewMessage>;
|
||||
}
|
||||
|
||||
const THREAD_REVIEW_RECENT_MESSAGE_COUNT = 20;
|
||||
const THREAD_REVIEW_MESSAGE_CHAR_LIMIT = 2_000;
|
||||
|
||||
export function buildThreadReviewPrompt(input: ThreadReviewPromptInput) {
|
||||
const recent = input.recentMessages.slice(-THREAD_REVIEW_RECENT_MESSAGE_COUNT);
|
||||
const transcript = recent
|
||||
.map(
|
||||
(message) =>
|
||||
`[${message.role}] ${limitSection(message.text, THREAD_REVIEW_MESSAGE_CHAR_LIMIT)}`,
|
||||
)
|
||||
.join("\n\n");
|
||||
|
||||
const prompt = [
|
||||
"You review a coding-agent conversation thread and report its state.",
|
||||
"Return a JSON object with keys: summary, suggestedTitle, recommendSettle, settleReason.",
|
||||
"Rules:",
|
||||
"- summary: 1-2 sentences covering what was asked and where the work landed",
|
||||
"- suggestedTitle: a corrected 3-8 word title ONLY if the current title is misleading or a placeholder like 'New thread'; otherwise null",
|
||||
"- recommendSettle: true ONLY when the work clearly concluded (done, abandoned, or superseded) and nothing awaits the user",
|
||||
"- settleReason: one short sentence justifying recommendSettle, or null when recommendSettle is false",
|
||||
"- be conservative: when in doubt, do not suggest a title change and do not recommend settling",
|
||||
...(input.isActive
|
||||
? [
|
||||
"- this thread is still ACTIVE (running or awaiting the user): recommendSettle must be false",
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
`Current title: ${input.title}`,
|
||||
"",
|
||||
"First user message:",
|
||||
limitSection(input.firstUserMessage ?? "(none)", THREAD_REVIEW_MESSAGE_CHAR_LIMIT),
|
||||
"",
|
||||
`Most recent messages (up to ${THREAD_REVIEW_RECENT_MESSAGE_COUNT}):`,
|
||||
limitSection(transcript.length > 0 ? transcript : "(no messages)", 24_000),
|
||||
].join("\n");
|
||||
|
||||
const outputSchema = Schema.Struct({
|
||||
summary: Schema.String,
|
||||
suggestedTitle: Schema.NullOr(Schema.String),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
@@ -63,6 +63,43 @@ export function sanitizeThreadTitle(raw: string): string {
|
||||
return `${normalized.slice(0, 47).trimEnd()}...`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a raw thread-review generation into the service result shape:
|
||||
* collapse whitespace, drop empty/no-op title suggestions, and force
|
||||
* `recommendSettle` off for active threads regardless of model output.
|
||||
*/
|
||||
export function normalizeThreadReview(
|
||||
raw: {
|
||||
summary: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
},
|
||||
isActive: boolean,
|
||||
): {
|
||||
summary: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
} {
|
||||
const summary = raw.summary.trim().replace(/\s+/g, " ");
|
||||
const suggestedTitle =
|
||||
raw.suggestedTitle && raw.suggestedTitle.trim().length > 0
|
||||
? sanitizeThreadTitle(raw.suggestedTitle)
|
||||
: null;
|
||||
const recommendSettle = raw.recommendSettle && !isActive;
|
||||
const settleReason =
|
||||
recommendSettle && raw.settleReason && raw.settleReason.trim().length > 0
|
||||
? raw.settleReason.trim().replace(/\s+/g, " ")
|
||||
: null;
|
||||
return {
|
||||
summary: summary.length > 0 ? summary : "No summary available.",
|
||||
suggestedTitle: suggestedTitle === "New thread" ? null : suggestedTitle,
|
||||
recommendSettle,
|
||||
settleReason,
|
||||
};
|
||||
}
|
||||
|
||||
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
|
||||
function cliLabel(cliName: string): string {
|
||||
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
|
||||
|
||||
@@ -332,6 +332,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsInit, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope],
|
||||
[WS_METHODS.reviewSummarizeThread, AuthReviewWriteScope],
|
||||
[WS_METHODS.terminalOpen, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalAttach, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalWrite, AuthTerminalOperateScope],
|
||||
@@ -1852,6 +1853,10 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.reviewSummarizeThread]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.reviewSummarizeThread, review.summarizeThread(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
FolderPlusIcon,
|
||||
GitBranchIcon,
|
||||
EllipsisIcon,
|
||||
ListChecksIcon,
|
||||
MessageSquareIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
@@ -70,6 +71,7 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { startReviewSweep } from "../reviewSweepStore";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
@@ -1739,6 +1741,12 @@ export default function SidebarV2() {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
}, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]);
|
||||
|
||||
const handleReviewSweepClick = useCallback(() => {
|
||||
if (isMobile) setOpenMobile(false);
|
||||
startReviewSweep();
|
||||
void router.navigate({ to: "/review-sweep" });
|
||||
}, [isMobile, router, setOpenMobile]);
|
||||
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle");
|
||||
// Same resolution as v1: prefer the local-thread binding, fall back to
|
||||
// chat.new, no platform gating — web users have working shortcuts too.
|
||||
@@ -1772,6 +1780,29 @@ export default function SidebarV2() {
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
className="relative size-8 justify-center rounded-md border-0 bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={handleReviewSweepClick}
|
||||
disabled={projects.length === 0}
|
||||
aria-label="Review unsettled work"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ListChecksIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">Review unsettled work</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ProjectId } from "@t3tools/contracts";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { ArrowRightIcon, ListChecksIcon, RotateCcwIcon, XIcon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import {
|
||||
applyAllSweepRecommendations,
|
||||
applySweepSettle,
|
||||
applySweepTitle,
|
||||
dismissSweepItem,
|
||||
retrySweepItem,
|
||||
startReviewSweep,
|
||||
useReviewSweepStore,
|
||||
type SweepItem,
|
||||
} from "../../reviewSweepStore";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { buildThreadRouteParams } from "../../threadRoutes";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Card } from "../ui/card";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
|
||||
import { SidebarInset } from "../ui/sidebar";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
|
||||
function SweepRecommendationBadge({ item }: { item: SweepItem }) {
|
||||
if (item.status === "error") {
|
||||
return <Badge variant="error">Review failed</Badge>;
|
||||
}
|
||||
if (item.status !== "done" || item.result === null) {
|
||||
return null;
|
||||
}
|
||||
if (item.result.recommendSettle) {
|
||||
return item.settleApplied ? (
|
||||
<Badge variant="outline">Settled</Badge>
|
||||
) : (
|
||||
<Badge variant="success">Recommend settle</Badge>
|
||||
);
|
||||
}
|
||||
return <Badge variant="secondary">Keep active</Badge>;
|
||||
}
|
||||
|
||||
function SweepItemCard({ item }: { item: SweepItem }) {
|
||||
const key = scopedThreadKey(item.ref);
|
||||
const [applyingTitle, setApplyingTitle] = useState(false);
|
||||
const [applyingSettle, setApplyingSettle] = useState(false);
|
||||
const result = item.result;
|
||||
|
||||
return (
|
||||
<Card className="gap-2 p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{item.status === "pending" || item.status === "running" ? (
|
||||
<Spinner className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
) : null}
|
||||
<Link
|
||||
to="/$environmentId/$threadId"
|
||||
params={buildThreadRouteParams(item.ref)}
|
||||
className="truncate text-sm font-medium text-foreground hover:underline"
|
||||
>
|
||||
{item.threadTitle}
|
||||
</Link>
|
||||
<SweepRecommendationBadge item={item} />
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="ms-auto shrink-0 text-muted-foreground"
|
||||
aria-label="Dismiss recommendation"
|
||||
onClick={() => dismissSweepItem(key)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{item.status === "error" ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="min-w-0 flex-1 truncate">{item.errorMessage}</span>
|
||||
<Button size="xs" variant="outline" onClick={() => retrySweepItem(key)}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{result !== null ? (
|
||||
<p className="text-sm text-muted-foreground">{result.summary}</p>
|
||||
) : item.status !== "error" ? (
|
||||
<p className="text-sm text-muted-foreground/60">Reviewing…</p>
|
||||
) : null}
|
||||
|
||||
{result?.suggestedTitle && !item.titleApplied ? (
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground/70">
|
||||
Title
|
||||
</span>
|
||||
<span className="text-muted-foreground line-through">{item.threadTitle}</span>
|
||||
<ArrowRightIcon className="size-3.5 text-muted-foreground/70" />
|
||||
<span className="font-medium text-foreground">{result.suggestedTitle}</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="ms-auto"
|
||||
disabled={applyingTitle}
|
||||
onClick={() => {
|
||||
setApplyingTitle(true);
|
||||
void applySweepTitle(key).finally(() => setApplyingTitle(false));
|
||||
}}
|
||||
>
|
||||
Apply title
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{result?.suggestedTitle && item.titleApplied ? (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Renamed to <span className="font-medium text-foreground">{result.suggestedTitle}</span>.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{result?.recommendSettle && !item.settleApplied ? (
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground/70">
|
||||
Settle
|
||||
</span>
|
||||
<span className="italic text-muted-foreground">
|
||||
{result.settleReason ?? "Work appears concluded."}
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="ms-auto"
|
||||
disabled={applyingSettle}
|
||||
onClick={() => {
|
||||
setApplyingSettle(true);
|
||||
void applySweepSettle(key).finally(() => setApplyingSettle(false));
|
||||
}}
|
||||
>
|
||||
Settle thread
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReviewSweepView() {
|
||||
const phase = useReviewSweepStore((state) => state.phase);
|
||||
const order = useReviewSweepStore((state) => state.order);
|
||||
const items = useReviewSweepStore((state) => state.items);
|
||||
const truncatedCount = useReviewSweepStore((state) => state.truncatedCount);
|
||||
const projects = useProjects();
|
||||
|
||||
const projectTitles = useMemo(() => {
|
||||
const titles = new Map<ProjectId, string>();
|
||||
for (const project of projects) {
|
||||
titles.set(project.id, project.title);
|
||||
}
|
||||
return titles;
|
||||
}, [projects]);
|
||||
|
||||
const visibleItems = useMemo(
|
||||
() =>
|
||||
order
|
||||
.map((key) => items[key])
|
||||
.filter((item): item is SweepItem => item !== undefined && !item.dismissed),
|
||||
[items, order],
|
||||
);
|
||||
const groups = useMemo(() => {
|
||||
const byProject = new Map<ProjectId, SweepItem[]>();
|
||||
for (const item of visibleItems) {
|
||||
const group = byProject.get(item.projectId);
|
||||
if (group) {
|
||||
group.push(item);
|
||||
} else {
|
||||
byProject.set(item.projectId, [item]);
|
||||
}
|
||||
}
|
||||
return [...byProject.entries()];
|
||||
}, [visibleItems]);
|
||||
|
||||
const reviewedCount = visibleItems.filter(
|
||||
(item) => item.status === "done" || item.status === "error",
|
||||
).length;
|
||||
const applicableCount = visibleItems.filter(
|
||||
(item) =>
|
||||
(item.result?.suggestedTitle && !item.titleApplied) ||
|
||||
(item.result?.recommendSettle && !item.settleApplied),
|
||||
).length;
|
||||
const running = phase === "running";
|
||||
const [applyingAll, setApplyingAll] = useState(false);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border/60 px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-7 items-center gap-3 sm:min-h-6">
|
||||
<span className="text-sm font-medium text-foreground">Work review</span>
|
||||
{phase !== "idle" ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{running ? (
|
||||
<>
|
||||
{reviewedCount} of {visibleItems.length} reviewed
|
||||
</>
|
||||
) : (
|
||||
<>{visibleItems.length} threads reviewed</>
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
<div className="ms-auto flex items-center gap-2">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={running}
|
||||
onClick={() => startReviewSweep()}
|
||||
>
|
||||
<RotateCcwIcon className="mx-1 size-3.5" />
|
||||
{phase === "idle" ? "Start review" : "Re-run"}
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={running || applyingAll || applicableCount === 0}
|
||||
onClick={() => {
|
||||
setApplyingAll(true);
|
||||
void applyAllSweepRecommendations().finally(() => setApplyingAll(false));
|
||||
}}
|
||||
>
|
||||
Apply all{applicableCount > 0 ? ` (${applicableCount})` : ""}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-4 sm:px-5">
|
||||
{visibleItems.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>
|
||||
{phase === "idle" ? "Review your in-progress work" : "All caught up"}
|
||||
</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{phase === "idle"
|
||||
? "Run a sweep to summarize every unsettled thread, catch stale titles, and find threads ready to settle."
|
||||
: "No unsettled threads to review right now."}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
{phase === "idle" ? (
|
||||
<Button size="sm" onClick={() => startReviewSweep()}>
|
||||
<ListChecksIcon className="me-1.5 size-4" />
|
||||
Review unsettled work
|
||||
</Button>
|
||||
) : null}
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
|
||||
{truncatedCount > 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Reviewing the {visibleItems.length} most recent threads; {truncatedCount} more
|
||||
were skipped this run.
|
||||
</p>
|
||||
) : null}
|
||||
{groups.map(([projectId, groupItems]) => (
|
||||
<section key={projectId} className="flex flex-col gap-2">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground/70">
|
||||
{projectTitles.get(projectId) ?? "Unknown project"}
|
||||
<span className="ms-2 font-normal normal-case tracking-normal">
|
||||
· {groupItems.length} {groupItems.length === 1 ? "thread" : "threads"}
|
||||
</span>
|
||||
</h2>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{groupItems.map((item) => (
|
||||
<SweepItemCard key={scopedThreadKey(item.ref)} item={item} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
canSettle,
|
||||
effectiveSettled,
|
||||
threadLastActivityAt,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ReviewThreadSummaryResult,
|
||||
ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
|
||||
import { stackedThreadToast, toastManager } from "./components/ui/toast";
|
||||
import { getClientSettings } from "./hooks/useSettings";
|
||||
import { appAtomRegistry } from "./rpc/atomRegistry";
|
||||
import { readThreadShell, readThreadRefs } from "./state/entities";
|
||||
import { reviewEnvironment } from "./state/review";
|
||||
import { environmentServerConfigsAtom } from "./state/server";
|
||||
import { threadEnvironment } from "./state/threads";
|
||||
|
||||
const SWEEP_CONCURRENCY = 3;
|
||||
/** Soft cap so a giant backlog doesn't spawn an unbounded number of LLM
|
||||
generations in one click. */
|
||||
export const SWEEP_MAX_THREADS = 50;
|
||||
|
||||
export type SweepItemStatus = "pending" | "running" | "done" | "error";
|
||||
|
||||
export interface SweepItem {
|
||||
readonly ref: ScopedThreadRef;
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadTitle: string;
|
||||
readonly status: SweepItemStatus;
|
||||
readonly result: ReviewThreadSummaryResult | null;
|
||||
readonly errorMessage: string | null;
|
||||
readonly titleApplied: boolean;
|
||||
readonly settleApplied: boolean;
|
||||
readonly dismissed: boolean;
|
||||
}
|
||||
|
||||
export type SweepPhase = "idle" | "running" | "complete";
|
||||
|
||||
interface ReviewSweepState {
|
||||
phase: SweepPhase;
|
||||
runId: number;
|
||||
/** Scoped thread keys in review order. */
|
||||
order: ReadonlyArray<string>;
|
||||
items: Readonly<Record<string, SweepItem>>;
|
||||
/** Count of candidates dropped by SWEEP_MAX_THREADS (0 = full coverage). */
|
||||
truncatedCount: number;
|
||||
startRun: (input: {
|
||||
runId: number;
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
truncatedCount: number;
|
||||
}) => void;
|
||||
patchItem: (key: string, patch: Partial<SweepItem>) => void;
|
||||
finishRun: (runId: number) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export const useReviewSweepStore = create<ReviewSweepState>((set) => ({
|
||||
phase: "idle",
|
||||
runId: 0,
|
||||
order: [],
|
||||
items: {},
|
||||
truncatedCount: 0,
|
||||
startRun: ({ runId, items, truncatedCount }) =>
|
||||
set({
|
||||
phase: "running",
|
||||
runId,
|
||||
order: items.map((item) => scopedThreadKey(item.ref)),
|
||||
items: Object.fromEntries(items.map((item) => [scopedThreadKey(item.ref), item])),
|
||||
truncatedCount,
|
||||
}),
|
||||
patchItem: (key, patch) =>
|
||||
set((state) => {
|
||||
const existing = state.items[key];
|
||||
if (!existing) return state;
|
||||
return { items: { ...state.items, [key]: { ...existing, ...patch } } };
|
||||
}),
|
||||
finishRun: (runId) => set((state) => (state.runId === runId ? { phase: "complete" } : state)),
|
||||
reset: () => set({ phase: "idle", order: [], items: {}, truncatedCount: 0 }),
|
||||
}));
|
||||
|
||||
function readServerCapabilities(environmentId: EnvironmentId) {
|
||||
return appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
|
||||
.capabilities;
|
||||
}
|
||||
|
||||
/** All unsettled, unarchived threads across every connected environment that
|
||||
supports the sweep, mirroring SidebarV2's active-card predicate. */
|
||||
function collectSweepCandidates(): EnvironmentThreadShell[] {
|
||||
const now = new Date().toISOString();
|
||||
const autoSettleAfterDays = getClientSettings().sidebarAutoSettleAfterDays;
|
||||
const candidates: EnvironmentThreadShell[] = [];
|
||||
for (const ref of readThreadRefs()) {
|
||||
const shell = readThreadShell(ref);
|
||||
if (!shell || shell.archivedAt !== null) continue;
|
||||
const capabilities = readServerCapabilities(shell.environmentId);
|
||||
if (capabilities?.threadSettlement !== true || capabilities.reviewSweep !== true) continue;
|
||||
// PR state is owned by per-row VCS subscriptions in the sidebar and isn't
|
||||
// readable here; passing null may include a few threads the sidebar shows
|
||||
// as settled (merged PR + idle). Reviewing them is harmless.
|
||||
if (effectiveSettled(shell, { now, autoSettleAfterDays, changeRequestState: null })) continue;
|
||||
candidates.push(shell);
|
||||
}
|
||||
// Most recently active first, so the SWEEP_MAX_THREADS cap drops the
|
||||
// longest-idle threads rather than the oldest-created ones.
|
||||
candidates.sort(
|
||||
(a, b) =>
|
||||
Date.parse(threadLastActivityAt(b) ?? b.createdAt) -
|
||||
Date.parse(threadLastActivityAt(a) ?? a.createdAt),
|
||||
);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
async function reviewOne(runId: number, item: SweepItem): Promise<void> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return;
|
||||
const key = scopedThreadKey(item.ref);
|
||||
store.patchItem(key, { status: "running" });
|
||||
|
||||
const shell = readThreadShell(item.ref);
|
||||
const canSettleNow = shell !== null && canSettle(shell, { now: new Date().toISOString() });
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
reviewEnvironment.summarizeThread,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId, canSettleNow },
|
||||
},
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
if (result._tag === "Success") {
|
||||
current.patchItem(key, { status: "done", result: result.value, errorMessage: null });
|
||||
} else {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
current.patchItem(key, {
|
||||
status: "error",
|
||||
errorMessage: error instanceof Error ? error.message : "Review failed.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function runPool(runId: number, items: ReadonlyArray<SweepItem>): Promise<void> {
|
||||
let next = 0;
|
||||
const workers = Array.from({ length: Math.min(SWEEP_CONCURRENCY, items.length) }, async () => {
|
||||
while (next < items.length) {
|
||||
if (useReviewSweepStore.getState().runId !== runId) return;
|
||||
const item = items[next];
|
||||
next += 1;
|
||||
if (item) await reviewOne(runId, item);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
useReviewSweepStore.getState().finishRun(runId);
|
||||
}
|
||||
|
||||
/** Kick off a sweep over every unsettled thread. Runs outside React so it
|
||||
survives navigation; results land in the store as they arrive. */
|
||||
export function startReviewSweep(): void {
|
||||
const runId = useReviewSweepStore.getState().runId + 1;
|
||||
const candidates = collectSweepCandidates();
|
||||
const reviewed = candidates.slice(0, SWEEP_MAX_THREADS);
|
||||
const items = reviewed.map(
|
||||
(shell): SweepItem => ({
|
||||
ref: scopeThreadRef(shell.environmentId, shell.id),
|
||||
projectId: shell.projectId,
|
||||
threadTitle: shell.title,
|
||||
status: "pending",
|
||||
result: null,
|
||||
errorMessage: null,
|
||||
titleApplied: false,
|
||||
settleApplied: false,
|
||||
dismissed: false,
|
||||
}),
|
||||
);
|
||||
useReviewSweepStore.getState().startRun({
|
||||
runId,
|
||||
items,
|
||||
truncatedCount: candidates.length - reviewed.length,
|
||||
});
|
||||
if (items.length === 0) {
|
||||
useReviewSweepStore.getState().finishRun(runId);
|
||||
return;
|
||||
}
|
||||
void runPool(runId, items);
|
||||
}
|
||||
|
||||
export function retrySweepItem(key: string): void {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const item = store.items[key];
|
||||
if (!item || item.status === "running") return;
|
||||
void reviewOne(store.runId, item);
|
||||
}
|
||||
|
||||
export async function applySweepTitle(key: string): Promise<boolean> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const item = store.items[key];
|
||||
const suggestedTitle = item?.result?.suggestedTitle;
|
||||
if (!item || !suggestedTitle || item.titleApplied) return false;
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.updateMetadata,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId, title: suggestedTitle },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to rename thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
useReviewSweepStore
|
||||
.getState()
|
||||
.patchItem(key, { titleApplied: true, threadTitle: suggestedTitle });
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function applySweepSettle(key: string): Promise<boolean> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const item = store.items[key];
|
||||
if (!item || !item.result?.recommendSettle || item.settleApplied) return false;
|
||||
// Re-check against the live shell: the thread may have gone active since
|
||||
// the review ran, and settling live work would hide it.
|
||||
const shell = readThreadShell(item.ref);
|
||||
if (!shell || !canSettle(shell, { now: new Date().toISOString() })) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Thread is active again",
|
||||
description: "This thread picked up new activity since the review, so it stays active.",
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.settle,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to settle thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
useReviewSweepStore.getState().patchItem(key, { settleApplied: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sequentially apply every un-dismissed recommendation: titles first, then
|
||||
settles, tolerating per-item failures (each failure already toasts). */
|
||||
export async function applyAllSweepRecommendations(): Promise<void> {
|
||||
const { order, items } = useReviewSweepStore.getState();
|
||||
for (const key of order) {
|
||||
const item = items[key];
|
||||
if (!item || item.dismissed) continue;
|
||||
if (item.result?.suggestedTitle && !item.titleApplied) {
|
||||
await applySweepTitle(key);
|
||||
}
|
||||
}
|
||||
for (const key of order) {
|
||||
const item = useReviewSweepStore.getState().items[key];
|
||||
if (!item || item.dismissed) continue;
|
||||
if (item.result?.recommendSettle && !item.settleApplied) {
|
||||
await applySweepSettle(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function dismissSweepItem(key: string): void {
|
||||
useReviewSweepStore.getState().patchItem(key, { dismissed: true });
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as ReviewSweepRouteImport } from './routes/review-sweep'
|
||||
import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ConnectRouteImport } from './routes/connect'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
@@ -31,6 +32,11 @@ const SettingsRoute = SettingsRouteImport.update({
|
||||
path: '/settings',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ReviewSweepRoute = ReviewSweepRouteImport.update({
|
||||
id: '/review-sweep',
|
||||
path: '/review-sweep',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const PairRoute = PairRouteImport.update({
|
||||
id: '/pair',
|
||||
path: '/pair',
|
||||
@@ -111,6 +117,7 @@ export interface FileRoutesByFullPath {
|
||||
'/': typeof ChatIndexRoute
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -127,6 +134,7 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -146,6 +154,7 @@ export interface FileRoutesById {
|
||||
'/_chat': typeof ChatRouteWithChildren
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -166,6 +175,7 @@ export interface FileRouteTypes {
|
||||
| '/'
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
@@ -182,6 +192,7 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
@@ -200,6 +211,7 @@ export interface FileRouteTypes {
|
||||
| '/_chat'
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect_/callback'
|
||||
| '/settings/archived'
|
||||
@@ -219,6 +231,7 @@ export interface RootRouteChildren {
|
||||
ChatRoute: typeof ChatRouteWithChildren
|
||||
ConnectRoute: typeof ConnectRoute
|
||||
PairRoute: typeof PairRoute
|
||||
ReviewSweepRoute: typeof ReviewSweepRoute
|
||||
SettingsRoute: typeof SettingsRouteWithChildren
|
||||
ConnectCallbackRoute: typeof ConnectCallbackRoute
|
||||
}
|
||||
@@ -232,6 +245,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/review-sweep': {
|
||||
id: '/review-sweep'
|
||||
path: '/review-sweep'
|
||||
fullPath: '/review-sweep'
|
||||
preLoaderRoute: typeof ReviewSweepRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/pair': {
|
||||
id: '/pair'
|
||||
path: '/pair'
|
||||
@@ -384,6 +404,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ChatRoute: ChatRouteWithChildren,
|
||||
ConnectRoute: ConnectRoute,
|
||||
PairRoute: PairRoute,
|
||||
ReviewSweepRoute: ReviewSweepRoute,
|
||||
SettingsRoute: SettingsRouteWithChildren,
|
||||
ConnectCallbackRoute: ConnectCallbackRoute,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
|
||||
import { ReviewSweepView } from "../components/reviewSweep/ReviewSweepView";
|
||||
|
||||
export const Route = createFileRoute("/review-sweep")({
|
||||
beforeLoad: async ({ context }) => {
|
||||
if (
|
||||
context.authGateState.status !== "authenticated" &&
|
||||
context.authGateState.status !== "hosted-static"
|
||||
) {
|
||||
throw redirect({ to: "/pair", replace: true });
|
||||
}
|
||||
},
|
||||
component: ReviewSweepView,
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
|
||||
export function createReviewEnvironmentAtoms<R, E>(
|
||||
@@ -13,5 +13,9 @@ export function createReviewEnvironmentAtoms<R, E>(
|
||||
tag: WS_METHODS.reviewGetDiffPreview,
|
||||
staleTimeMs: 5_000,
|
||||
}),
|
||||
summarizeThread: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:review:summarize-thread",
|
||||
tag: WS_METHODS.reviewSummarizeThread,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -44,6 +44,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
pre-settlement servers, so clients treat missing as unsupported and
|
||||
never send the commands under version skew. */
|
||||
threadSettlement: Schema.optionalKey(Schema.Boolean),
|
||||
/** Server understands the review.summarizeThread RPC used by the sidebar
|
||||
work-review sweep. Absent on older servers, so clients skip their
|
||||
threads instead of sending an unknown method. */
|
||||
reviewSweep: Schema.optionalKey(Schema.Boolean),
|
||||
/** The update path clients should offer for this server. Absent on
|
||||
servers that must be relaunched manually (dev checkouts, Windows
|
||||
foreground runs, pre-update servers). */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { GitCommandError } from "./git.ts";
|
||||
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { GitCommandError, TextGenerationError } from "./git.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const ReviewDiffPreviewInput = Schema.Struct({
|
||||
@@ -34,3 +34,33 @@ export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;
|
||||
|
||||
export const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);
|
||||
export type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;
|
||||
|
||||
export const ReviewThreadSummaryInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** Whether the thread is currently eligible to settle (no running session,
|
||||
pending approvals, or pending user input). The server never recommends
|
||||
settling when this is false, regardless of what the model says. */
|
||||
canSettleNow: Schema.Boolean,
|
||||
});
|
||||
export type ReviewThreadSummaryInput = typeof ReviewThreadSummaryInput.Type;
|
||||
|
||||
export const ReviewThreadSummaryResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
summary: TrimmedNonEmptyString,
|
||||
/** Null when the current title is still accurate. */
|
||||
suggestedTitle: Schema.NullOr(TrimmedNonEmptyString),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ReviewThreadSummaryResult = typeof ReviewThreadSummaryResult.Type;
|
||||
|
||||
export class ReviewThreadNotFoundError extends Schema.TaggedErrorClass<ReviewThreadNotFoundError>()(
|
||||
"ReviewThreadNotFoundError",
|
||||
{ threadId: ThreadId },
|
||||
) {}
|
||||
|
||||
export const ReviewThreadSummaryError = Schema.Union([
|
||||
TextGenerationError,
|
||||
ReviewThreadNotFoundError,
|
||||
]);
|
||||
export type ReviewThreadSummaryError = typeof ReviewThreadSummaryError.Type;
|
||||
@@ -43,6 +43,9 @@ import {
|
||||
ReviewDiffPreviewError,
|
||||
ReviewDiffPreviewInput,
|
||||
ReviewDiffPreviewResult,
|
||||
ReviewThreadSummaryError,
|
||||
ReviewThreadSummaryInput,
|
||||
ReviewThreadSummaryResult,
|
||||
} from "./review.ts";
|
||||
import { KeybindingsConfigError } from "./keybindings.ts";
|
||||
import {
|
||||
@@ -181,6 +184,7 @@ export const WS_METHODS = {
|
||||
|
||||
// Review methods
|
||||
reviewGetDiffPreview: "review.getDiffPreview",
|
||||
reviewSummarizeThread: "review.summarizeThread",
|
||||
|
||||
// Terminal methods
|
||||
terminalOpen: "terminal.open",
|
||||
@@ -495,6 +499,14 @@ export const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPrevie
|
||||
error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
/** One-shot agentic review of a single thread for the sidebar work-review
|
||||
sweep: summary, optional corrected title, and a settle recommendation. */
|
||||
export const WsReviewSummarizeThreadRpc = Rpc.make(WS_METHODS.reviewSummarizeThread, {
|
||||
payload: ReviewThreadSummaryInput,
|
||||
success: ReviewThreadSummaryResult,
|
||||
error: Schema.Union([ReviewThreadSummaryError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
payload: TerminalOpenInput,
|
||||
success: TerminalSessionSnapshot,
|
||||
@@ -738,6 +750,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsVcsSwitchRefRpc,
|
||||
WsVcsInitRpc,
|
||||
WsReviewGetDiffPreviewRpc,
|
||||
WsReviewSummarizeThreadRpc,
|
||||
WsTerminalOpenRpc,
|
||||
WsTerminalAttachRpc,
|
||||
WsTerminalWriteRpc,
|
||||
|
||||
Reference in new issue
Block a user