Compare commits
27
Commits
No files matched your search
@@ -13,13 +13,25 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
|
||||
|
||||
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
|
||||
|
||||
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
### Verify a shared environment before human handoff
|
||||
|
||||
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
|
||||
|
||||
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
@@ -55,7 +67,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
|
||||
@@ -13,6 +13,14 @@
|
||||
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
|
||||
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
|
||||
|
||||
## Dev Servers
|
||||
|
||||
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
|
||||
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
|
||||
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
|
||||
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
|
||||
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
|
||||
import { resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
|
||||
const TEST_SERVER_PORT = 13_773;
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
@@ -19,6 +23,12 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
// Last, so the port cannot be overridden out from under
|
||||
// makeCookieRequest — which builds the cookie name from this constant.
|
||||
// An override that changed it would leave the server reading
|
||||
// t3_session_<other> while every request still sent t3_session_13773,
|
||||
// and the tests would fail for a reason unrelated to what they assert.
|
||||
port: TEST_SERVER_PORT,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
||||
@@ -35,7 +45,11 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
// Derived, not hardcoded: the name is port-scoped so concurrent servers
|
||||
// on one hostname don't share a cookie. Mode and devUrl mirror
|
||||
// ServerConfig.layerTest, so this resolves to whatever the server reads.
|
||||
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
|
||||
sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) =>
|
||||
createPairingLink({
|
||||
scopes: input.scopes,
|
||||
subject: input.subject,
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(input.purpose ? { purpose: input.purpose } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
...(input?.purpose ? { purpose: input.purpose } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
|
||||
issuePairingCredentialForSubject({
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
|
||||
purpose: "startup",
|
||||
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
|
||||
|
||||
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
|
||||
|
||||
@@ -34,6 +34,9 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
// Packaged desktop has no devUrl, but still needs the port scope: it
|
||||
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
|
||||
// instance shares this one's hostname on a different port.
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
@@ -45,6 +48,22 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3774,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
@@ -75,6 +94,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("scopes web session cookies by port only in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
port: 13773,
|
||||
devUrl: new URL("http://127.0.0.1:5733"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -41,6 +41,7 @@ export const make = Effect.gen(function* () {
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
devUrl: config.devUrl,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
/**
|
||||
* "startup" marks the credential the server mints for itself at boot,
|
||||
* which gets the long dev TTL when a dev URL is configured.
|
||||
*/
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
// A dev server's startup token is read off a log by whoever (or whatever) is
|
||||
// driving the session, often minutes later — after a `node --watch` restart, a
|
||||
// detour into another task, or a hand-off to the person actually doing the
|
||||
// testing. Five minutes turns that into a restart-the-server loop for no
|
||||
// security benefit: the token only unlocks a local dev backend, and its holder
|
||||
// could read the log anyway. Same reasoning (and duration) as the desktop
|
||||
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
|
||||
// pairing links and real servers keep the 5-minute default.
|
||||
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -470,6 +470,7 @@ export const make = Effect.gen(function* () {
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
devUrl: serverConfig.devUrl,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -10,15 +10,29 @@ import * as Result from "effect/Result";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
/**
|
||||
* Cookies are scoped by host but *not* by port, so any two servers that can be
|
||||
* live on one hostname at once need separate names — otherwise the second
|
||||
* clobbers the first's session and both sides see "Invalid session token
|
||||
* signature" until someone clears cookies by hand.
|
||||
*
|
||||
* Two populations qualify, for the same reason but from different causes:
|
||||
*
|
||||
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
|
||||
* - **Desktop**, which scans upward from 3773 for a free port and binds
|
||||
* 127.0.0.1, so a second instance lands on a different port and the same host.
|
||||
*
|
||||
* Hosted deployments keep the stable production name: their public port can
|
||||
* change between releases, and scoping it would log every user out.
|
||||
*/
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
readonly devUrl: URL | undefined;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
return input.devUrl === undefined && input.mode !== "desktop"
|
||||
? SESSION_COOKIE_NAME
|
||||
: `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
|
||||
@@ -84,6 +84,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -48,6 +48,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
devAllowedOrigins: [],
|
||||
} as const;
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
|
||||
@@ -95,6 +96,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_DEV_ALLOWED_ORIGINS:
|
||||
"https://host.example.ts.net, https://phone.example.ts.net ",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
@@ -117,6 +120,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
host: "0.0.0.0",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
devAllowedOrigins: ["https://host.example.ts.net", "https://phone.example.ts.net"],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -106,6 +106,15 @@ const EnvServerConfig = Config.all({
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
|
||||
Config.withDefault(""),
|
||||
Config.map((value) =>
|
||||
value
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0),
|
||||
),
|
||||
),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -363,6 +372,7 @@ export const resolveServerConfig = (
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
devAllowedOrigins: env.devAllowedOrigins,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
|
||||
@@ -72,6 +72,7 @@ export class ServerConfig extends Context.Service<
|
||||
readonly baseDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly devAllowedOrigins: ReadonlyArray<string>;
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
@@ -187,6 +188,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
});
|
||||
|
||||
@@ -43,6 +43,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
|
||||
@@ -142,6 +142,7 @@ export const make = Effect.gen(function* () {
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
reviewSweep: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -365,6 +365,7 @@ function createTextGeneration(
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateThreadReview: () => Effect.die("generateThreadReview is not used by GitManager tests"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -4,6 +4,7 @@ import {
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -48,9 +49,17 @@ export const browserApiCorsLayer = Layer.unwrap(
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
//
|
||||
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
|
||||
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
|
||||
// through Vite and is same-origin (no preflight at all), so this is a
|
||||
// safety net for the desktop renderer and any direct-to-backend caller.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
? {
|
||||
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -216,6 +225,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
|
||||
@@ -3,17 +3,85 @@ 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 * as Schema from "effect/Schema";
|
||||
|
||||
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 GitHubCli from "../sourceControl/GitHubCli.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";
|
||||
|
||||
const GhPrViewFixture = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: Schema.String,
|
||||
state: Schema.String,
|
||||
reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
statusCheckRollup: Schema.optionalKey(Schema.Array(Schema.Struct({ conclusion: Schema.String }))),
|
||||
comments: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
author: Schema.Struct({ login: Schema.String }),
|
||||
body: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
const encodeGhPrViewFixture = Schema.encodeUnknownSync(Schema.fromJsonString(GhPrViewFixture));
|
||||
|
||||
function ghPrViewJson(fixture: typeof GhPrViewFixture.Type): string {
|
||||
return encodeGhPrViewFixture(fixture);
|
||||
}
|
||||
|
||||
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>;
|
||||
readonly ghExecute?: GitHubCli.GitHubCli["Service"]["execute"];
|
||||
}) {
|
||||
return ReviewService.layer.pipe(
|
||||
Layer.provide(
|
||||
@@ -28,11 +96,102 @@ 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.",
|
||||
nextStep: "Settle this thread.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Work concluded.",
|
||||
})
|
||||
);
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitHubCli.GitHubCli)({
|
||||
// Threads in these tests have no PR; investigation must degrade to
|
||||
// "no context" without touching gh.
|
||||
execute: input.ghExecute ?? (() => Effect.die("gh not stubbed in this test")),
|
||||
}),
|
||||
),
|
||||
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,
|
||||
// Tests mock getProjectShellById to None, so cwd resolution relies on
|
||||
// the worktree path; a thread with neither now fails loudly by design.
|
||||
worktreePath: "/tmp/t3-review-test-worktree",
|
||||
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 +256,479 @@ 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.",
|
||||
nextStep: "Nothing left — settle this thread.",
|
||||
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.",
|
||||
nextStep: "Wait for the agent.",
|
||||
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.",
|
||||
nextStep: "Settle this thread.",
|
||||
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)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread fails loudly when no workspace cwd can be resolved", () =>
|
||||
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-" });
|
||||
// No worktree and (per the mock) no project shell: cwd is unresolvable.
|
||||
const thread = makeThread({ worktreePath: null });
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review
|
||||
.summarizeThread({ threadId: thread.id, canSettleNow: true })
|
||||
.pipe(Effect.flip);
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread })));
|
||||
|
||||
assert.strictEqual(error._tag, "TextGenerationError");
|
||||
if (error._tag === "TextGenerationError") {
|
||||
assert.match(error.detail, /Unable to resolve a workspace directory/);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread attaches PR status and prompt context when gh finds a PR", () =>
|
||||
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({ branch: "feat/settle-default" });
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 4415,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/4415",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "MERGEABLE",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }, { conclusion: "SKIPPED" }],
|
||||
comments: [
|
||||
{ author: { login: "reviewer" }, body: "LGTM", createdAt: "2026-07-24T00:00:00Z" },
|
||||
],
|
||||
});
|
||||
|
||||
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,
|
||||
ghExecute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghPayload,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.prStatus?.number, 4415);
|
||||
assert.strictEqual(result.prStatus?.state, "open");
|
||||
assert.strictEqual(result.prStatus?.mergeReady, true);
|
||||
assert.strictEqual(result.prStatus?.checksPassing, true);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest?.number, 4415);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest?.recentComments[0]?.body, "LGTM");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread degrades to no PR context when gh fails", () =>
|
||||
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({ branch: "feat/no-pr" });
|
||||
|
||||
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,
|
||||
ghExecute: (ghInput) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: ghInput.cwd,
|
||||
cause: "gh missing in test",
|
||||
}) as never,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.prStatus, undefined);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest, undefined);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("mergePullRequest reports conflict when the branch no longer merges cleanly", () =>
|
||||
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 thread = makeThread({ branch: "feat/conflicting" });
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 77,
|
||||
url: "https://github.com/x/y/pull/77",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "CONFLICTING",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }],
|
||||
comments: [],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 77 });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
ghExecute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghPayload,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.outcome, "conflict");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("mergePullRequest merges and reports merged for a ready PR", () =>
|
||||
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 thread = makeThread({ branch: "feat/ready" });
|
||||
const ghCalls: string[] = [];
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 88,
|
||||
url: "https://github.com/x/y/pull/88",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "MERGEABLE",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }],
|
||||
comments: [],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 88 });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
ghExecute: (ghInput) => {
|
||||
ghCalls.push(ghInput.args.join(" "));
|
||||
return Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghInput.args[1] === "view" ? ghPayload : "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.outcome, "merged");
|
||||
assert.ok(ghCalls.some((call) => call.startsWith("pr merge 88")));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread sums diff stats across every ready checkpoint", () =>
|
||||
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-" });
|
||||
// Checkpoint files are per-TURN deltas, so a multi-turn thread's real
|
||||
// size is the sum — with files deduped by path across turns.
|
||||
const thread = makeThread({
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: "turn_1",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: "ref_1",
|
||||
status: "ready",
|
||||
files: [
|
||||
{ path: "a.ts", kind: "modified", additions: 10, deletions: 2 },
|
||||
{ path: "b.ts", kind: "added", additions: 5, deletions: 0 },
|
||||
],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
turnId: "turn_2",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: "ref_2",
|
||||
status: "ready",
|
||||
files: [{ path: "a.ts", kind: "modified", additions: 3, deletions: 1 }],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-07-20T00:01:00.000Z",
|
||||
},
|
||||
] as unknown as OrchestrationThread["checkpoints"],
|
||||
});
|
||||
|
||||
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 })));
|
||||
|
||||
assert.deepStrictEqual(result.diffStats, { files: 2, additions: 18, deletions: 3 });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread uses the client's model selection when provided", () =>
|
||||
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 clientModel = {
|
||||
instanceId: "claudeAgent",
|
||||
model: "claude-opus-5",
|
||||
options: [],
|
||||
} as unknown as NonNullable<TextGeneration.ThreadReviewGenerationInput["modelSelection"]>;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({
|
||||
threadId: thread.id,
|
||||
canSettleNow: true,
|
||||
modelSelection: clientModel,
|
||||
});
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread, reviewCalls })));
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.modelSelection.model, "claude-opus-5");
|
||||
assert.strictEqual(reviewCalls[0]?.modelSelection.instanceId, "claudeAgent");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread falls back to the server text-gen model", () =>
|
||||
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({});
|
||||
|
||||
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 })));
|
||||
|
||||
// No client model → whatever the server settings carry.
|
||||
assert.ok((reviewCalls[0]?.modelSelection.model.length ?? 0) > 0);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread treats a queued turn start as active", () =>
|
||||
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: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
// A just-sent user message with no adopting turn: session still
|
||||
// null, but the thread has in-flight work. it.effect runs on the
|
||||
// TestClock (epoch 0), so "just sent" is the epoch.
|
||||
shellOverrides: {
|
||||
latestUserMessageAt: "1970-01-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
session: null,
|
||||
},
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Looks finished.",
|
||||
nextStep: "Settle this thread.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Done.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -3,17 +3,35 @@ 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 * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ReviewMergeError,
|
||||
ReviewThreadNotFoundError,
|
||||
TextGenerationError,
|
||||
VcsRepositoryDetectionError,
|
||||
VcsUnsupportedOperationError,
|
||||
type ReviewDiffPreviewError,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
type ReviewMergePullRequestError,
|
||||
type ReviewMergePullRequestInput,
|
||||
type ReviewMergePullRequestResult,
|
||||
type ReviewThreadPrStatus,
|
||||
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 GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
@@ -23,15 +41,192 @@ export class ReviewService extends Context.Service<
|
||||
readonly getDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
|
||||
readonly summarizeThread: (
|
||||
input: ReviewThreadSummaryInput,
|
||||
) => Effect.Effect<ReviewThreadSummaryResult, ReviewThreadSummaryError>;
|
||||
readonly mergePullRequest: (
|
||||
input: ReviewMergePullRequestInput,
|
||||
) => Effect.Effect<ReviewMergePullRequestResult, ReviewMergePullRequestError>;
|
||||
}
|
||||
>()("t3/review/ReviewService") {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR investigation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Shape of `gh pr view --json <fields>` we rely on. Decoded leniently:
|
||||
a schema miss degrades to "no PR context", never a failed review. */
|
||||
const GhPrView = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: Schema.String,
|
||||
state: Schema.String,
|
||||
reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
statusCheckRollup: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Array(Schema.Struct({ conclusion: Schema.optionalKey(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
),
|
||||
comments: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
author: Schema.optionalKey(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
|
||||
body: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
const decodeGhPrView = Schema.decodeUnknownEffect(Schema.fromJsonString(GhPrView));
|
||||
|
||||
const GH_PR_VIEW_FIELDS = "number,url,state,reviewDecision,mergeable,statusCheckRollup,comments";
|
||||
const PR_COMMENT_CONTEXT_COUNT = 5;
|
||||
const PR_COMMENT_CHAR_LIMIT = 500;
|
||||
|
||||
export interface ThreadPrContext {
|
||||
readonly status: ReviewThreadPrStatus;
|
||||
/** Pre-rendered recent-comments block for the review prompt. */
|
||||
readonly recentComments: ReadonlyArray<{
|
||||
readonly author: string;
|
||||
readonly createdAt: string;
|
||||
readonly body: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function ghStateToPrState(state: string): "open" | "closed" | "merged" | null {
|
||||
const normalized = state.trim().toUpperCase();
|
||||
if (normalized === "OPEN") return "open";
|
||||
if (normalized === "CLOSED") return "closed";
|
||||
if (normalized === "MERGED") return "merged";
|
||||
return null;
|
||||
}
|
||||
|
||||
function rollupToChecksPassing(
|
||||
rollup: ReadonlyArray<{ conclusion?: string | null }> | null | undefined,
|
||||
): boolean | null {
|
||||
if (!rollup || rollup.length === 0) return null;
|
||||
// Neutral/skipped conclusions don't block; pending (null conclusion on some
|
||||
// check types) and failures do.
|
||||
const blocking = rollup.some((check) => {
|
||||
const conclusion = check.conclusion?.trim().toUpperCase() ?? "";
|
||||
return !["SUCCESS", "NEUTRAL", "SKIPPED"].includes(conclusion);
|
||||
});
|
||||
return !blocking;
|
||||
}
|
||||
|
||||
function toPrStatus(view: typeof GhPrView.Type): ReviewThreadPrStatus | null {
|
||||
const state = ghStateToPrState(view.state);
|
||||
if (state === null) return null;
|
||||
const reviewDecision = view.reviewDecision?.trim() || null;
|
||||
const checksPassing = rollupToChecksPassing(view.statusCheckRollup ?? null);
|
||||
const mergeable =
|
||||
view.mergeable == null
|
||||
? null
|
||||
: view.mergeable.trim().toUpperCase() === "MERGEABLE"
|
||||
? true
|
||||
: view.mergeable.trim().toUpperCase() === "CONFLICTING"
|
||||
? false
|
||||
: null;
|
||||
const mergeReady =
|
||||
state === "open" &&
|
||||
mergeable === true &&
|
||||
checksPassing !== false &&
|
||||
reviewDecision !== "CHANGES_REQUESTED" &&
|
||||
reviewDecision !== "REVIEW_REQUIRED";
|
||||
return {
|
||||
number: view.number,
|
||||
url: view.url,
|
||||
state,
|
||||
reviewDecision,
|
||||
checksPassing,
|
||||
mergeable,
|
||||
mergeReady,
|
||||
recentCommentCount: view.comments?.length ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Mirrors QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts and
|
||||
// the decider's thread.settle guard.
|
||||
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/** A user message no turn has adopted yet is in-flight work even though the
|
||||
session is still null. Mirrors the decider's settle guard and the
|
||||
client's hasQueuedTurnStart: newest user message strictly newer than
|
||||
every latestTurn timestamp, within the adoption grace window, and not
|
||||
already surfaced as a failed session start. */
|
||||
function hasQueuedTurnStart(
|
||||
shell: {
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string | null;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
nowMs: number,
|
||||
): boolean {
|
||||
if (shell.latestUserMessageAt === null) return false;
|
||||
if (shell.session?.status === "error") return false;
|
||||
const messageAt = Date.parse(shell.latestUserMessageAt);
|
||||
if (Number.isNaN(messageAt)) return false;
|
||||
// Bounded on both sides: message timestamps originate on client devices,
|
||||
// so a clock ahead of the server must not hold the queued state open.
|
||||
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
|
||||
const turn = shell.latestTurn;
|
||||
if (turn === null) return true;
|
||||
return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
|
||||
(candidate) => candidate === null || Date.parse(candidate) < messageAt,
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
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 gitHubCli = yield* GitHubCli.GitHubCli;
|
||||
|
||||
/** Look up the thread branch's PR with one `gh pr view`. Every failure —
|
||||
no PR, gh unauthenticated, schema drift — degrades to null: PR context
|
||||
enriches a review but must never fail it. */
|
||||
const investigateThreadPr = Effect.fn("ReviewService.investigateThreadPr")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.fn.Return<ThreadPrContext | null, never> {
|
||||
const context = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: ["pr", "view", branch, "--json", GH_PR_VIEW_FIELDS],
|
||||
timeoutMs: 20_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((output) => decodeGhPrView(output.stdout)),
|
||||
Effect.map((view): ThreadPrContext | null => {
|
||||
const status = toPrStatus(view);
|
||||
if (status === null) return null;
|
||||
const recentComments = (view.comments ?? [])
|
||||
.slice(-PR_COMMENT_CONTEXT_COUNT)
|
||||
.map((comment) => ({
|
||||
author: comment.author?.login ?? "unknown",
|
||||
createdAt: comment.createdAt,
|
||||
body:
|
||||
comment.body.length > PR_COMMENT_CHAR_LIMIT
|
||||
? `${comment.body.slice(0, PR_COMMENT_CHAR_LIMIT)}…`
|
||||
: comment.body,
|
||||
}));
|
||||
return { status, recentComments };
|
||||
}),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return context;
|
||||
});
|
||||
|
||||
const canonicalizePath = (value: string) => {
|
||||
const resolvedPath = path.resolve(value);
|
||||
@@ -106,8 +301,258 @@ 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));
|
||||
// No silent process.cwd() fallback: the cwd is handed to the provider
|
||||
// CLI spawn, which reads local context files (AGENTS.md, CLAUDE.md) from
|
||||
// it — reviewing "the server's own directory" would leak unrelated
|
||||
// content into an external LLM prompt. Fail the item instead; the client
|
||||
// shows it as a retry-able error card.
|
||||
const cwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: Option.isSome(projectOption) ? [projectOption.value] : [],
|
||||
});
|
||||
if (cwd === undefined) {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: `Unable to resolve a workspace directory for thread '${input.threadId}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
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.
|
||||
// The shell is deliberately read AFTER the transcript: the two reads are
|
||||
// separate transactions, and reading the activity view last means a
|
||||
// session starting in between is still caught. The reverse skew (activity
|
||||
// ending in between) only staleness-affects the summary text — an actual
|
||||
// settle is re-validated by the client at apply time and by the decider's
|
||||
// thread.settle guards, so a recommendation can never settle live work.
|
||||
const shellOption = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
const shell = Option.isSome(shellOption) ? shellOption.value : null;
|
||||
const now = yield* DateTime.now;
|
||||
const serverSideActive =
|
||||
shell === null ||
|
||||
shell.hasPendingApprovals ||
|
||||
shell.hasPendingUserInput ||
|
||||
shell.session?.status === "starting" ||
|
||||
shell.session?.status === "running" ||
|
||||
hasQueuedTurnStart(shell, DateTime.toEpochMillis(now));
|
||||
const canSettleNow = input.canSettleNow && !serverSideActive;
|
||||
const isActive = !canSettleNow;
|
||||
|
||||
// The client picks the model (defaulting to the user's last-used model
|
||||
// from the composer picker); the server's text-generation setting is
|
||||
// only the fallback for older clients that don't send one.
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: "Failed to load server settings for review generation.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const modelSelection = input.modelSelection ?? settings.textGenerationModelSelection;
|
||||
|
||||
// Deeper investigation: live PR state + recent comments, when the
|
||||
// thread has a branch. Failures degrade to "no PR context".
|
||||
const prContext =
|
||||
thread.branch !== null ? yield* investigateThreadPr(cwd, thread.branch) : null;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadReview({
|
||||
cwd,
|
||||
title: thread.title,
|
||||
isActive,
|
||||
firstUserMessage,
|
||||
recentMessages,
|
||||
modelSelection,
|
||||
...(prContext !== null
|
||||
? {
|
||||
pullRequest: {
|
||||
number: prContext.status.number,
|
||||
state: prContext.status.state,
|
||||
reviewDecision: prContext.status.reviewDecision,
|
||||
checksPassing: prContext.status.checksPassing,
|
||||
mergeable: prContext.status.mergeable,
|
||||
recentComments: prContext.recentComments,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
// Belt and braces on top of prompt rules + normalizeThreadReview: an
|
||||
// active thread must never carry a settle recommendation.
|
||||
const recommendSettle = generated.recommendSettle && canSettleNow;
|
||||
|
||||
// Each checkpoint's files are that TURN's delta (CheckpointReactor diffs
|
||||
// previous→current), not a cumulative thread diff — so sum every ready
|
||||
// checkpoint. Line counts add up across turns; the file count dedupes by
|
||||
// path so a file edited in three turns counts once.
|
||||
const readyCheckpoints = thread.checkpoints.filter(
|
||||
(checkpoint) => checkpoint.status === "ready",
|
||||
);
|
||||
const touchedPaths = new Set<string>();
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const checkpoint of readyCheckpoints) {
|
||||
for (const file of checkpoint.files) {
|
||||
touchedPaths.add(file.path);
|
||||
additions += file.additions;
|
||||
deletions += file.deletions;
|
||||
}
|
||||
}
|
||||
const diffStats =
|
||||
touchedPaths.size > 0 ? { files: touchedPaths.size, additions, deletions } : undefined;
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
summary: generated.summary,
|
||||
nextStep: generated.nextStep,
|
||||
suggestedTitle: generated.suggestedTitle,
|
||||
recommendSettle,
|
||||
settleReason: recommendSettle ? generated.settleReason : null,
|
||||
...(diffStats !== undefined ? { diffStats } : {}),
|
||||
...(prContext !== null ? { prStatus: prContext.status } : {}),
|
||||
...(generated.usage !== undefined
|
||||
? {
|
||||
usage: {
|
||||
inputTokens: generated.usage.inputTokens,
|
||||
outputTokens: generated.usage.outputTokens,
|
||||
durationMs: generated.usage.durationMs,
|
||||
...(generated.usage.costUsd !== undefined
|
||||
? { costUsd: generated.usage.costUsd }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergePullRequest: ReviewService["Service"]["mergePullRequest"] = Effect.fn(
|
||||
"ReviewService.mergePullRequest",
|
||||
)(function* (input) {
|
||||
const mapProjectionError = (cause: unknown) =>
|
||||
new ReviewMergeError({
|
||||
threadId: input.threadId,
|
||||
detail: "Failed to read the thread projection for merge.",
|
||||
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] : [],
|
||||
});
|
||||
if (cwd === undefined || thread.branch === null) {
|
||||
return yield* new ReviewMergeError({
|
||||
threadId: input.threadId,
|
||||
detail: "Thread has no resolvable workspace or branch to merge from.",
|
||||
});
|
||||
}
|
||||
|
||||
// Re-validate against LIVE GitHub state: in a merge queue, an earlier
|
||||
// merge may have landed since the review ran and made this branch
|
||||
// conflict (or someone merged/closed the PR out of band).
|
||||
const prContext = yield* investigateThreadPr(cwd, thread.branch);
|
||||
if (prContext === null || prContext.status.number !== input.pullRequestNumber) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "not-ready" as const,
|
||||
detail: "The pull request could not be re-validated against GitHub.",
|
||||
};
|
||||
}
|
||||
const status = prContext.status;
|
||||
if (status.state !== "open") {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "already-closed" as const,
|
||||
detail: `PR #${status.number} is already ${status.state}.`,
|
||||
};
|
||||
}
|
||||
if (status.mergeable === false) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "conflict" as const,
|
||||
detail: `PR #${status.number} no longer merges cleanly onto its base branch.`,
|
||||
};
|
||||
}
|
||||
if (!status.mergeReady) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "not-ready" as const,
|
||||
detail: `PR #${status.number} is not merge-ready (checks: ${String(status.checksPassing)}, review: ${status.reviewDecision ?? "none"}).`,
|
||||
};
|
||||
}
|
||||
|
||||
const mergeResult = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: ["pr", "merge", String(status.number), "--squash"],
|
||||
timeoutMs: 60_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(() => ({ merged: true as const, detail: null as string | null })),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
merged: false as const,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!mergeResult.merged) {
|
||||
// gh merge failures at this point are usually races (base advanced,
|
||||
// check flipped). Surface as conflict so the queue hands it to the
|
||||
// thread's agent rather than aborting the whole run.
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "conflict" as const,
|
||||
detail: mergeResult.detail ?? "gh pr merge failed.",
|
||||
};
|
||||
}
|
||||
return { threadId: input.threadId, outcome: "merged" as const, detail: null };
|
||||
});
|
||||
|
||||
return ReviewService.of({
|
||||
getDiffPreview,
|
||||
summarizeThread,
|
||||
mergePullRequest,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -86,7 +86,9 @@ import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
import * as GitHubCli from "./sourceControl/GitHubCli.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";
|
||||
@@ -380,6 +382,7 @@ const buildAppUnderTest = (options?: {
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
@@ -522,6 +525,24 @@ 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(
|
||||
Layer.mock(GitHubCli.GitHubCli)({
|
||||
execute: () => Effect.die("GitHubCli not stubbed in this test"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerSettings.layerTest()),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
|
||||
@@ -1328,6 +1349,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"bearer-access-token",
|
||||
"dpop-access-token",
|
||||
]);
|
||||
// Desktop, so port-scoped: instances scan for a free port and share
|
||||
// 127.0.0.1, and cookies are not scoped by port.
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -3246,6 +3269,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("allows configured development origins through ServerConfig", () =>
|
||||
Effect.gen(function* () {
|
||||
const tailnetOrigin = "https://host.example.ts.net";
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
devUrl: new URL(crossOriginClientOrigin),
|
||||
devAllowedOrigins: [tailnetOrigin],
|
||||
},
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: tailnetOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: tailnetOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -222,6 +222,8 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
|
||||
const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provide(TextGeneration.layer),
|
||||
Layer.provide(GitHubCli.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,
|
||||
@@ -49,12 +51,34 @@ const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
/**
|
||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
||||
* We only care about `structured_output`.
|
||||
* `structured_output` is the payload; the usage/cost fields are optional
|
||||
* telemetry surfaced to callers that ask for it (the review sweep shows
|
||||
* per-thread tokens and cost while it runs).
|
||||
*/
|
||||
const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
total_cost_usd: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
duration_api_ms: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
usage: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
output_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/** Telemetry a caller can opt into by passing an `onUsage` sink. */
|
||||
export interface ClaudeGenerationUsage {
|
||||
readonly inputTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly costUsd?: number | undefined;
|
||||
readonly durationMs: number;
|
||||
}
|
||||
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
|
||||
|
||||
@@ -85,7 +109,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
value: unknown,
|
||||
detail: string,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
@@ -110,16 +135,20 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
onUsage,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
/** Optional sink for the CLI's reported token/cost telemetry. */
|
||||
onUsage?: ((usage: ClaudeGenerationUsage) => void) | undefined;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = yield* encodeJsonForOperation(
|
||||
operation,
|
||||
@@ -246,6 +275,24 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
}),
|
||||
);
|
||||
|
||||
if (onUsage) {
|
||||
const usage = envelope.usage ?? null;
|
||||
// Cache-creation and cache-read tokens are still input the model
|
||||
// processed; fold them in so the reported number matches billing.
|
||||
const inputTokens =
|
||||
(usage?.input_tokens ?? 0) +
|
||||
(usage?.cache_creation_input_tokens ?? 0) +
|
||||
(usage?.cache_read_input_tokens ?? 0);
|
||||
onUsage({
|
||||
inputTokens: Math.round(inputTokens),
|
||||
outputTokens: Math.round(usage?.output_tokens ?? 0),
|
||||
...(typeof envelope.total_cost_usd === "number"
|
||||
? { costUsd: envelope.total_cost_usd }
|
||||
: {}),
|
||||
durationMs: Math.round(envelope.duration_api_ms ?? 0),
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
|
||||
return yield* decodeOutput(envelope.structured_output).pipe(
|
||||
Effect.catchTags({
|
||||
@@ -355,10 +402,39 @@ 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,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
let usage: TextGeneration.ThreadReviewGenerationUsage | undefined;
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
onUsage: (reported) => {
|
||||
usage = reported;
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...normalizeThreadReview(generated, input.isActive),
|
||||
...(usage !== undefined ? { usage } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
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,33 @@ 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,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
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,32 @@ 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,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
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,32 @@ 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,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
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,32 @@ 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,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
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,48 @@ export interface ThreadTitleGenerationResult {
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface ThreadReviewPullRequestContext {
|
||||
number: number;
|
||||
state: "open" | "closed" | "merged";
|
||||
reviewDecision: string | null;
|
||||
checksPassing: boolean | null;
|
||||
mergeable: boolean | null;
|
||||
recentComments: ReadonlyArray<{ author: string; createdAt: string; body: 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 }>;
|
||||
/** Live PR state + recent comments when the thread has one. */
|
||||
pullRequest?: ThreadReviewPullRequestContext | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationUsage {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd?: number | undefined;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationResult {
|
||||
/** Provider-reported cost of this generation, when available. */
|
||||
usage?: ThreadReviewGenerationUsage | undefined;
|
||||
summary: string;
|
||||
/** One imperative sentence: the user's single next action. */
|
||||
nextStep: 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 +116,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 +152,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 +170,8 @@ type TextGenerationOp =
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
|
||||
const resolveInstance = (
|
||||
registry: ProviderInstanceRegistry.ProviderInstanceRegistry["Service"],
|
||||
@@ -159,6 +211,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,91 @@ 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. ",
|
||||
nextStep: " Settle it. ",
|
||||
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.",
|
||||
nextStep: "Settle it.",
|
||||
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,116 @@ 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>;
|
||||
pullRequest?:
|
||||
| {
|
||||
number: number;
|
||||
state: "open" | "closed" | "merged";
|
||||
reviewDecision: string | null;
|
||||
checksPassing: boolean | null;
|
||||
mergeable: boolean | null;
|
||||
recentComments: ReadonlyArray<{ author: string; createdAt: string; body: string }>;
|
||||
}
|
||||
| undefined;
|
||||
}
|
||||
|
||||
function renderPullRequestSection(
|
||||
pullRequest: NonNullable<ThreadReviewPromptInput["pullRequest"]>,
|
||||
): string {
|
||||
const lines = [
|
||||
`PR #${pullRequest.number}: state=${pullRequest.state}`,
|
||||
`review decision: ${pullRequest.reviewDecision ?? "none required"}`,
|
||||
`CI checks passing: ${pullRequest.checksPassing === null ? "unknown" : String(pullRequest.checksPassing)}`,
|
||||
`mergeable: ${pullRequest.mergeable === null ? "unknown" : String(pullRequest.mergeable)}`,
|
||||
];
|
||||
if (pullRequest.recentComments.length > 0) {
|
||||
lines.push("Recent PR comments (newest last):");
|
||||
for (const comment of pullRequest.recentComments) {
|
||||
lines.push(`[${comment.author} @ ${comment.createdAt}] ${comment.body}`);
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
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, nextStep, suggestedTitle, recommendSettle, settleReason.",
|
||||
"Rules:",
|
||||
"- summary: ONE sentence, max ~25 words: what was asked and where it landed",
|
||||
"- nextStep: a COMMAND to the user, max 10 words. Start with a verb. Never describe status.",
|
||||
" GOOD: 'Merge PR #4415.'",
|
||||
" GOOD: 'Answer the agent's question about auth scopes.'",
|
||||
" GOOD: 'Settle this thread.'",
|
||||
" GOOD: 'Wait — agent still working.'",
|
||||
" BAD: 'The requested comparison and hosted write-up are complete, and...' (status recap, not a command)",
|
||||
" BAD: 'You should probably consider reviewing the PR when you have time.' (hedging filler)",
|
||||
"- 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",
|
||||
]
|
||||
: []),
|
||||
...(input.pullRequest
|
||||
? [
|
||||
"- weigh the PR context heavily: an open PR awaiting the user's review/merge is NOT settleable; a merged PR with no follow-up work is",
|
||||
"- if the PR is open, CI is green, reviews approve it, and it is mergeable, nextStep should be to merge it",
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
`Current title: ${input.title}`,
|
||||
...(input.pullRequest
|
||||
? [
|
||||
"",
|
||||
"Pull request status:",
|
||||
limitSection(renderPullRequestSection(input.pullRequest), 6_000),
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
"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,
|
||||
nextStep: Schema.String,
|
||||
suggestedTitle: Schema.NullOr(Schema.String),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
@@ -63,6 +63,58 @@ 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;
|
||||
nextStep: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
},
|
||||
isActive: boolean,
|
||||
): {
|
||||
summary: string;
|
||||
nextStep: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
} {
|
||||
const summary = raw.summary.trim().replace(/\s+/g, " ");
|
||||
// Backstop against rambling: first sentence only, hard-capped. The prompt
|
||||
// asks for a <=10-word command, but models drift — never render a recap.
|
||||
const nextStepFirstSentence =
|
||||
raw.nextStep
|
||||
.trim()
|
||||
.replace(/\s+/g, " ")
|
||||
.match(/^[^.!?]*[.!?]?/)?.[0]
|
||||
?.trim() ?? "";
|
||||
const nextStep =
|
||||
nextStepFirstSentence.length > 80
|
||||
? `${nextStepFirstSentence.slice(0, 77).trimEnd()}...`
|
||||
: nextStepFirstSentence;
|
||||
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.",
|
||||
nextStep: nextStep.length > 0 ? nextStep : "Review this thread.",
|
||||
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,8 @@ 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.reviewMergePullRequest, AuthReviewWriteScope],
|
||||
[WS_METHODS.terminalOpen, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalAttach, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalWrite, AuthTerminalOperateScope],
|
||||
@@ -1852,6 +1854,14 @@ 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.reviewMergePullRequest]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.reviewMergePullRequest, review.mergePullRequest(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
FolderPlusIcon,
|
||||
GitBranchIcon,
|
||||
EllipsisIcon,
|
||||
ListChecksIcon,
|
||||
MessageSquareIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
@@ -79,6 +80,8 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { publishSweepChangeRequestStates } from "../reviewSweepStore";
|
||||
import { ReviewSweepLaunchDialog } from "./reviewSweep/ReviewSweepLaunchDialog";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
@@ -1169,6 +1172,11 @@ export default function SidebarV2() {
|
||||
},
|
||||
[],
|
||||
);
|
||||
// Mirror PR states to the review-sweep store so its unsettled-candidate
|
||||
// predicate matches this sidebar's partition (merged-PR auto-settle).
|
||||
useEffect(() => {
|
||||
publishSweepChangeRequestStates(changeRequestStateByKey);
|
||||
}, [changeRequestStateByKey]);
|
||||
|
||||
// Project scope: one menu above the list. Scoping filters the list without
|
||||
// making the header width depend on the number or length of project names.
|
||||
@@ -2205,6 +2213,14 @@ export default function SidebarV2() {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
}, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]);
|
||||
|
||||
// Open the launch modal — the sweep itself runs in the background and
|
||||
// announces completion with a toast, so no navigation happens here.
|
||||
const [reviewSweepDialogOpen, setReviewSweepDialogOpen] = useState(false);
|
||||
const handleReviewSweepClick = useCallback(() => {
|
||||
if (isMobile) setOpenMobile(false);
|
||||
setReviewSweepDialogOpen(true);
|
||||
}, [isMobile, 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.
|
||||
@@ -2214,6 +2230,10 @@ export default function SidebarV2() {
|
||||
return (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<ReviewSweepLaunchDialog
|
||||
open={reviewSweepDialogOpen}
|
||||
onOpenChange={setReviewSweepDialogOpen}
|
||||
/>
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pb-2 pt-3">
|
||||
<div className="flex items-center gap-1">
|
||||
@@ -2238,6 +2258,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,110 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
options: ReadonlyArray<{ id: string; label: string }>,
|
||||
currentValue: string,
|
||||
): Extract<ProviderOptionDescriptor, { type: "select" }> {
|
||||
return { id, label: id, type: "select", options: [...options], currentValue };
|
||||
}
|
||||
|
||||
function fastModeDescriptor(
|
||||
currentValue: boolean,
|
||||
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
|
||||
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
|
||||
}
|
||||
|
||||
const EFFORT = selectDescriptor(
|
||||
"effort",
|
||||
[
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
"high",
|
||||
);
|
||||
const CONTEXT_WINDOW = selectDescriptor(
|
||||
"contextWindow",
|
||||
[
|
||||
{ id: "200k", label: "200k" },
|
||||
{ id: "1m", label: "1M" },
|
||||
],
|
||||
"1m",
|
||||
);
|
||||
|
||||
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
|
||||
return buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: false,
|
||||
fastModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildTraitsTriggerDisplay", () => {
|
||||
it("omits fast mode from the label entirely when it is off", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the bolt instead of a text label when fast mode is on", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps non-fastMode booleans as text labels", () => {
|
||||
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
|
||||
id: "thinking",
|
||||
label: "Thinking",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
};
|
||||
expect(display([EFFORT, thinking], false)).toEqual({
|
||||
label: "High · Thinking On",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a text label when fast mode is the only trait", () => {
|
||||
expect(display([fastModeDescriptor(true)], true)).toEqual({
|
||||
label: "Fast",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
expect(display([fastModeDescriptor(false)], false)).toEqual({
|
||||
label: "Normal",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
|
||||
// A select with neither a currentValue nor an isDefault option yields no
|
||||
// label. Without a fastMode descriptor present that must stay blank rather
|
||||
// than falling through to a bogus "Normal".
|
||||
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "effort",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "high", label: "High" },
|
||||
],
|
||||
};
|
||||
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
|
||||
});
|
||||
|
||||
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
|
||||
expect(
|
||||
buildTraitsTriggerDisplay({
|
||||
descriptors: [EFFORT, fastModeDescriptor(true)],
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: true,
|
||||
fastModeEnabled: true,
|
||||
}),
|
||||
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -379,6 +379,46 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Build the traits trigger's text label plus whether the fast-mode bolt should
|
||||
* render. Fast mode is a lightning bolt when on and nothing at all when off —
|
||||
* "Normal" is the near-universal case and isn't worth the horizontal space. The
|
||||
* one exception is when fast mode is the only trait, where a bare bolt (or bare
|
||||
* chevron) would leave the trigger unreadable.
|
||||
*/
|
||||
export function buildTraitsTriggerDisplay(input: {
|
||||
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
primarySelectDescriptorId: string | null;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}): { label: string; showFastModeIcon: boolean } {
|
||||
let hasFastMode = false;
|
||||
const labels: Array<string> = [];
|
||||
for (const descriptor of input.descriptors) {
|
||||
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
|
||||
hasFastMode = true;
|
||||
continue;
|
||||
}
|
||||
const label =
|
||||
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
labels.push(label);
|
||||
}
|
||||
}
|
||||
|
||||
// Only fall back to text when fast mode is genuinely the sole trait. Keying
|
||||
// off an empty label list alone would also catch descriptors that resolved to
|
||||
// no label at all, printing a bogus "Normal" for a model without fast mode.
|
||||
if (labels.length === 0 && hasFastMode) {
|
||||
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
|
||||
}
|
||||
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
|
||||
}
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
@@ -393,7 +433,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
|
||||
getTraitsSectionVisibility({
|
||||
provider,
|
||||
models,
|
||||
@@ -415,23 +455,18 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
const triggerLabels: Array<string> = [];
|
||||
for (const descriptor of descriptors) {
|
||||
const label =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? descriptor.id === "fastMode"
|
||||
? descriptor.currentValue === true
|
||||
? "Fast"
|
||||
: "Normal"
|
||||
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
triggerLabels.push(label);
|
||||
}
|
||||
}
|
||||
const triggerLabel = triggerLabels.join(" · ");
|
||||
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
|
||||
ultrathinkPromptControlled,
|
||||
fastModeEnabled,
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
@@ -457,12 +492,14 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { setSweepResultsNavigator, useReviewSweepStore } from "../../reviewSweepStore";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Dialog, DialogDescription, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
|
||||
import { SweepPreRunSummary } from "./ReviewSweepView";
|
||||
|
||||
/** Launch modal for the work-review sweep. The sweep itself runs in the
|
||||
background (module-level runner), so the modal just confirms scope/cost
|
||||
and closes; a toast announces completion with a link to the results. */
|
||||
export function ReviewSweepLaunchDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const phase = useReviewSweepStore((state) => state.phase);
|
||||
|
||||
// Install the navigator the store's completion toast uses. The dialog is
|
||||
// mounted for the sidebar's lifetime, so this stays registered.
|
||||
useEffect(() => {
|
||||
setSweepResultsNavigator(() => {
|
||||
void router.navigate({ to: "/review-sweep" });
|
||||
});
|
||||
return () => setSweepResultsNavigator(null);
|
||||
}, [router]);
|
||||
|
||||
const handleStarted = () => {
|
||||
onOpenChange(false);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "info",
|
||||
title: "Reviewing your work in the background",
|
||||
description: "You'll get a notification when the results are ready.",
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "Watch progress",
|
||||
onClick: () => void router.navigate({ to: "/review-sweep" }),
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPopup className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Review unsettled work</DialogTitle>
|
||||
<DialogDescription>
|
||||
{phase === "running"
|
||||
? "A review is already running — results will arrive as a notification."
|
||||
: "One AI review per unsettled thread, run in the background."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{phase === "running" ? null : <SweepPreRunSummary onStarted={handleStarted} />}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,958 @@
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { hasQueuedTurnStart } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
GitMergeIcon,
|
||||
InfoIcon,
|
||||
ListChecksIcon,
|
||||
LoaderIcon,
|
||||
PencilLineIcon,
|
||||
RotateCcwIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { useClientSettings, usePrimarySettings } from "../../hooks/useSettings";
|
||||
import { getCustomModelOptionsByInstance } from "../../modelSelection";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import { primaryServerProvidersAtom } from "../../state/server";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import {
|
||||
applyAllSweepRecommendations,
|
||||
applySweepSettle,
|
||||
applySweepTitle,
|
||||
dismissSweepItem,
|
||||
isSweepCandidate,
|
||||
mergeSweepItem,
|
||||
readSweepModelSelection,
|
||||
retrySweepItem,
|
||||
setSweepModelSelection,
|
||||
runMergeQueue,
|
||||
sortSweepCandidates,
|
||||
startReviewSweep,
|
||||
SWEEP_MAX_THREADS,
|
||||
sweepNowIso,
|
||||
useReviewSweepStore,
|
||||
type SweepItem,
|
||||
} from "../../reviewSweepStore";
|
||||
import {
|
||||
readThreadShell,
|
||||
useProjects,
|
||||
useServerConfigs,
|
||||
useThreadShells,
|
||||
} from "../../state/entities";
|
||||
import { formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { buildThreadRouteParams } from "../../threadRoutes";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
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";
|
||||
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Triage buckets: ordered by "how fast can you clear this" — one-click
|
||||
// settles first, quick title fixes second, then threads that need real
|
||||
// reading, then no-action-possible tails.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type SweepBucket =
|
||||
| "mergeReady"
|
||||
| "settle"
|
||||
| "title"
|
||||
| "attention"
|
||||
| "inFlight"
|
||||
| "failed"
|
||||
| "reviewing";
|
||||
|
||||
const BUCKET_ORDER: readonly SweepBucket[] = [
|
||||
"mergeReady",
|
||||
"settle",
|
||||
"title",
|
||||
"attention",
|
||||
"inFlight",
|
||||
"failed",
|
||||
"reviewing",
|
||||
];
|
||||
|
||||
const BUCKET_META: Record<
|
||||
SweepBucket,
|
||||
{
|
||||
title: string;
|
||||
hint: string;
|
||||
/** Tinted icon chip beside the section title. */
|
||||
iconChip: string;
|
||||
icon: typeof ArchiveIcon;
|
||||
}
|
||||
> = {
|
||||
mergeReady: {
|
||||
title: "Merge ready",
|
||||
hint: "Open PRs with green CI, approvals, and clean merges.",
|
||||
iconChip: "bg-violet-500/12 text-violet-400",
|
||||
icon: GitMergeIcon,
|
||||
},
|
||||
settle: {
|
||||
title: "Ready to settle",
|
||||
hint: "Work concluded — one click clears each from your active list.",
|
||||
iconChip: "bg-emerald-500/12 text-emerald-400",
|
||||
icon: ArchiveIcon,
|
||||
},
|
||||
title: {
|
||||
title: "Title fixes",
|
||||
hint: "Still in progress, but the name no longer matches the work.",
|
||||
iconChip: "bg-sky-500/12 text-sky-400",
|
||||
icon: PencilLineIcon,
|
||||
},
|
||||
attention: {
|
||||
title: "Needs your attention",
|
||||
hint: "Waiting on you — review, input, or a decision.",
|
||||
iconChip: "bg-amber-500/12 text-amber-400",
|
||||
icon: CircleAlertIcon,
|
||||
},
|
||||
inFlight: {
|
||||
title: "In flight",
|
||||
hint: "Agents are still working; nothing to do yet.",
|
||||
iconChip: "bg-muted text-muted-foreground",
|
||||
icon: LoaderIcon,
|
||||
},
|
||||
failed: {
|
||||
title: "Review failed",
|
||||
hint: "The reviewer couldn't process these — retry or open them directly.",
|
||||
iconChip: "bg-red-500/12 text-red-400",
|
||||
icon: CircleAlertIcon,
|
||||
},
|
||||
reviewing: {
|
||||
title: "Still reviewing",
|
||||
hint: "",
|
||||
iconChip: "bg-muted text-muted-foreground",
|
||||
icon: LoaderIcon,
|
||||
},
|
||||
};
|
||||
|
||||
function classifySweepItem(item: SweepItem): SweepBucket {
|
||||
if (item.status === "error") return "failed";
|
||||
if (item.status !== "done" || item.result === null) return "reviewing";
|
||||
// Merge-ready wins over everything: it's the highest-leverage one-click.
|
||||
// Items stay in the bucket through the queue lifecycle (queued → merging
|
||||
// → merged/conflicted) so progress is visible in place.
|
||||
if (item.result.prStatus?.mergeReady && !item.settleApplied) return "mergeReady";
|
||||
if (item.result.recommendSettle && !item.settleApplied) return "settle";
|
||||
if (item.result.suggestedTitle && !item.titleApplied) return "title";
|
||||
// Live shell wins over review-time knowledge: a thread blocked on the user
|
||||
// right now belongs in "attention" even if the review predates the block.
|
||||
const shell = readThreadShell(item.ref);
|
||||
const working =
|
||||
shell?.session?.status === "running" ||
|
||||
shell?.session?.status === "starting" ||
|
||||
// A just-sent message no session has adopted yet is in-flight work, not
|
||||
// something waiting on the user.
|
||||
(shell !== null && hasQueuedTurnStart(shell, { now: new Date().toISOString() }));
|
||||
const blocked = shell?.hasPendingApprovals === true || shell?.hasPendingUserInput === true;
|
||||
if (blocked) return "attention";
|
||||
if (working) return "inFlight";
|
||||
return "attention";
|
||||
}
|
||||
|
||||
function DiffStatsLabel({ item }: { item: SweepItem }) {
|
||||
const stats = item.result?.diffStats;
|
||||
if (!stats || stats.files === 0) return null;
|
||||
return (
|
||||
<span className="flex items-center gap-1 font-mono text-[11px]">
|
||||
<span className="text-emerald-500">+{stats.additions}</span>
|
||||
<span className="text-red-400">−{stats.deletions}</span>
|
||||
<span className="text-muted-foreground/70">
|
||||
· {stats.files} {stats.files === 1 ? "file" : "files"}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SweepItemMetaRow({
|
||||
item,
|
||||
projectTitle,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
item: SweepItem;
|
||||
projectTitle: string;
|
||||
workspaceRoot: string | null;
|
||||
}) {
|
||||
const age = formatRelativeTimeLabel(item.lastActivityAt);
|
||||
return (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
{workspaceRoot ? (
|
||||
<ProjectFavicon
|
||||
environmentId={item.ref.environmentId}
|
||||
cwd={workspaceRoot}
|
||||
className="size-3.5 shrink-0"
|
||||
/>
|
||||
) : null}
|
||||
<span className="truncate">{projectTitle}</span>
|
||||
</span>
|
||||
{item.branch ? (
|
||||
<span className="max-w-56 truncate font-mono text-[11px] text-muted-foreground/80">
|
||||
{item.branch}
|
||||
</span>
|
||||
) : null}
|
||||
{item.result?.prStatus ? (
|
||||
<a
|
||||
href={item.result.prStatus.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="shrink-0 font-mono text-[11px] text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
#{item.result.prStatus.number}
|
||||
</a>
|
||||
) : null}
|
||||
{age ? <span className="shrink-0">{age}</span> : null}
|
||||
<DiffStatsLabel item={item} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MergeStatusBadge({ item }: { item: SweepItem }) {
|
||||
switch (item.mergeStatus) {
|
||||
case "queued":
|
||||
return <Badge variant="secondary">Queued</Badge>;
|
||||
case "merging":
|
||||
return (
|
||||
<Badge variant="info">
|
||||
<Spinner className="me-1 size-3" />
|
||||
Merging
|
||||
</Badge>
|
||||
);
|
||||
case "merged":
|
||||
return <Badge variant="success">Merged</Badge>;
|
||||
case "conflicted":
|
||||
return <Badge variant="warning">Conflict — agent rebasing</Badge>;
|
||||
case "failed":
|
||||
return <Badge variant="error">Merge failed</Badge>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function SweepItemCard({
|
||||
item,
|
||||
bucket,
|
||||
projectTitle,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
item: SweepItem;
|
||||
bucket: SweepBucket;
|
||||
projectTitle: string;
|
||||
workspaceRoot: string | null;
|
||||
}) {
|
||||
const key = scopedThreadKey(item.ref);
|
||||
const [applying, setApplying] = useState(false);
|
||||
const result = item.result;
|
||||
|
||||
const primaryAction =
|
||||
bucket === "mergeReady" ? (
|
||||
item.mergeStatus === "idle" || item.mergeStatus === "failed" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void mergeSweepItem(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
<GitMergeIcon className="me-1 size-3.5" />
|
||||
Merge & settle
|
||||
</Button>
|
||||
) : null
|
||||
) : bucket === "settle" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void applySweepSettle(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="me-1 size-3.5" />
|
||||
Settle
|
||||
</Button>
|
||||
) : bucket === "title" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void applySweepTitle(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
Apply title
|
||||
</Button>
|
||||
) : bucket === "failed" ? (
|
||||
<Button size="xs" variant="outline" className="shrink-0" onClick={() => retrySweepItem(key)}>
|
||||
Retry
|
||||
</Button>
|
||||
) : null;
|
||||
|
||||
// The one-line "what should I do" is the card body; the full summary
|
||||
// lives behind the info icon so the grid stays scannable. Results from
|
||||
// pre-nextStep servers fall back to settleReason (settle bucket) or the
|
||||
// summary (attention bucket) so action cards never render bodyless.
|
||||
const nextStepFallback =
|
||||
bucket === "settle"
|
||||
? (result?.settleReason ?? null)
|
||||
: bucket === "attention"
|
||||
? (result?.summary ?? null)
|
||||
: null;
|
||||
const nextStep = item.status === "error" ? null : (result?.nextStep ?? nextStepFallback);
|
||||
|
||||
return (
|
||||
<Card className="group min-w-0 gap-2 p-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
<Link
|
||||
to="/$environmentId/$threadId"
|
||||
params={buildThreadRouteParams(item.ref)}
|
||||
className="min-w-0 truncate text-sm font-medium tracking-[-0.005em] text-foreground hover:underline"
|
||||
>
|
||||
{item.threadTitle}
|
||||
</Link>
|
||||
{bucket === "settle" && item.settleApplied ? (
|
||||
<Badge variant="outline" size="sm">
|
||||
Settled
|
||||
</Badge>
|
||||
) : null}
|
||||
{bucket === "mergeReady" ? <MergeStatusBadge item={item} /> : null}
|
||||
</div>
|
||||
<SweepItemMetaRow item={item} projectTitle={projectTitle} workspaceRoot={workspaceRoot} />
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100">
|
||||
{result?.summary ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70"
|
||||
aria-label="Show thread summary"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<InfoIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="bottom" className="max-w-80">
|
||||
{result.summary}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground"
|
||||
aria-label="Dismiss recommendation"
|
||||
onClick={() => dismissSweepItem(key)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{item.status === "error" ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-destructive-foreground">
|
||||
{item.errorMessage}
|
||||
</p>
|
||||
) : item.mergeStatus === "conflicted" || item.mergeStatus === "failed" ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-warning-foreground">
|
||||
{item.mergeDetail}
|
||||
</p>
|
||||
) : nextStep ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-muted-foreground">{nextStep}</p>
|
||||
) : null}
|
||||
|
||||
{bucket === "title" && result?.suggestedTitle ? (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">
|
||||
<span className="max-w-full truncate text-muted-foreground/70 line-through">
|
||||
{item.threadTitle}
|
||||
</span>
|
||||
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground/70" />
|
||||
<span className="max-w-full truncate font-medium text-foreground">
|
||||
{result.suggestedTitle}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{result?.suggestedTitle && item.titleApplied ? (
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
Renamed to <span className="font-medium text-foreground">{result.suggestedTitle}</span>.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{primaryAction ? <div className="flex justify-end pt-1">{primaryAction}</div> : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDuration(ms: number): string {
|
||||
const totalSeconds = Math.max(0, Math.round(ms / 1000));
|
||||
if (totalSeconds < 60) return `${totalSeconds}s`;
|
||||
return `${Math.floor(totalSeconds / 60)}m ${String(totalSeconds % 60).padStart(2, "0")}s`;
|
||||
}
|
||||
|
||||
function formatTokens(tokens: number): string {
|
||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
||||
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
|
||||
return String(tokens);
|
||||
}
|
||||
|
||||
/** Live per-thread progress: what's running, for how long, and what each
|
||||
review cost. Replaces a bare spinner so a multi-minute sweep is
|
||||
legible while it works. */
|
||||
function SweepProgressList({
|
||||
items,
|
||||
projectsByKey,
|
||||
}: {
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
projectsByKey: ReadonlyMap<string, { title: string; workspaceRoot: string }>;
|
||||
}) {
|
||||
// Ticking clock so elapsed times advance without store writes.
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setNowMs(Date.now()), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Running first (that's the live part), then queued, then finished.
|
||||
const ordered = useMemo(() => {
|
||||
const rank = (item: SweepItem) =>
|
||||
item.status === "running" ? 0 : item.status === "pending" ? 1 : 2;
|
||||
return [...items].sort((a, b) => rank(a) - rank(b));
|
||||
}, [items]);
|
||||
|
||||
return (
|
||||
<Card className="flex flex-col gap-0 divide-y divide-border/50 overflow-hidden p-0">
|
||||
{ordered.map((item) => {
|
||||
const project = projectsByKey.get(
|
||||
scopedProjectKey(scopeProjectRef(item.ref.environmentId, item.projectId)),
|
||||
);
|
||||
const elapsedMs =
|
||||
item.startedAtMs === null ? null : (item.finishedAtMs ?? nowMs) - item.startedAtMs;
|
||||
const usage = item.result?.usage;
|
||||
return (
|
||||
<div
|
||||
key={scopedThreadKey(item.ref)}
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-3 py-2 text-sm",
|
||||
item.status === "pending" && "opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center">
|
||||
{item.status === "running" ? (
|
||||
<Spinner className="size-3.5 text-sky-400" />
|
||||
) : item.status === "done" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : item.status === "error" ? (
|
||||
<CircleAlertIcon className="size-3.5 text-red-400" />
|
||||
) : (
|
||||
<span className="size-1.5 rounded-full bg-muted-foreground/40" />
|
||||
)}
|
||||
</span>
|
||||
{project?.workspaceRoot ? (
|
||||
<ProjectFavicon
|
||||
environmentId={item.ref.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-3.5 shrink-0"
|
||||
/>
|
||||
) : null}
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/90">{item.threadTitle}</span>
|
||||
{usage ? (
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">
|
||||
{formatTokens(usage.inputTokens + usage.outputTokens)} tok
|
||||
{usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="w-16 shrink-0 text-right font-mono text-[11px] text-muted-foreground">
|
||||
{elapsedMs === null ? "—" : formatDuration(elapsedMs)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cost-transparency threshold: at or above this many candidate threads the
|
||||
pre-run screen calls out that the sweep may be slow/expensive. */
|
||||
const SWEEP_COST_NOTE_THRESHOLD = 15;
|
||||
|
||||
/** Pre-run summary: how many threads a sweep would cover and which model
|
||||
each environment's server will use, so starting is an informed choice.
|
||||
Rendered on the idle /review-sweep page and inside the sidebar's launch
|
||||
modal. `onStarted` lets the modal close itself when the sweep kicks off. */
|
||||
export function SweepPreRunSummary({ onStarted }: { onStarted?: () => void } = {}) {
|
||||
const shells = useThreadShells();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
// Recompute when the sidebar publishes fresh PR states — merged-PR
|
||||
// auto-settle changes which threads count as unsettled.
|
||||
const candidateVersion = useReviewSweepStore((state) => state.candidateVersion);
|
||||
|
||||
// Review model: defaults to the composer's last-used pick, overridable
|
||||
// here. Re-read on candidateVersion so the trigger reflects changes.
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const settings = usePrimarySettings();
|
||||
const selectedModel = useMemo(
|
||||
() => readSweepModelSelection(),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- module-level source
|
||||
[candidateVersion],
|
||||
);
|
||||
const instanceEntries = useMemo(
|
||||
() =>
|
||||
sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
),
|
||||
[serverProviders, settings],
|
||||
);
|
||||
const activeInstanceId = selectedModel?.instanceId ?? instanceEntries[0]?.instanceId ?? null;
|
||||
const activeModel = selectedModel?.model ?? instanceEntries[0]?.models[0]?.slug ?? "";
|
||||
const activeOptions = selectedModel?.options ?? [];
|
||||
const modelOptionsByInstance = useMemo(
|
||||
() =>
|
||||
activeInstanceId === null
|
||||
? new Map()
|
||||
: getCustomModelOptionsByInstance(settings, serverProviders, activeInstanceId, activeModel),
|
||||
[activeInstanceId, activeModel, serverProviders, settings],
|
||||
);
|
||||
const activeInstanceEntry = instanceEntries.find(
|
||||
(entry) => entry.instanceId === activeInstanceId,
|
||||
);
|
||||
|
||||
const { candidateCount, reviewedCount, modelsByEnvironment } = useMemo(() => {
|
||||
const now = sweepNowIso();
|
||||
const candidates = sortSweepCandidates(
|
||||
shells.filter((shell) =>
|
||||
isSweepCandidate(shell, serverConfigs.get(shell.environmentId)?.environment.capabilities, {
|
||||
now,
|
||||
autoSettleAfterDays,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Aggregate only what a run would actually review: the cap is applied
|
||||
// here, in the same most-recently-active order startReviewSweep uses,
|
||||
// so the environment/model rows never overstate the calls.
|
||||
const reviewed = candidates.slice(0, SWEEP_MAX_THREADS);
|
||||
const models = new Map<
|
||||
string,
|
||||
{ environmentId: string; label: string; model: string; threads: number }
|
||||
>();
|
||||
for (const shell of reviewed) {
|
||||
const config = serverConfigs.get(shell.environmentId);
|
||||
const entry = models.get(shell.environmentId);
|
||||
if (entry) {
|
||||
entry.threads += 1;
|
||||
} else {
|
||||
const selection = config?.settings.textGenerationModelSelection;
|
||||
models.set(shell.environmentId, {
|
||||
environmentId: shell.environmentId,
|
||||
label: config?.environment.label ?? shell.environmentId,
|
||||
model: selection ? `${selection.model}` : "server default",
|
||||
threads: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
candidateCount: candidates.length,
|
||||
reviewedCount: reviewed.length,
|
||||
modelsByEnvironment: [...models.values()],
|
||||
};
|
||||
}, [autoSettleAfterDays, candidateVersion, serverConfigs, shells]);
|
||||
|
||||
if (candidateCount === 0) {
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>All caught up</EmptyTitle>
|
||||
<EmptyDescription>No unsettled threads to review right now.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>Review your in-progress work</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
This sweep runs one AI review per thread to summarize it, catch stale titles, and find
|
||||
threads ready to settle. Nothing is applied without your click.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<div className="flex w-full max-w-md flex-col gap-1.5 rounded-lg border border-border/60 bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
|
||||
<div>
|
||||
<span className="font-medium text-foreground">{reviewedCount}</span>{" "}
|
||||
{reviewedCount === 1 ? "thread" : "threads"} will be reviewed
|
||||
{candidateCount > SWEEP_MAX_THREADS
|
||||
? ` (${candidateCount - SWEEP_MAX_THREADS} least-recently-active skipped)`
|
||||
: ""}
|
||||
</div>
|
||||
{modelsByEnvironment.length > 1 ? (
|
||||
<div className="truncate">
|
||||
Across{" "}
|
||||
{modelsByEnvironment.map((entry, index) => (
|
||||
<span key={entry.environmentId}>
|
||||
{index > 0 ? ", " : ""}
|
||||
{entry.label} ({entry.threads})
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center gap-2 pt-0.5">
|
||||
<span className="shrink-0">Review with</span>
|
||||
{activeInstanceId !== null ? (
|
||||
<>
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeInstanceId}
|
||||
model={activeModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
// Carry the current traits across a model switch when the
|
||||
// instance is unchanged; a different instance's options
|
||||
// aren't transferable, so start clean there.
|
||||
setSweepModelSelection(
|
||||
createModelSelection(
|
||||
instanceId,
|
||||
model,
|
||||
instanceId === activeInstanceId ? activeOptions : undefined,
|
||||
),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{activeInstanceEntry ? (
|
||||
<TraitsPicker
|
||||
provider={activeInstanceEntry.driverKind}
|
||||
models={activeInstanceEntry.models}
|
||||
model={activeModel}
|
||||
prompt=""
|
||||
onPromptChange={() => {}}
|
||||
modelOptions={activeOptions}
|
||||
allowPromptInjectedEffort={false}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onModelOptionsChange={(nextOptions) => {
|
||||
setSweepModelSelection(
|
||||
createModelSelection(activeInstanceId, activeModel, nextOptions),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-foreground">server default</span>
|
||||
)}
|
||||
</div>
|
||||
{reviewedCount >= SWEEP_COST_NOTE_THRESHOLD ? (
|
||||
<div className="text-warning-foreground">
|
||||
Heads up: {reviewedCount} model calls may take a few minutes and use noticeable credits.
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
startReviewSweep();
|
||||
onStarted?.();
|
||||
}}
|
||||
>
|
||||
<ListChecksIcon className="me-1.5 size-4" />
|
||||
Review {reviewedCount} {reviewedCount === 1 ? "thread" : "threads"}
|
||||
</Button>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
// classifySweepItem reads live shells (running vs blocked), so bucketing
|
||||
// must recompute when shells change and not only when items do.
|
||||
const shells = useThreadShells();
|
||||
|
||||
// Projects are only unique per (environmentId, projectId) — ids can
|
||||
// collide across connected environments.
|
||||
const projectsByKey = useMemo(() => {
|
||||
const byKey = new Map<string, { title: string; workspaceRoot: string }>();
|
||||
for (const project of projects) {
|
||||
byKey.set(scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), {
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
});
|
||||
}
|
||||
return byKey;
|
||||
}, [projects]);
|
||||
|
||||
const visibleItems = useMemo(
|
||||
() =>
|
||||
order
|
||||
.map((key) => items[key])
|
||||
.filter((item): item is SweepItem => item !== undefined && !item.dismissed),
|
||||
[items, order],
|
||||
);
|
||||
|
||||
const buckets = useMemo(() => {
|
||||
const grouped = new Map<SweepBucket, SweepItem[]>();
|
||||
for (const item of visibleItems) {
|
||||
const bucket = classifySweepItem(item);
|
||||
const group = grouped.get(bucket);
|
||||
if (group) {
|
||||
group.push(item);
|
||||
} else {
|
||||
grouped.set(bucket, [item]);
|
||||
}
|
||||
}
|
||||
// Within a bucket, smallest diff first — clear the easy ones, build
|
||||
// momentum. Unknown diff sizes sink to the bottom.
|
||||
for (const group of grouped.values()) {
|
||||
group.sort((a, b) => {
|
||||
const sizeOf = (item: SweepItem) => {
|
||||
const stats = item.result?.diffStats;
|
||||
return stats ? stats.additions + stats.deletions : Number.MAX_SAFE_INTEGER;
|
||||
};
|
||||
return sizeOf(a) - sizeOf(b);
|
||||
});
|
||||
}
|
||||
return BUCKET_ORDER.flatMap((bucket) => {
|
||||
const group = grouped.get(bucket);
|
||||
return group && group.length > 0 ? [[bucket, group] as const] : [];
|
||||
});
|
||||
// `shells` is a classification input via readThreadShell, not unused.
|
||||
}, [shells, 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);
|
||||
const [mergingAll, setMergingAll] = useState(false);
|
||||
// Aggregate what the run has cost so far, from provider-reported usage.
|
||||
const runTotals = useMemo(
|
||||
() =>
|
||||
visibleItems.reduce(
|
||||
(totals, item) => {
|
||||
const usage = item.result?.usage;
|
||||
if (!usage) return totals;
|
||||
return {
|
||||
tokens: totals.tokens + usage.inputTokens + usage.outputTokens,
|
||||
costUsd: totals.costUsd + (usage.costUsd ?? 0),
|
||||
};
|
||||
},
|
||||
{ tokens: 0, costUsd: 0 },
|
||||
),
|
||||
[visibleItems],
|
||||
);
|
||||
|
||||
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}
|
||||
{phase !== "idle" ? (
|
||||
<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" />
|
||||
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>
|
||||
) : null}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="settings-page-scroll-fade scrollbar-gutter-both min-h-0 flex-1 overflow-y-auto px-4 pt-8 pb-10 sm:px-8">
|
||||
{phase === "idle" ? (
|
||||
<SweepPreRunSummary />
|
||||
) : running ? (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<h2 className="text-sm font-medium text-foreground">
|
||||
Reviewing your work — {reviewedCount} of {visibleItems.length}
|
||||
</h2>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{runTotals.tokens > 0 ? `${formatTokens(runTotals.tokens)} tokens` : null}
|
||||
{runTotals.costUsd > 0 ? ` · $${runTotals.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-sky-500 transition-[width] duration-500"
|
||||
style={{
|
||||
width: `${visibleItems.length === 0 ? 0 : Math.round((reviewedCount / visibleItems.length) * 100)}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Results appear all at once when every thread is reviewed, so you can triage in one
|
||||
pass. Feel free to navigate away; the sweep keeps running.
|
||||
</p>
|
||||
</div>
|
||||
<SweepProgressList items={visibleItems} projectsByKey={projectsByKey} />
|
||||
</div>
|
||||
) : visibleItems.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>All caught up</EmptyTitle>
|
||||
<EmptyDescription>No unsettled threads to review right now.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
) : (
|
||||
<TooltipProvider>
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col gap-10">
|
||||
{truncatedCount > 0 ? (
|
||||
<p className="text-[13px] leading-[1.45] text-muted-foreground/80">
|
||||
Reviewed the {visibleItems.length} most recent threads; {truncatedCount} more
|
||||
were skipped this run.
|
||||
</p>
|
||||
) : null}
|
||||
{buckets.map(([bucket, bucketItems]) => {
|
||||
const meta = BUCKET_META[bucket];
|
||||
const BucketIcon = meta.icon;
|
||||
const mergeableCount =
|
||||
bucket === "mergeReady"
|
||||
? bucketItems.filter(
|
||||
(item) => item.mergeStatus === "idle" || item.mergeStatus === "queued",
|
||||
).length
|
||||
: 0;
|
||||
return (
|
||||
<section key={bucket} className="flex flex-col gap-3">
|
||||
<div className="flex min-h-8 items-center gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-7 shrink-0 items-center justify-center rounded-lg",
|
||||
meta.iconChip,
|
||||
)}
|
||||
>
|
||||
<BucketIcon className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="flex items-baseline gap-2 text-[15px] font-semibold tracking-[-0.02em] text-foreground">
|
||||
{meta.title}
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
{bucketItems.length}
|
||||
</span>
|
||||
</h2>
|
||||
{meta.hint ? (
|
||||
<p className="truncate text-[13px] leading-[1.45] text-muted-foreground/80">
|
||||
{meta.hint}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{bucket === "mergeReady" && mergeableCount > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={mergingAll}
|
||||
onClick={() => {
|
||||
setMergingAll(true);
|
||||
void runMergeQueue().finally(() => setMergingAll(false));
|
||||
}}
|
||||
>
|
||||
<GitMergeIcon className="me-1 size-3.5" />
|
||||
Merge all ({mergeableCount})
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||
{bucketItems.map((item) => {
|
||||
const projectKey = scopedProjectKey(
|
||||
scopeProjectRef(item.ref.environmentId, item.projectId),
|
||||
);
|
||||
const project = projectsByKey.get(projectKey);
|
||||
return (
|
||||
<SweepItemCard
|
||||
key={scopedThreadKey(item.ref)}
|
||||
item={item}
|
||||
bucket={bucket}
|
||||
projectTitle={project?.title ?? "Unknown project"}
|
||||
workspaceRoot={project?.workspaceRoot ?? null}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
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 { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectId,
|
||||
type ReviewThreadSummaryResult,
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
import { stackedThreadToast, toastManager } from "./components/ui/toast";
|
||||
import { useComposerDraftStore } from "./composerDraftStore";
|
||||
import { getClientSettings } from "./hooks/useSettings";
|
||||
import { newMessageId } from "~/lib/utils";
|
||||
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";
|
||||
|
||||
/** PR states mirrored from SidebarV2's per-row VCS subscriptions (keyed by
|
||||
scoped thread key). The sidebar auto-settles merged/closed+idle threads
|
||||
using this data; the sweep must see the same states or it will count
|
||||
those threads as unsettled. Module-level because the sidebar is mounted
|
||||
for the app's lifetime and owns the subscriptions. */
|
||||
let changeRequestStateByKey: ReadonlyMap<string, "open" | "closed" | "merged"> = new Map();
|
||||
|
||||
export function publishSweepChangeRequestStates(
|
||||
states: ReadonlyMap<string, "open" | "closed" | "merged">,
|
||||
): void {
|
||||
// MERGE rather than replace: SidebarV2 remounts (navigating to settings and
|
||||
// back) publish an empty map before its rows re-subscribe, and wiping the
|
||||
// cache would make merged-PR threads look unsettled again. Rows only ever
|
||||
// add states for threads they own, so stale entries are harmless — a
|
||||
// thread whose PR state genuinely changes republishes its own key.
|
||||
const merged = new Map(changeRequestStateByKey);
|
||||
for (const [key, state] of states) {
|
||||
merged.set(key, state);
|
||||
}
|
||||
changeRequestStateByKey = merged;
|
||||
// Bump the store version so the pre-run summary recomputes its candidate
|
||||
// count as PR states stream in from the sidebar rows.
|
||||
useReviewSweepStore.getState().bumpCandidateVersion();
|
||||
}
|
||||
|
||||
/** Model the next run will use. Defaults to the composer's last-used
|
||||
(sticky) selection so reviews run on the model the user actually picks
|
||||
for work, not the server's commit-message text-gen default. Overridable
|
||||
in the launch modal. */
|
||||
let sweepModelSelection: ModelSelection | null = null;
|
||||
|
||||
export function readSweepModelSelection(): ModelSelection | null {
|
||||
return sweepModelSelection ?? readStickyComposerModelSelection();
|
||||
}
|
||||
|
||||
export function setSweepModelSelection(selection: ModelSelection | null): void {
|
||||
sweepModelSelection = selection;
|
||||
useReviewSweepStore.getState().bumpCandidateVersion();
|
||||
}
|
||||
|
||||
/** The composer picker's last-used model, if any. */
|
||||
function readStickyComposerModelSelection(): ModelSelection | null {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const activeProvider = store.stickyActiveProvider;
|
||||
if (activeProvider === null) return null;
|
||||
return store.stickyModelSelectionByProvider[activeProvider] ?? null;
|
||||
}
|
||||
|
||||
const SWEEP_CONCURRENCY = 5;
|
||||
/** 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";
|
||||
|
||||
/** Merge-queue lifecycle for merge-ready items. "conflicted" means the
|
||||
merge failed and the thread's agent has been asked to resolve it. */
|
||||
export type SweepMergeStatus = "idle" | "queued" | "merging" | "merged" | "conflicted" | "failed";
|
||||
|
||||
export interface SweepItem {
|
||||
readonly ref: ScopedThreadRef;
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadTitle: string;
|
||||
readonly branch: string | null;
|
||||
/** Last activity (falls back to createdAt) for the age label. */
|
||||
readonly lastActivityAt: string;
|
||||
readonly status: SweepItemStatus;
|
||||
readonly result: ReviewThreadSummaryResult | null;
|
||||
readonly errorMessage: string | null;
|
||||
readonly titleApplied: boolean;
|
||||
readonly settleApplied: boolean;
|
||||
readonly dismissed: boolean;
|
||||
readonly mergeStatus: SweepMergeStatus;
|
||||
readonly mergeDetail: string | null;
|
||||
/** Epoch ms when this item's review started (for the live elapsed clock). */
|
||||
readonly startedAtMs: number | null;
|
||||
/** Epoch ms when it finished, successfully or not. */
|
||||
readonly finishedAtMs: number | null;
|
||||
}
|
||||
|
||||
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;
|
||||
/** Bumped when sidebar-owned PR states change; the pre-run summary
|
||||
subscribes so its candidate count tracks the sidebar's partition. */
|
||||
candidateVersion: number;
|
||||
startRun: (input: {
|
||||
runId: number;
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
truncatedCount: number;
|
||||
}) => void;
|
||||
patchItem: (key: string, patch: Partial<SweepItem>) => void;
|
||||
finishRun: (runId: number) => void;
|
||||
bumpCandidateVersion: () => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const SWEEP_STORAGE_KEY = "t3code:review-sweep:v1";
|
||||
|
||||
export const useReviewSweepStore = create<ReviewSweepState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
phase: "idle",
|
||||
runId: 0,
|
||||
order: [],
|
||||
items: {},
|
||||
truncatedCount: 0,
|
||||
candidateVersion: 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)),
|
||||
bumpCandidateVersion: () =>
|
||||
set((state) => ({ candidateVersion: state.candidateVersion + 1 })),
|
||||
reset: () => set({ phase: "idle", order: [], items: {}, truncatedCount: 0 }),
|
||||
}),
|
||||
{
|
||||
name: SWEEP_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => window.localStorage),
|
||||
// candidateVersion is a live signal, not state worth keeping.
|
||||
partialize: (state) => ({
|
||||
phase: state.phase,
|
||||
runId: state.runId,
|
||||
order: state.order,
|
||||
items: state.items,
|
||||
truncatedCount: state.truncatedCount,
|
||||
}),
|
||||
merge: (persisted, current) => {
|
||||
const restored = { ...current, ...(persisted as Partial<ReviewSweepState>) };
|
||||
// In-flight RPCs don't survive a reload: anything still pending or
|
||||
// running when the page died rehydrates as a retry-able error, and
|
||||
// an interrupted run reports as complete so the header offers
|
||||
// Re-run instead of a progress bar that will never advance.
|
||||
const items = Object.fromEntries(
|
||||
Object.entries(restored.items).map(([key, item]) => [
|
||||
key,
|
||||
item.status === "pending" || item.status === "running"
|
||||
? {
|
||||
...item,
|
||||
status: "error" as const,
|
||||
errorMessage: "Interrupted by reload — retry to review this thread.",
|
||||
finishedAtMs: item.finishedAtMs ?? Date.now(),
|
||||
}
|
||||
: item,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
...restored,
|
||||
items,
|
||||
phase: restored.phase === "running" ? "complete" : restored.phase,
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
function readServerCapabilities(environmentId: EnvironmentId) {
|
||||
return appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
|
||||
.capabilities;
|
||||
}
|
||||
|
||||
/** The sweep-eligibility predicate, mirroring SidebarV2's active-card
|
||||
partition. Exported so the pre-run confirmation screen counts exactly
|
||||
the threads a run would review. */
|
||||
export function isSweepCandidate(
|
||||
shell: EnvironmentThreadShell,
|
||||
capabilities: { threadSettlement?: boolean; reviewSweep?: boolean } | undefined,
|
||||
options: { readonly now: string; readonly autoSettleAfterDays: number | null },
|
||||
): boolean {
|
||||
if (shell.archivedAt !== null) return false;
|
||||
if (capabilities?.threadSettlement !== true || capabilities.reviewSweep !== true) return false;
|
||||
// PR state comes from SidebarV2's per-row subscriptions via
|
||||
// publishSweepChangeRequestStates, so merged-PR+idle threads classify as
|
||||
// settled here exactly like they do in the sidebar. Rows that haven't
|
||||
// reported yet fall back to null (treated as unsettled) — same as a
|
||||
// freshly mounted sidebar.
|
||||
const changeRequestState =
|
||||
changeRequestStateByKey.get(scopedThreadKey(scopeThreadRef(shell.environmentId, shell.id))) ??
|
||||
null;
|
||||
return !effectiveSettled(shell, {
|
||||
now: options.now,
|
||||
autoSettleAfterDays: options.autoSettleAfterDays,
|
||||
changeRequestState,
|
||||
});
|
||||
}
|
||||
|
||||
/** Minute-quantized clock, matching SidebarV2's `nowMinute`. Using a raw
|
||||
wall clock here would disagree with the sidebar around the merged-PR
|
||||
idle boundary and include threads the sidebar already shows as settled. */
|
||||
export function sweepNowIso(): string {
|
||||
return `${new Date().toISOString().slice(0, 16)}:00.000Z`;
|
||||
}
|
||||
|
||||
/** All unsettled, unarchived threads across every connected environment that
|
||||
supports the sweep, most recently active first — the exact order the
|
||||
SWEEP_MAX_THREADS cap is applied in. */
|
||||
export function collectSweepCandidates(): EnvironmentThreadShell[] {
|
||||
const now = sweepNowIso();
|
||||
const autoSettleAfterDays = getClientSettings().sidebarAutoSettleAfterDays;
|
||||
const candidates: EnvironmentThreadShell[] = [];
|
||||
for (const ref of readThreadRefs()) {
|
||||
const shell = readThreadShell(ref);
|
||||
if (!shell) continue;
|
||||
const capabilities = readServerCapabilities(shell.environmentId);
|
||||
if (!isSweepCandidate(shell, capabilities, { now, autoSettleAfterDays })) continue;
|
||||
candidates.push(shell);
|
||||
}
|
||||
return sortSweepCandidates(candidates);
|
||||
}
|
||||
|
||||
/** Most recently active first, so the SWEEP_MAX_THREADS cap drops the
|
||||
longest-idle threads rather than the oldest-created ones. Exported so
|
||||
the pre-run summary previews the exact capped selection. */
|
||||
export function sortSweepCandidates(
|
||||
candidates: ReadonlyArray<EnvironmentThreadShell>,
|
||||
): EnvironmentThreadShell[] {
|
||||
const activityMs = (shell: EnvironmentThreadShell): number =>
|
||||
toSortableTimestamp(threadLastActivityAt(shell) ?? undefined) ??
|
||||
toSortableTimestamp(shell.createdAt) ??
|
||||
0;
|
||||
return [...candidates].sort((a, b) => activityMs(b) - activityMs(a));
|
||||
}
|
||||
|
||||
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", startedAtMs: Date.now(), finishedAtMs: null });
|
||||
|
||||
const shell = readThreadShell(item.ref);
|
||||
const canSettleNow = shell !== null && canSettle(shell, { now: new Date().toISOString() });
|
||||
const modelSelection = readSweepModelSelection();
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
reviewEnvironment.summarizeThread,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: {
|
||||
threadId: item.ref.threadId,
|
||||
canSettleNow,
|
||||
...(modelSelection !== null ? { modelSelection } : {}),
|
||||
},
|
||||
},
|
||||
{ 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,
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
} else {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
current.patchItem(key, {
|
||||
status: "error",
|
||||
errorMessage: error instanceof Error ? error.message : "Review failed.",
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Navigation callback installed by the app shell so store-level toasts can
|
||||
deep-link to /review-sweep without importing the router. */
|
||||
let navigateToSweepResults: (() => void) | null = null;
|
||||
export function setSweepResultsNavigator(navigate: (() => void) | null): void {
|
||||
navigateToSweepResults = navigate;
|
||||
}
|
||||
|
||||
function isViewingSweepResults(): boolean {
|
||||
return window.location.pathname === "/review-sweep";
|
||||
}
|
||||
|
||||
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);
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return;
|
||||
store.finishRun(runId);
|
||||
// The sweep runs in the background; only toast when the user isn't
|
||||
// already staring at the results page.
|
||||
if (!isViewingSweepResults()) {
|
||||
const actionable = Object.values(store.items).filter(
|
||||
(item) =>
|
||||
!item.dismissed &&
|
||||
((item.result?.suggestedTitle && !item.titleApplied) ||
|
||||
(item.result?.recommendSettle && !item.settleApplied) ||
|
||||
item.result?.prStatus?.mergeReady === true),
|
||||
).length;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "success",
|
||||
title: "Work review finished",
|
||||
description:
|
||||
actionable > 0
|
||||
? `${actionable} ${actionable === 1 ? "thread has" : "threads have"} recommended actions.`
|
||||
: "No actions recommended — you're caught up.",
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "View results",
|
||||
onClick: () => navigateToSweepResults?.(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,
|
||||
branch: shell.branch,
|
||||
lastActivityAt: threadLastActivityAt(shell) ?? shell.createdAt,
|
||||
status: "pending",
|
||||
result: null,
|
||||
errorMessage: null,
|
||||
titleApplied: false,
|
||||
settleApplied: false,
|
||||
dismissed: false,
|
||||
mergeStatus: "idle",
|
||||
mergeDetail: null,
|
||||
startedAtMs: null,
|
||||
finishedAtMs: null,
|
||||
}),
|
||||
);
|
||||
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 runId = store.runId;
|
||||
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;
|
||||
}
|
||||
// The rename itself succeeded either way, but a Re-run mid-flight replaces
|
||||
// the item set with fresh reviews — don't stamp stale applied-state onto
|
||||
// the new run's card.
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId === runId) {
|
||||
current.patchItem(key, { titleApplied: true, threadTitle: suggestedTitle });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function applySweepSettle(key: string): Promise<boolean> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const runId = store.runId;
|
||||
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.",
|
||||
}),
|
||||
);
|
||||
// The recommendation is now known-stale — withdraw it so the card stops
|
||||
// advertising a settle the live guard just refused.
|
||||
store.patchItem(key, {
|
||||
result: { ...item.result, recommendSettle: false, settleReason: null },
|
||||
});
|
||||
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;
|
||||
}
|
||||
// Same staleness guard as applySweepTitle: never patch a newer run's item.
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId === runId) {
|
||||
current.patchItem(key, { settleApplied: true });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sequentially apply every un-dismissed recommendation: titles first, then
|
||||
settles, tolerating per-item failures (each failure already toasts).
|
||||
Items are re-read from the store on every step so dismissals (and
|
||||
re-runs) mid-apply are respected. */
|
||||
export async function applyAllSweepRecommendations(): Promise<void> {
|
||||
const { order, runId } = useReviewSweepStore.getState();
|
||||
for (const key of order) {
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
const item = current.items[key];
|
||||
if (!item || item.dismissed) continue;
|
||||
if (item.result?.suggestedTitle && !item.titleApplied) {
|
||||
await applySweepTitle(key);
|
||||
}
|
||||
}
|
||||
for (const key of order) {
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
const item = current.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 });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Merge queue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Message sent to a thread's agent when its PR stopped merging cleanly
|
||||
because earlier queue entries landed first. */
|
||||
function conflictHandoffMessage(prNumber: number): string {
|
||||
return [
|
||||
`PR #${prNumber} no longer merges cleanly — other pull requests were merged into the base branch ahead of it.`,
|
||||
"Please rebase this branch onto the latest base branch, resolve any merge conflicts, verify the build still passes, and push the updated branch.",
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function isMergeQueueCandidate(item: SweepItem): boolean {
|
||||
return (
|
||||
!item.dismissed &&
|
||||
item.result?.prStatus?.mergeReady === true &&
|
||||
(item.mergeStatus === "idle" || item.mergeStatus === "queued")
|
||||
);
|
||||
}
|
||||
|
||||
let mergeQueueActive = false;
|
||||
|
||||
/** Merge one item's PR and settle its thread on success. On conflict, mark
|
||||
the card and hand the rebase to the thread's agent. Returns the outcome
|
||||
for queue accounting. */
|
||||
async function mergeOne(
|
||||
runId: number,
|
||||
key: string,
|
||||
): Promise<"merged" | "conflict" | "skipped" | "failed"> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return "skipped";
|
||||
const item = store.items[key];
|
||||
const prNumber = item?.result?.prStatus?.number;
|
||||
if (!item || prNumber === undefined) return "skipped";
|
||||
store.patchItem(key, { mergeStatus: "merging" });
|
||||
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
reviewEnvironment.mergePullRequest,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId, pullRequestNumber: prNumber },
|
||||
},
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
|
||||
const after = useReviewSweepStore.getState();
|
||||
if (after.runId !== runId) return "skipped";
|
||||
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
after.patchItem(key, {
|
||||
mergeStatus: "failed",
|
||||
mergeDetail: error instanceof Error ? error.message : "Merge failed.",
|
||||
});
|
||||
return "failed";
|
||||
}
|
||||
|
||||
const outcome = result.value.outcome;
|
||||
if (outcome === "merged" || outcome === "already-closed") {
|
||||
after.patchItem(key, { mergeStatus: "merged", mergeDetail: result.value.detail });
|
||||
// Merged PRs are concluded work: settle right away so the sidebar
|
||||
// reflects the merge without waiting for auto-settle.
|
||||
const settleResult = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.settle,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (settleResult._tag === "Success") {
|
||||
useReviewSweepStore.getState().patchItem(key, { settleApplied: true });
|
||||
}
|
||||
return "merged";
|
||||
}
|
||||
|
||||
if (outcome === "conflict") {
|
||||
after.patchItem(key, { mergeStatus: "conflicted", mergeDetail: result.value.detail });
|
||||
// Hand the conflict to the thread's own agent: it has the branch
|
||||
// checked out and the full context to rebase and resolve.
|
||||
await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.startTurn,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: {
|
||||
threadId: item.ref.threadId,
|
||||
message: {
|
||||
messageId: newMessageId(),
|
||||
role: "user" as const,
|
||||
text: conflictHandoffMessage(prNumber),
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
return "conflict";
|
||||
}
|
||||
|
||||
after.patchItem(key, { mergeStatus: "failed", mergeDetail: result.value.detail });
|
||||
return "failed";
|
||||
}
|
||||
|
||||
/** Merge a single card's PR (per-item button). */
|
||||
export async function mergeSweepItem(key: string): Promise<void> {
|
||||
const { runId } = useReviewSweepStore.getState();
|
||||
await mergeOne(runId, key);
|
||||
}
|
||||
|
||||
/** Merge every merge-ready PR SEQUENTIALLY — one at a time, so each merge
|
||||
sees the base branch the previous one produced and the server re-check
|
||||
catches freshly introduced conflicts. Conflicts don't stop the queue:
|
||||
the item is marked conflicted and its thread's agent is asked to rebase
|
||||
and resolve; re-run the sweep once it pushes to pick the PR back up. */
|
||||
export async function runMergeQueue(): Promise<void> {
|
||||
if (mergeQueueActive) return;
|
||||
mergeQueueActive = true;
|
||||
try {
|
||||
const { order, items, runId } = useReviewSweepStore.getState();
|
||||
const queueKeys = order.filter((key) => {
|
||||
const item = items[key];
|
||||
return item !== undefined && isMergeQueueCandidate(item);
|
||||
});
|
||||
for (const key of queueKeys) {
|
||||
useReviewSweepStore.getState().patchItem(key, { mergeStatus: "queued" });
|
||||
}
|
||||
|
||||
let mergedCount = 0;
|
||||
let conflictCount = 0;
|
||||
for (const key of queueKeys) {
|
||||
const outcome = await mergeOne(runId, key);
|
||||
if (outcome === "merged") mergedCount += 1;
|
||||
if (outcome === "conflict") conflictCount += 1;
|
||||
if (useReviewSweepStore.getState().runId !== runId) return;
|
||||
}
|
||||
|
||||
if (queueKeys.length > 0) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: conflictCount > 0 ? "warning" : "success",
|
||||
title: `Merge queue finished: ${mergedCount} of ${queueKeys.length} merged`,
|
||||
description:
|
||||
conflictCount > 0
|
||||
? `${conflictCount} ${conflictCount === 1 ? "PR hit a conflict and was" : "PRs hit conflicts and were"} handed to ${conflictCount === 1 ? "its" : "their"} thread's agent to rebase.`
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
mergeQueueActive = false;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
+74
-25
@@ -7,14 +7,27 @@ import "vite-plus/test/config";
|
||||
import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
// Single-origin dev is signalled positively, because it cannot be inferred
|
||||
// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
|
||||
// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
|
||||
// a developer with either URL in their `.env` gets it back here. Baking it then
|
||||
// pins the client to localhost and breaks every non-localhost origin — the
|
||||
// exact failure single-origin mode exists to prevent, and an invisible one
|
||||
// since the page still loads.
|
||||
const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const explicitHost = process.env.HOST?.trim();
|
||||
const host = explicitHost || "localhost";
|
||||
const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
|
||||
const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -65,7 +78,20 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
function resolveDevProxyTarget(
|
||||
backendPort: string | undefined,
|
||||
wsUrl: string | undefined,
|
||||
): string | undefined {
|
||||
// Browser dev is single-origin: the backend port is proxied through this
|
||||
// server so the app works from any origin (localhost, tailnet, LAN, phone).
|
||||
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
|
||||
const port = Number(backendPort?.trim());
|
||||
if (Number.isInteger(port) && port > 0) {
|
||||
return `http://localhost:${port}/`;
|
||||
}
|
||||
|
||||
// dev:desktop still points the renderer straight at the backend, so fall
|
||||
// back to deriving the target from the explicit websocket URL.
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -86,7 +112,17 @@ function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
|
||||
|
||||
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
|
||||
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
|
||||
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
|
||||
// Anything else (ngrok, a LAN IP alias) goes through the env var.
|
||||
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
@@ -119,6 +155,10 @@ export default defineConfig(() => {
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
|
||||
// Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
|
||||
// under single-origin dev this must stay empty even when a `.env`
|
||||
// supplies it, so the client falls back to window.location.origin.
|
||||
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
|
||||
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
|
||||
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
|
||||
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
|
||||
@@ -145,32 +185,41 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
allowedHosts,
|
||||
...(devProxyTarget
|
||||
? {
|
||||
proxy: {
|
||||
"/.well-known": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
// One entry per shared prefix; the server's dev catch-all 404s the
|
||||
// same list, so the two sides cannot drift. `/ws` is the app's own
|
||||
// socket — Vite's HMR socket is matched separately and exactly
|
||||
// (path "/" plus a vite-hmr subprotocol), so the two upgrade
|
||||
// handlers don't collide.
|
||||
proxy: Object.fromEntries(
|
||||
DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
|
||||
prefix,
|
||||
{
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
...(prefix === "/ws" ? { ws: true } : {}),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
|
||||
// host to connect reliably; dev:desktop is the only mode that sets HOST.
|
||||
// Everywhere else, leaving this unset lets the client derive it from the
|
||||
// page origin, which is what makes HMR work over Tailscale/LAN instead of
|
||||
// failing an attempt against the wrong machine's localhost first.
|
||||
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
|
||||
...(explicitHost
|
||||
? {
|
||||
hmr: {
|
||||
protocol: "ws",
|
||||
host: explicitHost,
|
||||
clientPort: port,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host,
|
||||
clientPort: port,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# Scripts
|
||||
|
||||
- `vp run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
|
||||
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
|
||||
- `vp run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.
|
||||
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
|
||||
- Pass dev-runner flags directly after the root task name, for example:
|
||||
`vp run dev --home-dir /tmp/t3code-dev`
|
||||
@@ -23,6 +25,7 @@
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
|
||||
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg -- --keep-stage`
|
||||
@@ -36,6 +39,12 @@
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Browser development
|
||||
|
||||
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
|
||||
|
||||
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-tsgo patch && vp config --no-agent",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:share": "node scripts/dev-runner.ts dev --share",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:marketing": "vp run --filter @t3tools/marketing dev",
|
||||
|
||||
@@ -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,13 @@ 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,
|
||||
}),
|
||||
mergePullRequest: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:review:merge-pull-request",
|
||||
tag: WS_METHODS.reviewMergePullRequest,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -47,6 +47,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
/** Server understands thread.snooze / thread.unsnooze commands. Same
|
||||
version-skew contract as threadSettlement. */
|
||||
threadSnooze: 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,7 @@
|
||||
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 { ModelSelection } from "./orchestration.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const ReviewDiffPreviewInput = Schema.Struct({
|
||||
@@ -34,3 +35,122 @@ 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,
|
||||
/** Model to run the review with. Defaults to the server's
|
||||
textGenerationModelSelection when omitted (older clients). */
|
||||
modelSelection: Schema.optionalKey(ModelSelection),
|
||||
});
|
||||
export type ReviewThreadSummaryInput = typeof ReviewThreadSummaryInput.Type;
|
||||
|
||||
/** Size of the thread's latest ready checkpoint diff — a cheap effort proxy
|
||||
for the review UI ("how big is this thread's change"). */
|
||||
export const ReviewThreadDiffStats = Schema.Struct({
|
||||
files: Schema.Int,
|
||||
additions: Schema.Int,
|
||||
deletions: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadDiffStats = typeof ReviewThreadDiffStats.Type;
|
||||
|
||||
/** Live pull-request context gathered during the review: state, review
|
||||
verdict, CI, and whether the PR is mergeable as-is. */
|
||||
export const ReviewThreadPrStatus = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: TrimmedNonEmptyString,
|
||||
state: Schema.Literals(["open", "closed", "merged"]),
|
||||
/** GitHub reviewDecision: APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED /
|
||||
empty (no required reviews). */
|
||||
reviewDecision: Schema.NullOr(TrimmedNonEmptyString),
|
||||
/** Rolled-up CI outcome for the head commit. */
|
||||
checksPassing: Schema.NullOr(Schema.Boolean),
|
||||
/** GitHub mergeable: whether the branch applies cleanly onto base. */
|
||||
mergeable: Schema.NullOr(Schema.Boolean),
|
||||
/** Open + clean merge + CI green + not blocked by requested changes. */
|
||||
mergeReady: Schema.Boolean,
|
||||
recentCommentCount: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadPrStatus = typeof ReviewThreadPrStatus.Type;
|
||||
|
||||
/** What the review generation itself cost, reported by the provider CLI. */
|
||||
export const ReviewThreadGenerationUsage = Schema.Struct({
|
||||
inputTokens: Schema.Int,
|
||||
outputTokens: Schema.Int,
|
||||
/** Absent when the provider doesn't report a cost. */
|
||||
costUsd: Schema.optionalKey(Schema.Number),
|
||||
durationMs: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadGenerationUsage = typeof ReviewThreadGenerationUsage.Type;
|
||||
|
||||
export const ReviewThreadSummaryResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
summary: TrimmedNonEmptyString,
|
||||
/** One imperative sentence: the user's single next action. Optional for
|
||||
pre-nextStep servers. */
|
||||
nextStep: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
/** Null when the current title is still accurate. */
|
||||
suggestedTitle: Schema.NullOr(TrimmedNonEmptyString),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(TrimmedNonEmptyString),
|
||||
/** Absent when the thread has no ready checkpoint (or pre-diff servers). */
|
||||
diffStats: Schema.optionalKey(ReviewThreadDiffStats),
|
||||
/** Absent when the thread has no PR, the lookup failed, or pre-PR servers. */
|
||||
prStatus: Schema.optionalKey(ReviewThreadPrStatus),
|
||||
/** Absent when the provider doesn't report usage. */
|
||||
usage: Schema.optionalKey(ReviewThreadGenerationUsage),
|
||||
});
|
||||
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;
|
||||
|
||||
export const ReviewMergePullRequestInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** The PR number the client saw at review time; the server re-validates
|
||||
merge-readiness against live GitHub state before merging. */
|
||||
pullRequestNumber: Schema.Int,
|
||||
});
|
||||
export type ReviewMergePullRequestInput = typeof ReviewMergePullRequestInput.Type;
|
||||
|
||||
export const ReviewMergePullRequestResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
outcome: Schema.Literals([
|
||||
"merged",
|
||||
/** Branch no longer applies cleanly (e.g. an earlier queue merge landed
|
||||
first). The client hands the conflict to the thread's agent. */
|
||||
"conflict",
|
||||
/** PR already merged or closed since the review ran. */
|
||||
"already-closed",
|
||||
/** No longer merge-ready (CI regressed, review dismissed, ...). */
|
||||
"not-ready",
|
||||
]),
|
||||
detail: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ReviewMergePullRequestResult = typeof ReviewMergePullRequestResult.Type;
|
||||
|
||||
export class ReviewMergeError extends Schema.TaggedErrorClass<ReviewMergeError>()(
|
||||
"ReviewMergeError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
detail: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const ReviewMergePullRequestError = Schema.Union([
|
||||
ReviewThreadNotFoundError,
|
||||
ReviewMergeError,
|
||||
]);
|
||||
export type ReviewMergePullRequestError = typeof ReviewMergePullRequestError.Type;
|
||||
@@ -43,6 +43,12 @@ import {
|
||||
ReviewDiffPreviewError,
|
||||
ReviewDiffPreviewInput,
|
||||
ReviewDiffPreviewResult,
|
||||
ReviewMergePullRequestError,
|
||||
ReviewMergePullRequestInput,
|
||||
ReviewMergePullRequestResult,
|
||||
ReviewThreadSummaryError,
|
||||
ReviewThreadSummaryInput,
|
||||
ReviewThreadSummaryResult,
|
||||
} from "./review.ts";
|
||||
import { KeybindingsConfigError } from "./keybindings.ts";
|
||||
import {
|
||||
@@ -181,6 +187,8 @@ export const WS_METHODS = {
|
||||
|
||||
// Review methods
|
||||
reviewGetDiffPreview: "review.getDiffPreview",
|
||||
reviewSummarizeThread: "review.summarizeThread",
|
||||
reviewMergePullRequest: "review.mergePullRequest",
|
||||
|
||||
// Terminal methods
|
||||
terminalOpen: "terminal.open",
|
||||
@@ -495,6 +503,24 @@ 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]),
|
||||
});
|
||||
|
||||
/** Merge a review-sweep thread's PR after re-validating merge readiness
|
||||
against live GitHub state. Non-exceptional failures (conflict, already
|
||||
closed, no longer ready) are outcomes, not errors, so the client's merge
|
||||
queue can branch on them. */
|
||||
export const WsReviewMergePullRequestRpc = Rpc.make(WS_METHODS.reviewMergePullRequest, {
|
||||
payload: ReviewMergePullRequestInput,
|
||||
success: ReviewMergePullRequestResult,
|
||||
error: Schema.Union([ReviewMergePullRequestError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
payload: TerminalOpenInput,
|
||||
success: TerminalSessionSnapshot,
|
||||
@@ -738,6 +764,8 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsVcsSwitchRefRpc,
|
||||
WsVcsInitRpc,
|
||||
WsReviewGetDiffPreviewRpc,
|
||||
WsReviewSummarizeThreadRpc,
|
||||
WsReviewMergePullRequestRpc,
|
||||
WsTerminalOpenRpc,
|
||||
WsTerminalAttachRpc,
|
||||
WsTerminalWriteRpc,
|
||||
|
||||
@@ -194,6 +194,14 @@
|
||||
"./httpReadiness": {
|
||||
"types": "./src/httpReadiness.ts",
|
||||
"import": "./src/httpReadiness.ts"
|
||||
},
|
||||
"./devHome": {
|
||||
"types": "./src/devHome.ts",
|
||||
"import": "./src/devHome.ts"
|
||||
},
|
||||
"./devProxy": {
|
||||
"types": "./src/devProxy.ts",
|
||||
"import": "./src/devProxy.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "./devHome.ts";
|
||||
|
||||
const makeRepo = (
|
||||
kind:
|
||||
| "worktree"
|
||||
| "checkout"
|
||||
| "bare"
|
||||
| "submodule"
|
||||
| "unreadable-git-file"
|
||||
| "bare-repo-worktree"
|
||||
| "custom-common-dir-worktree",
|
||||
) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devhome-"));
|
||||
if (kind === "worktree") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");
|
||||
} else if (kind === "bare-repo-worktree") {
|
||||
// `git worktree add` from a bare repo: the common dir is `<name>.git`.
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/myrepo.git/worktrees/x\n");
|
||||
} else if (kind === "custom-common-dir-worktree") {
|
||||
// $GIT_COMMON_DIR need not be named `.git` at all.
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/store/worktrees/x\n");
|
||||
} else if (kind === "submodule") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: ../.git/modules/sub\n");
|
||||
} else if (kind === "unreadable-git-file") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "not a gitdir pointer\n");
|
||||
} else if (kind === "checkout") {
|
||||
NodeFS.mkdirSync(NodePath.join(root, ".git"));
|
||||
}
|
||||
const nested = NodePath.join(root, "apps", "web", "src");
|
||||
NodeFS.mkdirSync(nested, { recursive: true });
|
||||
return { root, nested };
|
||||
}),
|
||||
({ root }) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
describe("resolveGitWorktreePath", () => {
|
||||
it.effect("finds a worktree root from a nested directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a main checkout as not a linked worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("checkout");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a directory outside a repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("bare");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a submodule as not a linked worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("submodule");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a .git file without a usable gitdir pointer", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("unreadable-git-file");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("finds a worktree of a bare repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("bare-repo-worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("finds a worktree whose common dir is not named .git", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("custom-common-dir-worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveWorktreeT3Home", () => {
|
||||
it.effect("answers with .t3 before the dev runner creates it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
const home = yield* resolveWorktreeT3Home(nested);
|
||||
assert.equal(home, NodePath.join(NodePath.resolve(root), ".t3"));
|
||||
assert.isFalse(NodeFS.existsSync(home ?? ""));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Where development state lives, and how to keep it away from the shared
|
||||
* `~/.t3` that a user's installed T3 Code runs against.
|
||||
*
|
||||
* A linked git worktree gets its own (gitignored) `.t3`: feature work in a
|
||||
* throwaway branch must not share a database with the real app, and an ambient
|
||||
* `T3CODE_HOME` counts as an explicit base dir — flipping the state directory
|
||||
* from `<base>/dev` to `<base>/userdata`, the live production database.
|
||||
*/
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
/**
|
||||
* A `.git` file points at the real git directory. A linked worktree's lives at
|
||||
* `<common-dir>/worktrees/<name>`; a submodule's at
|
||||
* `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the
|
||||
* file-vs-directory distinction alone — is what identifies a worktree.
|
||||
*
|
||||
* The common dir is not necessarily named `.git`: a worktree of a bare repo
|
||||
* points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be
|
||||
* anything. So match on the `worktrees/<name>` tail, which git always uses,
|
||||
* rather than on the name of the directory containing it.
|
||||
*/
|
||||
const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {
|
||||
const gitdir = gitFileContents
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.startsWith("gitdir:"))
|
||||
?.slice("gitdir:".length)
|
||||
.trim();
|
||||
if (gitdir === undefined || gitdir.length === 0) {
|
||||
return false;
|
||||
}
|
||||
// Compare as path segments so a directory merely named `…worktrees…` cannot
|
||||
// match as a substring. Trailing separators normalize away first.
|
||||
const segments = path
|
||||
.normalize(gitdir.replaceAll("\\", "/"))
|
||||
.split(/[/\\]/)
|
||||
.filter((segment) => segment.length > 0);
|
||||
// `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,
|
||||
// and something must precede it. This excludes `<git-dir>/modules/<name>`.
|
||||
return segments.length >= 3 && segments.at(-2) === "worktrees";
|
||||
};
|
||||
|
||||
/**
|
||||
* The path of the linked git worktree containing `cwd`, or undefined when
|
||||
* `cwd` is not inside one. Git marks a linked worktree by making `.git` a file
|
||||
* whose `gitdir:` points into the repository's `.git/worktrees`.
|
||||
*
|
||||
* Walks up to the repository root, so running from a subdirectory resolves the
|
||||
* same worktree as running from the top.
|
||||
*/
|
||||
export const resolveGitWorktreePath = (
|
||||
cwd: string,
|
||||
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
let directory = path.resolve(cwd);
|
||||
for (;;) {
|
||||
const gitPath = path.join(directory, ".git");
|
||||
const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
|
||||
if (Option.isSome(info)) {
|
||||
// A directory means the main checkout. Stop either way: nesting one
|
||||
// repository inside another does not make the outer one this root.
|
||||
if (info.value.type !== "File") {
|
||||
return undefined;
|
||||
}
|
||||
// A submodule also has a `.git` file, but it is not a worktree of this
|
||||
// repository and gets no worktree-local home.
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(gitPath)
|
||||
.pipe(Effect.orElseSucceed(() => ""));
|
||||
return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
|
||||
}
|
||||
const parent = path.dirname(directory);
|
||||
if (parent === directory) {
|
||||
return undefined;
|
||||
}
|
||||
directory = parent;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The worktree-local data directory for `cwd`, or undefined outside a linked
|
||||
* worktree. Deliberately does not require the directory to exist yet: falling
|
||||
* back because it is missing would send callers at the shared home.
|
||||
*/
|
||||
export const resolveWorktreeT3Home = (
|
||||
cwd: string,
|
||||
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const worktreePath = yield* resolveGitWorktreePath(cwd);
|
||||
if (worktreePath === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const path = yield* Path.Path;
|
||||
return path.join(worktreePath, ".t3");
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Backend paths the web dev server proxies in single-origin browser dev.
|
||||
*
|
||||
* Two consumers must agree on this list: the Vite proxy map
|
||||
* (apps/web/vite.config.ts) that forwards these to the backend, and the
|
||||
* server's dev catch-all (apps/server/src/http.ts) that 404s them instead of
|
||||
* redirecting back to Vite. Drift is silent and nasty in both directions — a
|
||||
* prefix only Vite knows gets answered with index.html; a prefix only the
|
||||
* server knows redirect-loops through the proxy.
|
||||
*/
|
||||
export const DEV_PROXIED_PATH_PREFIXES = ["/api", "/oauth", "/.well-known", "/ws"] as const;
|
||||
|
||||
export function isDevProxiedPath(pathname: string): boolean {
|
||||
return DEV_PROXIED_PATH_PREFIXES.some(
|
||||
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,13 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(
|
||||
},
|
||||
);
|
||||
|
||||
export const HostProcessWorkingDirectory = Context.Reference<string>(
|
||||
"@t3tools/shared/hostProcess/HostProcessWorkingDirectory",
|
||||
{
|
||||
defaultValue: () => process.cwd(),
|
||||
},
|
||||
);
|
||||
|
||||
export const HostProcessExecutablePath = Context.Reference<string>(
|
||||
"@t3tools/shared/hostProcess/HostProcessExecutablePath",
|
||||
{
|
||||
|
||||
@@ -25,6 +25,44 @@ import {
|
||||
} from "./tailscale.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/**
|
||||
* Asserts nothing reachable from `error` contains `secret`. Recurses through
|
||||
* nested objects, arrays, and `cause` chains rather than checking only
|
||||
* top-level strings: a leak one level down (say, a wrapped cause carrying raw
|
||||
* stderr) is just as visible in a log, and a shallow check would pass it.
|
||||
*
|
||||
* Walks values instead of serializing so it holds for fields added later, and
|
||||
* tracks visited objects so a cyclic cause chain terminates.
|
||||
*/
|
||||
function assertCarriesNoSecret(error: object, secret: string): void {
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
const walk = (value: unknown, path: string): void => {
|
||||
if (typeof value === "string") {
|
||||
assert.notInclude(value, secret, `${path} leaked stderr`);
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object" || value === null || seen.has(value)) {
|
||||
return;
|
||||
}
|
||||
seen.add(value);
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
|
||||
return;
|
||||
}
|
||||
// `message` and `cause` are getters on Error subclasses, so they are not
|
||||
// own enumerable properties and Object.entries alone would skip them.
|
||||
walk((value as { message?: unknown }).message, `${path}.message`);
|
||||
walk((value as { cause?: unknown }).cause, `${path}.cause`);
|
||||
for (const [key, nested] of Object.entries(value)) {
|
||||
walk(nested, `${path}.${key}`);
|
||||
}
|
||||
};
|
||||
|
||||
walk(error, "error");
|
||||
}
|
||||
const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
|
||||
const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
|
||||
|
||||
@@ -194,6 +232,26 @@ describe("tailscale", () => {
|
||||
assert.notProperty(error, "stderr");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
assert.equal(error.message, "tailscale status exited with code 7.");
|
||||
assert.equal(error.stderrDiagnostic, "not-logged-in");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies unrecognized stderr without quoting it", () => {
|
||||
const layer = mockSpawnerLayer(() => ({
|
||||
code: 3,
|
||||
stderr: "something novel went wrong for node fluffy-badger tskey-auth-secret-token-value",
|
||||
}));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
|
||||
|
||||
assert.instanceOf(error, TailscaleCommandExitError);
|
||||
// Unmatched stderr degrades to "unknown" rather than passing text
|
||||
// through — that fallback is what keeps novel output from leaking.
|
||||
assert.equal(error.stderrDiagnostic, "unknown");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
assertCarriesNoSecret(error, "fluffy-badger");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,6 +311,10 @@ describe("tailscale", () => {
|
||||
assert.notProperty(error, "command");
|
||||
assert.notProperty(error, "stderr");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
// The diagnostic classifies the failure without quoting stderr, so the
|
||||
// key cannot reach a log through it either.
|
||||
assert.equal(error.stderrDiagnostic, "permission-denied");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -23,6 +23,37 @@ const TailscaleCommandContext = {
|
||||
argumentCount: Schema.Number,
|
||||
};
|
||||
|
||||
/**
|
||||
* Failure kinds we can name without quoting the CLI. Anything unrecognized
|
||||
* becomes "unknown" rather than falling back to raw text — stderr can contain
|
||||
* auth keys (`tskey-…`) and node names, and these labels are logged.
|
||||
*/
|
||||
export const TailscaleStderrDiagnostic = Schema.Literals([
|
||||
"no-existing-handler",
|
||||
"not-logged-in",
|
||||
"permission-denied",
|
||||
"unknown",
|
||||
]);
|
||||
export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
|
||||
|
||||
// Matched against stderr, most specific first. Patterns are deliberately short
|
||||
// and anchored on tailscale's own wording.
|
||||
const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
|
||||
readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
|
||||
> = [
|
||||
[/handler does not exist/i, "no-existing-handler"],
|
||||
[/not logged in|logged out|needs? login/i, "not-logged-in"],
|
||||
[/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
|
||||
];
|
||||
|
||||
/** Classifies stderr into a safe label, dropping the text itself. */
|
||||
export const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
|
||||
if (stderr.trim().length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
|
||||
};
|
||||
|
||||
export class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(
|
||||
"TailscaleCommandSpawnError",
|
||||
{
|
||||
@@ -54,6 +85,12 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
|
||||
exitCode: Schema.Number,
|
||||
stdoutLength: Schema.optional(Schema.Number),
|
||||
stderrLength: Schema.Number,
|
||||
// A classified diagnostic, never raw CLI output. `tailscale` prints auth
|
||||
// keys and node identifiers into stderr, and this field is surfaced in
|
||||
// dev-runner logs — so it carries only a known-safe label from the closed
|
||||
// set below. Callers that need to recognize a specific failure (e.g.
|
||||
// `serve off` on a port with no mapping) match on the label.
|
||||
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
@@ -212,6 +249,9 @@ export const readTailscaleStatus = Effect.gen(function* () {
|
||||
exitCode,
|
||||
stdoutLength: stdout.length,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
return yield* parseTailscaleStatus(stdout);
|
||||
@@ -275,6 +315,9 @@ const runTailscaleCommand = (
|
||||
...commandContext,
|
||||
exitCode,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
|
||||
Generated
+3
@@ -905,6 +905,9 @@ importers:
|
||||
'@t3tools/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../packages/shared
|
||||
'@t3tools/tailscale':
|
||||
specifier: workspace:*
|
||||
version: link:../packages/tailscale
|
||||
effect:
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
|
||||
|
||||
+553
-2
@@ -1,6 +1,14 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
HostProcessWorkingDirectory,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -14,8 +22,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
checkPortAvailabilityOnHosts,
|
||||
createDevRunnerEnv,
|
||||
devPortProbeHosts,
|
||||
findFirstAvailableOffset,
|
||||
getDevRunnerModeArgs,
|
||||
isBrowserAllowedPort,
|
||||
resolveModePortOffsets,
|
||||
resolveOffset,
|
||||
runDevRunnerWithInput,
|
||||
@@ -58,6 +68,7 @@ const devServerInput = {
|
||||
port: 13_773,
|
||||
devUrl: undefined,
|
||||
dryRun: false,
|
||||
share: false,
|
||||
runArgs: ["--inspect", "secret-token-value"],
|
||||
} as const;
|
||||
|
||||
@@ -336,8 +347,175 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_PORT, "13773");
|
||||
assert.equal(env.PORT, "5733");
|
||||
}),
|
||||
);
|
||||
|
||||
// Browser dev is single-origin: Vite proxies the backend, and the client
|
||||
// resolves it from window.location.origin. Baking a localhost URL here is
|
||||
// what breaks sharing a dev server to another device.
|
||||
for (const mode of ["dev", "dev:web"] as const) {
|
||||
it.effect(`leaves the client backend URLs unset in ${mode} mode`, () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode,
|
||||
baseEnv: {
|
||||
VITE_HTTP_URL: "http://localhost:1234",
|
||||
VITE_WS_URL: "ws://localhost:1234",
|
||||
},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.VITE_HTTP_URL, undefined);
|
||||
assert.equal(env.VITE_WS_URL, undefined);
|
||||
assert.equal(env.T3CODE_PORT, "13773");
|
||||
// Deleting the keys is not sufficient — vite.config.ts merges
|
||||
// `.env`/`.env.local` underneath this env and would revive them, so
|
||||
// the intent has to be stated positively.
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, "1");
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop pins the renderer at loopback deliberately; an ambient marker
|
||||
// must not make Vite discard those URLs.
|
||||
it.effect("clears the single-origin marker in dev:desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
|
||||
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears the single-origin marker in dev:server mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
|
||||
assert.equal(env.VITE_HTTP_URL, "http://localhost:13773");
|
||||
assert.equal(env.VITE_WS_URL, "ws://localhost:13773");
|
||||
}),
|
||||
);
|
||||
|
||||
// HOST is Vite's bind address and gates the HMR pin in vite.config.ts. An
|
||||
// inherited one would survive into browser dev and point HMR at the wrong
|
||||
// interface — invisible over a shared origin, since the page still loads.
|
||||
for (const mode of ["dev", "dev:web"] as const) {
|
||||
it.effect(`drops an inherited HOST in ${mode} mode`, () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode,
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, undefined);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// --host configures the *backend* (T3CODE_HOST). It must not become Vite's
|
||||
// bind address by way of an inherited HOST that happens to agree with it.
|
||||
it.effect("drops an inherited HOST even when --host is given", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: "0.0.0.0",
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, undefined);
|
||||
assert.equal(env.T3CODE_HOST, "0.0.0.0");
|
||||
}),
|
||||
);
|
||||
|
||||
// Desktop sets HOST itself, so the clearing must not reach it.
|
||||
it.effect("still pins HOST for dev:desktop", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps explicit backend URLs for the desktop renderer", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
|
||||
assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:13773");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -370,6 +548,41 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips browser-blocked web ports before probing availability", () =>
|
||||
Effect.gen(function* () {
|
||||
const probed: Array<{ port: number; role: string | undefined }> = [];
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
// 5733 + 833 = 6566, which browsers block as sane-port.
|
||||
startOffset: 833,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: (port, role) => {
|
||||
probed.push({ port, role });
|
||||
return Effect.succeed(true);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(offset, 834);
|
||||
assert.deepStrictEqual(probed, [
|
||||
{ port: 14_607, role: "server" },
|
||||
{ port: 6567, role: "web" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not reject a server-only offset because its unused web port is blocked", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
startOffset: 833,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
assert.equal(offset, 833);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows offsets where the non-required server port exceeds max", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
@@ -406,6 +619,19 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("isBrowserAllowedPort", () => {
|
||||
it.each([6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697])(
|
||||
"rejects Fetch-blocked web port %s from the worktree offset range",
|
||||
(port) => {
|
||||
assert.equal(isBrowserAllowedPort(port), false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([5733, 5900, 6567, 6670, 8733])("allows browser-safe web port %s", (port) => {
|
||||
assert.equal(isBrowserAllowedPort(port), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkPortAvailabilityOnHosts", () => {
|
||||
it.effect("checks overlapping hosts sequentially to avoid self-interference", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -436,6 +662,59 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("devPortProbeHosts", () => {
|
||||
it.effect("probes loopback only when no bind host is configured", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts(undefined), ["127.0.0.1", "::1"]);
|
||||
assert.deepStrictEqual(devPortProbeHosts(" "), ["127.0.0.1", "::1"]);
|
||||
}),
|
||||
);
|
||||
|
||||
// A port free on loopback can be taken on the interface the server will
|
||||
// actually bind, so --host/T3CODE_HOST has to be probed as well.
|
||||
it.effect("adds a non-loopback bind host to the probe list", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts("0.0.0.0"), ["127.0.0.1", "::1", "0.0.0.0"]);
|
||||
assert.deepStrictEqual(devPortProbeHosts("192.168.1.10"), [
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"192.168.1.10",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not probe loopback twice when it is the configured host", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts("127.0.0.1"), ["127.0.0.1", "::1"]);
|
||||
}),
|
||||
);
|
||||
|
||||
// Only the backend honours --host/T3CODE_HOST. Vite reads HOST (set for
|
||||
// desktop only), so judging the web port against the backend's interface
|
||||
// would reject ports for a server that never binds there.
|
||||
it.effect("passes the port role so only the server port sees the bind host", () =>
|
||||
Effect.gen(function* () {
|
||||
const probed: Array<{ port: number; role: string | undefined }> = [];
|
||||
|
||||
yield* resolveModePortOffsets({
|
||||
mode: "dev",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: (port, role) => {
|
||||
probed.push({ port, role });
|
||||
return Effect.succeed(true);
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(probed, [
|
||||
{ port: 13_773, role: "server" },
|
||||
{ port: 5733, role: "web" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveModePortOffsets", () => {
|
||||
it.effect("uses a shared fallback offset for dev mode", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -569,6 +848,170 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
// `tailscale serve` config outlives the process, so a dry run that shared
|
||||
// would replace and then tear down whatever mapping the port already had.
|
||||
// Base-dir precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME)
|
||||
// lives in runDevRunnerWithInput; the env builder must not consult the
|
||||
// ambient variable on its own, or it would silently outrank the worktree
|
||||
// default and land dev state on the user's real database.
|
||||
it.effect("ignores an ambient T3CODE_HOME when no home is resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: { T3CODE_HOME: "/home/user/.t3" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_HOME, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
// Sharing dev:desktop would publish a URL whose renderer dials the
|
||||
// visitor's own loopback, and would clobber the VITE_DEV_SERVER_URL that
|
||||
// Electron loads from. It must decline, not half-work.
|
||||
it.effect("declines to share for dev:desktop and still starts the stack", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev:desktop",
|
||||
port: undefined,
|
||||
share: true,
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// Single-origin browser dev proxies the backend at localhost, so a backend
|
||||
// bound only to a specific interface breaks every proxied request in a way
|
||||
// that looks like a broken server. Reject the combination up front.
|
||||
it.effect("rejects a specific non-loopback --host for browser dev modes", () => {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
host: "192.168.1.10",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "DevRunnerHostNotProxiableError") {
|
||||
assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.mode, "dev");
|
||||
assert.equal(error.host, "192.168.1.10");
|
||||
assert.include(error.message, "0.0.0.0");
|
||||
assert.include(error.message, "--share");
|
||||
});
|
||||
});
|
||||
|
||||
// Wildcards keep loopback answering, so the proxy target stays valid and
|
||||
// the combination must keep working — it is the documented way to serve a
|
||||
// LAN interface and the browser proxy at once.
|
||||
it.effect("still spawns the stack for a wildcard --host in dev mode", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
host: "0.0.0.0",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// dev:server does not proxy — the client talks to the backend directly —
|
||||
// so a specific interface bind stays legitimate there.
|
||||
it.effect("keeps a specific --host working for dev:server", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
host: "192.168.1.10",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("spawns nothing when --dry-run is combined with --share", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
dryRun: true,
|
||||
share: true,
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 0);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("reports non-zero exits without manufacturing a cause", () => {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -629,5 +1072,113 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
assert.notInclude(error.message, "secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
describe("t3 home precedence", () => {
|
||||
const makeWorktree = Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devrunner-"));
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(root, ".git"),
|
||||
"gitdir: /elsewhere/.git/worktrees/x\n",
|
||||
);
|
||||
return root;
|
||||
}),
|
||||
(root) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
const spawnedHome = (input: {
|
||||
readonly t3Home: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly ambientHome: string | undefined;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
let captured: Record<string, string | undefined> | undefined;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
captured = (
|
||||
command as {
|
||||
readonly options?: { readonly env?: Record<string, string | undefined> };
|
||||
}
|
||||
).options?.env;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* runDevRunnerWithInput({ ...devServerInput, t3Home: input.t3Home }).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.provideService(HostProcessWorkingDirectory, input.cwd),
|
||||
Effect.provideService(
|
||||
HostProcessEnvironment,
|
||||
input.ambientHome === undefined ? {} : { T3CODE_HOME: input.ambientHome },
|
||||
),
|
||||
);
|
||||
|
||||
return captured?.T3CODE_HOME;
|
||||
});
|
||||
|
||||
it.effect("prefers an explicit --home-dir over the worktree default", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: "/tmp/explicit-home",
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.resolve("/tmp/explicit-home"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("treats a blank --home-dir as unset rather than as a selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: " ",
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.join(path.resolve(root), ".t3"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("prefers the worktree .t3 over an ambient T3CODE_HOME", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.join(path.resolve(root), ".t3"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("falls back to an ambient T3CODE_HOME outside a worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: NodeOS.tmpdir(),
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.resolve("/home/user/.t3"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the home implicit with no worktree and no ambient value", () =>
|
||||
Effect.gen(function* () {
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: NodeOS.tmpdir(),
|
||||
ambientHome: undefined,
|
||||
});
|
||||
assert.equal(home, undefined);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+287
-28
@@ -5,7 +5,8 @@ import * as NodeOS from "node:os";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -18,6 +19,7 @@ import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
|
||||
import { loadRepoEnv } from "./lib/public-config.ts";
|
||||
|
||||
Object.assign(process.env, loadRepoEnv());
|
||||
@@ -27,7 +29,43 @@ const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
|
||||
// HTTP(S) requests to these ports are blocked by the Fetch standard before a
|
||||
// browser reaches the network. Keep the complete list here so explicit or
|
||||
// future wider offsets cannot produce a URL that curl accepts but browsers
|
||||
// reject. https://fetch.spec.whatwg.org/#port-blocking
|
||||
const FETCH_BAD_PORTS = new Set([
|
||||
0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
|
||||
103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
|
||||
512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
|
||||
995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
|
||||
6669, 6679, 6697, 10080,
|
||||
]);
|
||||
// Dev servers bind loopback, so loopback is the only interface whose
|
||||
// availability decides whether we can use a port. Probing wildcards too made
|
||||
// the runner walk away from a perfectly free port whenever something else held
|
||||
// the same number on another interface — `tailscale serve` does exactly that,
|
||||
// which silently moved the ports out from under a URL that had just been shared.
|
||||
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
|
||||
|
||||
/**
|
||||
* Bind hosts on which a backend still answers `http://localhost:<port>`, which
|
||||
* is where single-origin browser dev proxies to. Loopback and the wildcards
|
||||
* qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
|
||||
* that address and the proxy target goes dark.
|
||||
*/
|
||||
export function isProxiableBindHost(host: string): boolean {
|
||||
const normalized = host.trim();
|
||||
return (
|
||||
normalized === "" ||
|
||||
normalized === "localhost" ||
|
||||
normalized === "127.0.0.1" ||
|
||||
normalized === "::1" ||
|
||||
normalized === "[::1]" ||
|
||||
normalized === "0.0.0.0" ||
|
||||
normalized === "::" ||
|
||||
normalized === "[::]"
|
||||
);
|
||||
}
|
||||
|
||||
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(NodeOS.homedir(), ".t3"),
|
||||
@@ -48,7 +86,15 @@ const MODE_ARGS = {
|
||||
} as const satisfies Record<string, ReadonlyArray<string>>;
|
||||
|
||||
type DevMode = keyof typeof MODE_ARGS;
|
||||
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
|
||||
/**
|
||||
* `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
|
||||
* web port is always loopback. Passed explicitly rather than inferred from the
|
||||
* port number, which stops distinguishing them under a large port offset.
|
||||
*/
|
||||
type PortAvailabilityCheck<R = never> = (
|
||||
port: number,
|
||||
role?: "server" | "web",
|
||||
) => Effect.Effect<boolean, never, R>;
|
||||
|
||||
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
|
||||
|
||||
@@ -56,6 +102,10 @@ export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
|
||||
return MODE_ARGS[mode];
|
||||
}
|
||||
|
||||
export function isBrowserAllowedPort(port: number): boolean {
|
||||
return !FETCH_BAD_PORTS.has(port);
|
||||
}
|
||||
|
||||
export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
|
||||
"DevRunnerConfigurationError",
|
||||
{
|
||||
@@ -128,8 +178,21 @@ export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunner
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<DevRunnerHostNotProxiableError>()(
|
||||
"DevRunnerHostNotProxiableError",
|
||||
{
|
||||
mode: Schema.Literals(["dev", "dev:web"]),
|
||||
host: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DevRunnerError = Schema.Union([
|
||||
DevRunnerConfigurationError,
|
||||
DevRunnerHostNotProxiableError,
|
||||
DevRunnerInvalidPortOffsetError,
|
||||
DevRunnerPortExhaustedError,
|
||||
DevRunnerProcessError,
|
||||
@@ -166,6 +229,7 @@ const OffsetConfig = Config.all({
|
||||
export function resolveOffset(config: {
|
||||
readonly portOffset: number | undefined;
|
||||
readonly devInstance: string | undefined;
|
||||
readonly worktreePath?: string | undefined;
|
||||
}): Effect.Effect<
|
||||
{ readonly offset: number; readonly source: string },
|
||||
DevRunnerInvalidPortOffsetError
|
||||
@@ -187,19 +251,30 @@ export function resolveOffset(config: {
|
||||
}
|
||||
|
||||
const seed = config.devInstance?.trim();
|
||||
if (!seed) {
|
||||
return Effect.succeed({ offset: 0, source: "default ports" });
|
||||
if (seed) {
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return Effect.succeed({
|
||||
offset: Number(seed),
|
||||
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
|
||||
});
|
||||
}
|
||||
|
||||
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return Effect.succeed({
|
||||
offset: Number(seed),
|
||||
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
|
||||
});
|
||||
// Worktrees get ports derived from their path so each one is stable across
|
||||
// restarts and distinct from its siblings. Without this every worktree starts
|
||||
// at offset 0 and scan-collides onto whatever happens to be free that minute,
|
||||
// so ports move under you between runs — which breaks any URL you already
|
||||
// shared. The main checkout keeps the documented 5733/13773.
|
||||
const worktreePath = config.worktreePath?.trim();
|
||||
if (worktreePath) {
|
||||
const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
|
||||
}
|
||||
|
||||
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
|
||||
return Effect.succeed({ offset: 0, source: "default ports" });
|
||||
}
|
||||
|
||||
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
|
||||
@@ -245,7 +320,9 @@ export function createDevRunnerEnv({
|
||||
return Effect.gen(function* () {
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
|
||||
// Precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME) is resolved
|
||||
// by the caller; an unset t3Home here genuinely means "use the default".
|
||||
const configuredBaseDir = t3Home?.trim() || undefined;
|
||||
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
|
||||
const isDesktopMode = mode === "dev:desktop";
|
||||
|
||||
@@ -265,12 +342,41 @@ export function createDevRunnerEnv({
|
||||
|
||||
if (!isDesktopMode) {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
// HOST is Vite's own bind address, and the desktop branch below is the
|
||||
// only place we set it. An inherited one (an exported HOST, a container,
|
||||
// a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
|
||||
// its HMR socket to that address — see the `explicitHost` gate in
|
||||
// apps/web/vite.config.ts. Over a shared origin that is invisible: the
|
||||
// page loads and only HMR quietly dials the wrong machine.
|
||||
delete output.HOST;
|
||||
if (mode === "dev" || mode === "dev:web") {
|
||||
// Browser dev is single-origin: everything (including /ws) is proxied
|
||||
// through Vite, so the client must resolve its backend from
|
||||
// window.location.origin rather than a baked-in localhost URL. See
|
||||
// resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
|
||||
// — it only defers to the origin when both of these are absent. Baking
|
||||
// localhost here is what breaks any non-localhost origin (tailnet, LAN,
|
||||
// phone): the remote browser dials its own machine.
|
||||
delete output.VITE_HTTP_URL;
|
||||
delete output.VITE_WS_URL;
|
||||
// Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
|
||||
// which merges `.env`/`.env.local` *under* this env, so a developer
|
||||
// with either URL in their `.env` would get it back and silently lose
|
||||
// single-origin mode. This states the intent positively so Vite can
|
||||
// ignore those values rather than infer from their absence.
|
||||
output.T3CODE_SINGLE_ORIGIN_DEV = "1";
|
||||
} else {
|
||||
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
delete output.T3CODE_SINGLE_ORIGIN_DEV;
|
||||
}
|
||||
} else {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
|
||||
// Desktop pins the renderer to loopback on purpose; an ambient marker
|
||||
// must not make Vite drop those URLs.
|
||||
delete output.T3CODE_SINGLE_ORIGIN_DEV;
|
||||
delete output.T3CODE_MODE;
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
delete output.T3CODE_HOST;
|
||||
@@ -341,13 +447,41 @@ export function checkPortAvailabilityOnHosts<R>(
|
||||
});
|
||||
}
|
||||
|
||||
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService.NetService> = (port) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService.NetService;
|
||||
return yield* checkPortAvailabilityOnHosts(port, DEV_PORT_PROBE_HOSTS, (candidatePort, host) =>
|
||||
net.canListenOnHost(candidatePort, host),
|
||||
);
|
||||
});
|
||||
/**
|
||||
* Hosts to probe for a dev server bound to `configuredHost`.
|
||||
*
|
||||
* Loopback is always checked because the web server and the desktop renderer
|
||||
* target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
|
||||
* another interface, that interface decides whether the bind actually
|
||||
* succeeds — probing only loopback would hand back a port that is free here
|
||||
* and taken there, and the server would fail to start.
|
||||
*
|
||||
* `configuredHost` applies to the *backend* only. Vite takes its bind address
|
||||
* from `HOST`, which the runner sets for desktop alone, so the web port stays
|
||||
* on loopback and must not be judged against the backend's interface —
|
||||
* a port free on loopback but busy on that interface would otherwise be
|
||||
* rejected for a server that was never going to bind there.
|
||||
*/
|
||||
export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
|
||||
const host = configuredHost?.trim();
|
||||
if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
|
||||
return DEV_PORT_PROBE_HOSTS;
|
||||
}
|
||||
return [...DEV_PORT_PROBE_HOSTS, host];
|
||||
}
|
||||
|
||||
const makeDefaultCheckPortAvailability =
|
||||
(configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
|
||||
(port, role) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService.NetService;
|
||||
const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
|
||||
return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
|
||||
net.canListenOnHost(candidatePort, host),
|
||||
);
|
||||
});
|
||||
|
||||
const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
|
||||
|
||||
interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
|
||||
readonly startOffset: number;
|
||||
@@ -379,12 +513,16 @@ export function findFirstAvailableOffset<R = NetService.NetService>({
|
||||
break;
|
||||
}
|
||||
|
||||
if (requireWebPort && !isBrowserAllowedPort(webPort)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const checks: Array<Effect.Effect<boolean, never, R>> = [];
|
||||
if (requireServerPort) {
|
||||
checks.push(checkPort(serverPort));
|
||||
checks.push(checkPort(serverPort, "server"));
|
||||
}
|
||||
if (requireWebPort) {
|
||||
checks.push(checkPort(webPort));
|
||||
checks.push(checkPort(webPort, "web"));
|
||||
}
|
||||
|
||||
if (checks.length === 0) {
|
||||
@@ -480,6 +618,7 @@ interface DevRunnerCliInput {
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly dryRun: boolean;
|
||||
readonly share: boolean;
|
||||
readonly runArgs: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
@@ -495,22 +634,55 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
),
|
||||
);
|
||||
|
||||
const { offset, source } = yield* resolveOffset({ portOffset, devInstance });
|
||||
// Single-origin browser dev proxies the backend at localhost. A wildcard
|
||||
// bind still answers there; a specific non-loopback interface does not,
|
||||
// which breaks every proxied request in a way that reads as "server is
|
||||
// broken" rather than "flag combination is unsupported". Reject it up
|
||||
// front instead. (dev:server and dev:desktop don't proxy — untouched.)
|
||||
if (
|
||||
(input.mode === "dev" || input.mode === "dev:web") &&
|
||||
input.host !== undefined &&
|
||||
!isProxiableBindHost(input.host)
|
||||
) {
|
||||
return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
|
||||
}
|
||||
|
||||
const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
|
||||
|
||||
const { offset, source } = yield* resolveOffset({
|
||||
portOffset,
|
||||
devInstance,
|
||||
worktreePath,
|
||||
});
|
||||
|
||||
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
|
||||
mode: input.mode,
|
||||
startOffset: offset,
|
||||
hasExplicitServerPort: input.port !== undefined,
|
||||
hasExplicitDevUrl: input.devUrl !== undefined,
|
||||
// A non-loopback bind host decides whether the backend can actually take
|
||||
// the port, so it has to be probed alongside loopback.
|
||||
checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
|
||||
});
|
||||
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
// A dev server started inside a worktree defaults to that worktree's own
|
||||
// (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
|
||||
// outrank an ambient T3CODE_HOME. `--home-dir` still wins.
|
||||
const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
|
||||
// Trim before choosing: `--home-dir ""` is not a selection, and treating it
|
||||
// as one would skip the worktree default and land on the shared home —
|
||||
// exactly the outcome this precedence exists to prevent.
|
||||
const resolvedT3Home =
|
||||
(input.t3Home?.trim() || undefined) ??
|
||||
worktreeHome ??
|
||||
(hostEnvironment.T3CODE_HOME?.trim() || undefined);
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: input.mode,
|
||||
baseEnv: hostEnvironment,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
t3Home: input.t3Home,
|
||||
t3Home: resolvedT3Home,
|
||||
browser: input.browser,
|
||||
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents: input.logWebSocketEvents,
|
||||
@@ -529,10 +701,90 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
|
||||
);
|
||||
|
||||
// Before the share block: --dry-run only resolves and prints. Sharing would
|
||||
// replace, then tear down, whatever mapping the port already had — a
|
||||
// surprising side effect from a command documented as inert.
|
||||
if (input.dryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sharedWebPort = BASE_WEB_PORT + webOffset;
|
||||
if (input.share) {
|
||||
if (input.mode === "dev:server") {
|
||||
yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
|
||||
} else if (input.mode === "dev:desktop") {
|
||||
// Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
|
||||
// VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
|
||||
// and then watch it dial its own 127.0.0.1 for the backend. Worse,
|
||||
// sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
|
||||
// Electron itself loads the renderer from. Refuse rather than hand out
|
||||
// a URL that is broken in a way the user cannot see.
|
||||
yield* Effect.logWarning(
|
||||
"[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
|
||||
);
|
||||
} else {
|
||||
// acquireRelease, not share-then-addFinalizer: the mapping outlives this
|
||||
// process (and reboots), so the cleanup has to be registered atomically
|
||||
// with creating it. An interrupt landing in between would otherwise
|
||||
// leave a mapping pointing at a port nothing is listening on.
|
||||
//
|
||||
// Deliberately no ownership tracking beyond that: if a second runner
|
||||
// takes this port during a fast restart, the first's exit can briefly
|
||||
// tear down the new mapping — visible (the URL stops working) and fixed
|
||||
// by re-running --share. A lease protocol closing that window existed
|
||||
// and was removed as more machinery than a dev convenience warrants.
|
||||
//
|
||||
// A tailnet that isn't up shouldn't stop the dev server from starting —
|
||||
// warn, and carry on serving locally.
|
||||
const shared = yield* Effect.acquireRelease(
|
||||
shareDevServer({ webPort: sharedWebPort }),
|
||||
() =>
|
||||
// Serve config outlives this process, so a cleanup that did not
|
||||
// take leaves a tailnet URL pointing at a port nothing serves.
|
||||
unshareDevServer(sharedWebPort).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.cleared
|
||||
? Effect.void
|
||||
: Effect.logWarning(
|
||||
`[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
|
||||
result.explanation ? `: ${result.explanation}` : ""
|
||||
}. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Effect.tapError((error: DevShareError) =>
|
||||
Effect.logWarning(
|
||||
`[dev-runner] could not share on the tailnet: ${error.message}${
|
||||
error.hint ? ` — ${error.hint}` : ""
|
||||
}`,
|
||||
),
|
||||
),
|
||||
Effect.option,
|
||||
Effect.map(Option.getOrUndefined),
|
||||
);
|
||||
|
||||
if (shared) {
|
||||
// The app is reached from the tailnet origin. Vite already allows
|
||||
// *.ts.net hosts; the backend needs the origin for credentialed
|
||||
// requests that bypass the proxy (desktop renderer, direct calls).
|
||||
env.T3CODE_DEV_ALLOWED_ORIGINS = [
|
||||
env.T3CODE_DEV_ALLOWED_ORIGINS,
|
||||
new URL(shared.url).origin,
|
||||
]
|
||||
.filter((entry) => entry && entry.length > 0)
|
||||
.join(",");
|
||||
// The server builds its pairing URL from this, so the URL printed at
|
||||
// startup is already the shareable one — no rewriting by hand. An
|
||||
// explicit --dev-url still wins.
|
||||
if (input.devUrl === undefined) {
|
||||
env.VITE_DEV_SERVER_URL = shared.url;
|
||||
}
|
||||
yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
"vp",
|
||||
[...MODE_ARGS[input.mode], ...input.runArgs],
|
||||
@@ -592,9 +844,10 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
),
|
||||
t3Home: Flag.string("home-dir").pipe(
|
||||
Flag.withDescription(
|
||||
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
|
||||
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
|
||||
),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
browser: Flag.boolean("browser").pipe(
|
||||
Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
|
||||
@@ -631,6 +884,12 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
share: Flag.boolean("share").pipe(
|
||||
Flag.withDescription(
|
||||
"Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
|
||||
),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
runArgs: Argument.string("run-arg").pipe(
|
||||
Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
|
||||
Argument.variadic(),
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
type DevShareError,
|
||||
DevServeFailedError,
|
||||
shareDevServer,
|
||||
unshareDevServer,
|
||||
} from "./dev-share.ts";
|
||||
|
||||
const TAILNET_STATUS = JSON.stringify({ Self: { DNSName: "host.example.ts.net." } });
|
||||
const NO_HANDLER_STDERR = "error: failed to remove web serve: handler does not exist";
|
||||
|
||||
interface CallResult {
|
||||
readonly exitCode: number;
|
||||
readonly stderr?: string;
|
||||
}
|
||||
|
||||
const encode = (value: string) => Stream.make(new TextEncoder().encode(value));
|
||||
|
||||
/**
|
||||
* Answers `tailscale status --json` with a valid tailnet name, and lets each
|
||||
* test set the outcome of the `off` (pre-clear) and `serve` calls separately —
|
||||
* they are the same subcommand and are told apart by the trailing `off`.
|
||||
*/
|
||||
const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallResult }) =>
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
|
||||
const result: CallResult = args.includes("status")
|
||||
? { exitCode: 0 }
|
||||
: args.includes("off")
|
||||
? (input.off ?? { exitCode: 0 })
|
||||
: (input.serve ?? { exitCode: 0 });
|
||||
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: args.includes("status") ? encode(TAILNET_STATUS) : Stream.empty,
|
||||
stderr: result.stderr ? encode(result.stderr) : Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
describe("unshareDevServer", () => {
|
||||
it.effect("treats a removed mapping as cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 0 } })),
|
||||
);
|
||||
assert.isTrue(result.cleared);
|
||||
}),
|
||||
);
|
||||
|
||||
// `tailscale serve … off` exits 1 when the port had no mapping, which is the
|
||||
// normal first-share case — the port is clear, so this must not be an error.
|
||||
it.effect("treats a missing handler as cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
|
||||
);
|
||||
assert.isTrue(result.cleared);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a genuine removal failure as not cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
|
||||
);
|
||||
assert.isFalse(result.cleared);
|
||||
assert.include(result.explanation, "permission denied");
|
||||
// Structured, so a wrapping error can keep the real chain.
|
||||
assert.equal(result.cause?._tag, "TailscaleCommandExitError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("shareDevServer", () => {
|
||||
it.effect("returns the tailnet URL for the same port", () =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
|
||||
);
|
||||
|
||||
assert.equal(shared.host, "host.example.ts.net");
|
||||
assert.equal(shared.url, "https://host.example.ts.net:5788/");
|
||||
}),
|
||||
);
|
||||
|
||||
// The stale-mapping clear runs before serve, so a failure here leaves the
|
||||
// port serving nothing. Saying only "serve failed" would let an operator
|
||||
// assume their previous mapping survived.
|
||||
it.effect("reports that the prior mapping was cleared when serve fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
off: { exitCode: 0 },
|
||||
serve: { exitCode: 1, stderr: "port already in use" },
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
assert.equal(error.stage, "serve");
|
||||
assert.equal(error.webPort, 5788);
|
||||
// The underlying failure is preserved rather than flattened to a string.
|
||||
assert.equal(
|
||||
(error.cause as { _tag?: string } | undefined)?._tag,
|
||||
"TailscaleCommandExitError",
|
||||
);
|
||||
// Unclassifiable stderr is never quoted (it can carry auth keys), so the
|
||||
// message points at the command instead of echoing the CLI.
|
||||
assert.notInclude(error.message, "port already in use");
|
||||
assert.include(error.message, "run the command by hand");
|
||||
assert.include(error.message, "no longer served");
|
||||
assert.include(error.message, "5788");
|
||||
}),
|
||||
);
|
||||
|
||||
// A recognized failure gets our own wording for it — enough to act on
|
||||
// without passing CLI text through.
|
||||
it.effect("explains a recognized serve failure without quoting stderr", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
off: { exitCode: 0 },
|
||||
serve: {
|
||||
exitCode: 1,
|
||||
stderr: "permission denied for tskey-auth-secret-token-value",
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
assert.equal(error.stage, "serve");
|
||||
assert.include(error.message, "permission denied");
|
||||
assert.include(error.message, "elevated privileges");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
}),
|
||||
);
|
||||
|
||||
// Serving over routes we could not remove yields a URL that loads but whose
|
||||
// /ws and /api quietly point at a dead backend.
|
||||
it.effect("refuses to serve when the existing mapping could not be cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
// A distinct stage: the prior mapping survived, so nothing was replaced.
|
||||
assert.equal(error.stage, "clear-existing");
|
||||
assert.include(error.message, "could not clear the existing mapping");
|
||||
assert.include(error.message, "permission denied");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Shares a running dev server on the local tailnet via `tailscale serve`, so it
|
||||
* can be opened from a phone, another laptop, or by whoever is reviewing the
|
||||
* work.
|
||||
*
|
||||
* Thin wrapper over `@t3tools/tailscale` (the same client the server's own
|
||||
* `--tailscale-serve` uses). What it adds is dev-share semantics: replacing a
|
||||
* stale mapping left by a killed run, and refusing to serve over routes it
|
||||
* could not remove.
|
||||
*
|
||||
* Because browser dev is single-origin (Vite proxies the backend — see
|
||||
* `resolveDevProxyTarget` in apps/web/vite.config.ts), one proxy rule covering
|
||||
* the web port is enough; the backend needs no mapping of its own.
|
||||
*/
|
||||
|
||||
import {
|
||||
buildTailscaleHttpsBaseUrl,
|
||||
disableTailscaleServe,
|
||||
ensureTailscaleServe,
|
||||
readTailscaleStatus,
|
||||
type TailscaleCommandError,
|
||||
type TailscaleStderrDiagnostic,
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
/**
|
||||
* Human-readable gloss for each diagnostic. Deliberately our own words rather
|
||||
* than the CLI's: tailscale prints auth keys and node names into stderr, and
|
||||
* this string is logged.
|
||||
*/
|
||||
const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
|
||||
"no-existing-handler": "no mapping existed for that port",
|
||||
"not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
|
||||
"permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
|
||||
unknown: undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Our own wording for why a tailscale command failed, derived from the
|
||||
* classified diagnostic. Never the CLI's text — see `stderrDiagnosticOf`.
|
||||
*/
|
||||
const explainCommandFailure = (error: TailscaleCommandError): string | undefined =>
|
||||
error._tag === "TailscaleCommandExitError" && error.stderrDiagnostic !== undefined
|
||||
? (DIAGNOSTIC_EXPLANATIONS[error.stderrDiagnostic] ?? "run the command by hand to see why")
|
||||
: undefined;
|
||||
|
||||
/**
|
||||
* Three distinct failures, three classes: each has its own caller-visible
|
||||
* message and its own remedy, and `shareDevServer` chooses between them
|
||||
* structurally. A single error with a `reason` discriminator would encode that
|
||||
* distinction twice and put a lookup table in the `message` getter.
|
||||
*
|
||||
* Each wraps a real underlying failure and so keeps it as `cause`; the message
|
||||
* is derived only from the structural fields, never from `cause.message`.
|
||||
*/
|
||||
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
|
||||
"TailscaleUnavailableError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "could not talk to tailscale";
|
||||
}
|
||||
|
||||
get hint(): string {
|
||||
return "Is Tailscale installed and tailscaled running? Try `tailscale status` — or drop --share and open the printed localhost URL.";
|
||||
}
|
||||
}
|
||||
|
||||
/** No underlying failure: the status read succeeded and simply had no name. */
|
||||
export class TailnetNameMissingError extends Schema.TaggedErrorClass<TailnetNameMissingError>()(
|
||||
"TailnetNameMissingError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "this machine has no tailnet DNS name";
|
||||
}
|
||||
|
||||
get hint(): string {
|
||||
return "Run `tailscale up` and make sure MagicDNS is enabled.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `stage` is a genuine multi-value discriminator: both stages share the same
|
||||
* semantics (a `tailscale serve` invocation failed for this port) and differ
|
||||
* only in which one, which the message states plainly.
|
||||
*/
|
||||
export class DevServeFailedError extends Schema.TaggedErrorClass<DevServeFailedError>()(
|
||||
"DevServeFailedError",
|
||||
{
|
||||
stage: Schema.Literals(["clear-existing", "serve"]),
|
||||
webPort: Schema.Number,
|
||||
explanation: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const port = String(this.webPort);
|
||||
const base =
|
||||
this.stage === "clear-existing"
|
||||
? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
|
||||
: `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
|
||||
return this.explanation ? `${base}: ${this.explanation}` : base;
|
||||
}
|
||||
|
||||
get hint(): undefined {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const DevShareError = Schema.Union([
|
||||
TailscaleUnavailableError,
|
||||
TailnetNameMissingError,
|
||||
DevServeFailedError,
|
||||
]);
|
||||
export type DevShareError = typeof DevShareError.Type;
|
||||
export const isDevShareError = Schema.is(DevShareError);
|
||||
|
||||
/**
|
||||
* Removes any mapping for `webPort`, reporting whether the port is now clear.
|
||||
*
|
||||
* Runs uninterruptibly: this is called from a finalizer on the way out of an
|
||||
* interrupted program, and cancelling the cleanup subprocess would leave
|
||||
* exactly the stale mapping it exists to remove.
|
||||
*/
|
||||
export const unshareDevServer = (
|
||||
webPort: number,
|
||||
): Effect.Effect<
|
||||
{
|
||||
readonly cleared: boolean;
|
||||
readonly explanation?: string | undefined;
|
||||
// Kept structured so a caller wrapping this can preserve the real error
|
||||
// chain rather than a flattened string.
|
||||
readonly cause?: TailscaleCommandError | undefined;
|
||||
},
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> =>
|
||||
disableTailscaleServe({ servePort: webPort }).pipe(
|
||||
Effect.as({ cleared: true } as const),
|
||||
Effect.catch((error: TailscaleCommandError) =>
|
||||
Effect.succeed(
|
||||
// "Nothing was mapped" leaves the port clear either way.
|
||||
error._tag === "TailscaleCommandExitError" &&
|
||||
error.stderrDiagnostic === "no-existing-handler"
|
||||
? ({ cleared: true } as const)
|
||||
: ({
|
||||
cleared: false,
|
||||
...(explainCommandFailure(error) !== undefined
|
||||
? { explanation: explainCommandFailure(error) }
|
||||
: {}),
|
||||
cause: error,
|
||||
} as const),
|
||||
),
|
||||
),
|
||||
Effect.uninterruptible,
|
||||
);
|
||||
|
||||
export interface DevShareResult {
|
||||
readonly url: string;
|
||||
readonly host: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes `webPort` on the tailnet at the same port number and returns the
|
||||
* resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.
|
||||
*/
|
||||
export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
|
||||
readonly webPort: number;
|
||||
}) {
|
||||
const status = yield* readTailscaleStatus.pipe(
|
||||
Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),
|
||||
);
|
||||
if (status.magicDnsName === null) {
|
||||
return yield* new TailnetNameMissingError();
|
||||
}
|
||||
|
||||
// Clear any mapping left behind by a run that was killed before its finalizer
|
||||
// could fire. Serve config survives both the process and a reboot, and a
|
||||
// stale entry may carry path routes we no longer want — older versions mapped
|
||||
// /ws, /api and friends to a separate backend port, and serving "/" alone
|
||||
// would leave those pointing at a port nothing is listening on.
|
||||
const cleared = yield* unshareDevServer(input.webPort);
|
||||
if (!cleared.cleared) {
|
||||
// Serving over routes we failed to remove would hand out a URL that is
|
||||
// broken in a way the user cannot see: the page loads while /ws and /api
|
||||
// silently resolve to a dead backend. Better to refuse and say why.
|
||||
return yield* new DevServeFailedError({
|
||||
stage: "clear-existing",
|
||||
webPort: input.webPort,
|
||||
...(cleared.explanation !== undefined ? { explanation: cleared.explanation } : {}),
|
||||
...(cleared.cause !== undefined ? { cause: cleared.cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
yield* ensureTailscaleServe({ localPort: input.webPort, servePort: input.webPort }).pipe(
|
||||
Effect.mapError((error) => {
|
||||
const explanation = explainCommandFailure(error);
|
||||
return new DevServeFailedError({
|
||||
stage: "serve",
|
||||
webPort: input.webPort,
|
||||
...(explanation !== undefined ? { explanation } : {}),
|
||||
cause: error,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
url: buildTailscaleHttpsBaseUrl({
|
||||
magicDnsName: status.magicDnsName,
|
||||
servePort: input.webPort,
|
||||
}),
|
||||
host: status.magicDnsName,
|
||||
} satisfies DevShareResult;
|
||||
});
|
||||
@@ -10,6 +10,7 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"pngjs": "7.0.0",
|
||||
"yaml": "catalog:"
|
||||
|
||||
Reference in new issue
Block a user