Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57ae612f0e | ||
|
|
afdc17c415 | ||
|
|
1153afb4fb | ||
|
|
a2ffb122e2 | ||
|
|
3957a95818 | ||
|
|
6a3df51707 | ||
|
|
6afbed3c36 | ||
|
|
eea3ea4c6f | ||
|
|
10bca3f44e | ||
|
|
e77f42c111 | ||
|
|
6e3b73884b | ||
|
|
5ba6ef7f84 | ||
|
|
80ead5f3a7 | ||
|
|
32af2f0024 | ||
|
|
f0121f31d0 | ||
|
|
0e19c103ef |
No files matched your search
@@ -864,6 +864,7 @@ jobs:
|
||||
echo "Deploying hosted web app for $channel_name channel."
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--prod \
|
||||
--skip-domain \
|
||||
--yes \
|
||||
|
||||
@@ -22,9 +22,17 @@ import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
describe("fitPictureInPictureContentSize", () => {
|
||||
it("fits landscape and portrait viewports without letterboxing the window", () => {
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([480, 270]);
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 9 / 16)).toEqual([240, 427]);
|
||||
it("preserves the PiP content area across aspect-ratio changes", () => {
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([523, 294]);
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 9 / 16)).toEqual([294, 523]);
|
||||
});
|
||||
|
||||
it("does not collapse toward the minimum size when orientation changes repeatedly", () => {
|
||||
const portrait = PreviewManager.fitPictureInPictureContentSize([523, 294], 9 / 16);
|
||||
const landscape = PreviewManager.fitPictureInPictureContentSize(portrait, 16 / 9);
|
||||
|
||||
expect(portrait).toEqual([294, 523]);
|
||||
expect(landscape).toEqual([523, 294]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -741,10 +749,30 @@ describe("PreviewManager", () => {
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
|
||||
// Chromium reports UnknownVizError while a hidden guest warms its
|
||||
// first compositor frame, so transient failures are retried.
|
||||
capturePage.mockClear();
|
||||
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
|
||||
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
|
||||
const retriedFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const retriedExit = yield* Fiber.join(retriedFiber);
|
||||
expect(Exit.isSuccess(retriedExit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(3);
|
||||
|
||||
// A persistent failure still surfaces once the retries are spent.
|
||||
capturePage.mockClear();
|
||||
const captureCause = new Error("capture failed");
|
||||
capturePage.mockRejectedValueOnce(captureCause);
|
||||
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
|
||||
capturePage.mockRejectedValue(captureCause);
|
||||
const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const exit = yield* Fiber.join(failingFiber);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(3);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
@@ -758,6 +786,36 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("stops capture retries when the tab swaps to another guest", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const capturePage = vi.fn(async () => ({
|
||||
toPNG: () => Buffer.from("png"),
|
||||
toJPEG: () => Buffer.from("jpeg"),
|
||||
getSize: () => ({ width: 100, height: 80 }),
|
||||
}));
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
// Fail persistently, then swap the tab onto a different web contents:
|
||||
// retrying against the detached guest would capture the wrong page.
|
||||
capturePage.mockClear();
|
||||
capturePage.mockRejectedValue(new Error("UnknownVizError"));
|
||||
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
|
||||
yield* manager.registerWebview("tab_1", 43);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const exit = yield* Fiber.join(fiber);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures hidden preview recordings independently for concurrent tabs", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1065,7 +1123,7 @@ describe("PreviewManager", () => {
|
||||
skipTransformProcessType: true,
|
||||
});
|
||||
expect(pictureInPictureWindow.setAspectRatio.mock.calls).toEqual([[0], [1280 / 720]]);
|
||||
expect(pictureInPictureWindow.setContentSize).toHaveBeenCalledWith(480, 270, false);
|
||||
expect(pictureInPictureWindow.setContentSize).toHaveBeenCalledWith(523, 294, false);
|
||||
expect(pictureInPictureWindow.setAspectRatio.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
pictureInPictureWindow.setContentSize.mock.invocationCallOrder[0] ?? 0,
|
||||
);
|
||||
|
||||
@@ -44,6 +44,7 @@ import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -98,12 +99,21 @@ const MAX_EVALUATION_BYTES = 64_000;
|
||||
const MAX_VISIBLE_TEXT_LENGTH = 20_000;
|
||||
const MAX_INTERACTIVE_ELEMENTS = 200;
|
||||
const MAX_SCREENSHOT_WIDTH = 1280;
|
||||
/**
|
||||
* Chromium reports UnknownVizError while a hidden or freshly attached guest is
|
||||
* warming its first compositor frame. Background frame capture already rides
|
||||
* this out via its scheduled loop; one-shot captures need their own retry or a
|
||||
* snapshot taken against a backgrounded preview fails outright.
|
||||
*/
|
||||
const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
|
||||
const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
|
||||
const RECORDING_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);
|
||||
const RECORDING_JPEG_QUALITY = 80;
|
||||
const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
|
||||
const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
|
||||
const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
|
||||
const PICTURE_IN_PICTURE_MIN_HEIGHT = 160;
|
||||
const PICTURE_IN_PICTURE_ASPECT_RATIO_EPSILON = 0.002;
|
||||
const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
@@ -164,8 +174,8 @@ export const fitPictureInPictureContentSize = (
|
||||
): readonly [width: number, height: number] => {
|
||||
const currentWidth = Math.max(1, current[0] ?? PICTURE_IN_PICTURE_INITIAL_WIDTH);
|
||||
const currentHeight = Math.max(1, current[1] ?? PICTURE_IN_PICTURE_INITIAL_HEIGHT);
|
||||
let width =
|
||||
currentWidth / currentHeight > aspectRatio ? currentHeight * aspectRatio : currentWidth;
|
||||
const currentArea = currentWidth * currentHeight;
|
||||
let width = Math.sqrt(currentArea * aspectRatio);
|
||||
let height = width / aspectRatio;
|
||||
const minimumScale = Math.max(
|
||||
1,
|
||||
@@ -509,6 +519,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try: evaluate,
|
||||
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
|
||||
});
|
||||
/**
|
||||
* capturePage for one-shot captures (snapshots, screenshots), retrying the
|
||||
* transient compositor warm-up failure instead of surfacing it to callers.
|
||||
*
|
||||
* Retries stop as soon as the tab no longer points at this guest, so a
|
||||
* webview swap during the retry window surfaces the original failure instead
|
||||
* of capturing from a detached web contents.
|
||||
*/
|
||||
const capturePageWithRetry = (
|
||||
errorContext: PreviewOperationContext,
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
) => {
|
||||
const guestIsCurrent = Effect.gen(function* () {
|
||||
if (wc.isDestroyed()) return false;
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
return tabs.get(tabId)?.webContentsId === wc.id;
|
||||
});
|
||||
return attemptPromise(errorContext, () => wc.capturePage()).pipe(
|
||||
Effect.retry({
|
||||
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
|
||||
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
|
||||
while: () => guestIsCurrent,
|
||||
}),
|
||||
);
|
||||
};
|
||||
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
const currentMillis = Clock.currentTimeMillis;
|
||||
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>
|
||||
@@ -1946,13 +1982,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const [createdAt, millis, image] = yield* Effect.all([
|
||||
currentIso,
|
||||
currentMillis,
|
||||
attemptPromise(
|
||||
capturePageWithRetry(
|
||||
{
|
||||
operation: "captureScreenshot.capturePage",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.capturePage(),
|
||||
tabId,
|
||||
wc,
|
||||
),
|
||||
]);
|
||||
const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}`;
|
||||
@@ -2074,7 +2111,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
tabId,
|
||||
);
|
||||
const aspectRatio = frame.width / frame.height;
|
||||
if (previousAspectRatio !== aspectRatio) {
|
||||
if (
|
||||
previousAspectRatio === undefined ||
|
||||
Math.abs(previousAspectRatio - aspectRatio) > PICTURE_IN_PICTURE_ASPECT_RATIO_EPSILON
|
||||
) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "pictureInPicture.setAspectRatio",
|
||||
@@ -2617,13 +2657,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const [accessibility, sourceImage, diagnostics, timelines] = yield* Effect.all([
|
||||
send("Accessibility.getFullAXTree"),
|
||||
attemptPromise(
|
||||
capturePageWithRetry(
|
||||
{
|
||||
operation: "automationSnapshot.capturePage",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.capturePage(),
|
||||
tabId,
|
||||
wc,
|
||||
),
|
||||
Ref.get(diagnosticsRef),
|
||||
Ref.get(actionTimelineRef),
|
||||
|
||||
@@ -101,8 +101,8 @@
|
||||
"expo-web-browser": "~56.0.5",
|
||||
"expo-widgets": "~56.0.19",
|
||||
"punycode": "^2.3.1",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
|
||||
@@ -16,11 +16,16 @@ import { expect } from "vite-plus/test";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
ModelSelection,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
GitCommandError,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
@@ -29,6 +34,7 @@ import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceContr
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
|
||||
@@ -65,38 +71,7 @@ function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
generateThreadTitle: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string }, TextGenerationError>;
|
||||
}
|
||||
type FakeGitTextGeneration = TextGeneration.TextGeneration["Service"];
|
||||
|
||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||
|
||||
@@ -640,6 +615,7 @@ function preparePullRequestThread(
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
@@ -648,7 +624,7 @@ function makeManager(input?: {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest(input?.serverSettings);
|
||||
|
||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
@@ -672,6 +648,9 @@ function makeManager(input?: {
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
|
||||
Layer.mock(ProviderRegistry.ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner,
|
||||
input?.setupScriptRunner ?? {
|
||||
@@ -1568,8 +1547,22 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Use a direct tone.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Implement stacked git actions", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
@@ -1579,6 +1572,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(generatedPolicy).toMatchObject({ commitInstructions: "Use a direct tone." });
|
||||
expect(result.toast).toMatchObject({
|
||||
description: "Implement stacked git actions",
|
||||
cta: {
|
||||
@@ -1598,6 +1592,118 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves custom style when instructions are empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Preserve custom style", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "custom",
|
||||
inferRepositoryConventions: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back when the dedicated source control writer is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
const missingInstanceId = ProviderInstanceId.make("missing_writer");
|
||||
let generatedModelSelection:
|
||||
| TextGeneration.CommitMessageGenerationInput["modelSelection"]
|
||||
| undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
providerInstances: {
|
||||
[missingInstanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: missingInstanceId,
|
||||
model: "missing-model",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedModelSelection = input.modelSelection;
|
||||
return Effect.succeed({ subject: "Use the available writer", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedModelSelection).toEqual(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves repository conventions style when recent history is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* runGit(repoDir, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(repoDir, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(repoDir, ["config", "user.name", "Test User"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\n");
|
||||
yield* runGit(repoDir, ["add", "README.md"]);
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "repo_conventions" as const,
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Create initial commit", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "repo_conventions",
|
||||
commitInstructions:
|
||||
"Follow the repository's established commit message style when examples are available.",
|
||||
changeRequestInstructions:
|
||||
"Follow the repository's established change request title and body style when examples are available.",
|
||||
inferRepositoryConventions: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses custom commit message when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2535,6 +2641,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(repoDir, ".github", "pull_request_template.md"),
|
||||
"## What changed?\n\n## Verification",
|
||||
);
|
||||
yield* runGit(repoDir, ["add", ".github/pull_request_template.md"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Add pull request template"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
@@ -2543,8 +2656,26 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
let generatedPolicy: TextGeneration.PrContentGenerationInput["policy"] = undefined;
|
||||
let generatedChangeRequestTemplate: string | undefined;
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Lead with user impact.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generatePrContent: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
generatedChangeRequestTemplate = input.changeRequestTemplate;
|
||||
return Effect.succeed({
|
||||
title: "Add stacked git actions",
|
||||
body: "## What changed?\nAdded stacked git actions.",
|
||||
});
|
||||
},
|
||||
},
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
@@ -2569,6 +2700,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(generatedPolicy).toMatchObject({
|
||||
changeRequestInstructions: "Lead with user impact.",
|
||||
});
|
||||
expect(generatedChangeRequestTemplate).toBe("## What changed?\n\n## Verification");
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
ModelSelection,
|
||||
type SourceControlWritingStyleSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
@@ -44,12 +45,19 @@ import {
|
||||
|
||||
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import {
|
||||
conventionalCommitsTextGenerationPolicy,
|
||||
customTextGenerationPolicy,
|
||||
repositoryConventionsTextGenerationPolicy,
|
||||
} from "../textGeneration/TextGenerationPresets.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { detectPrTemplate } from "../sourceControl/PrTemplateDetection.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
@@ -61,6 +69,11 @@ export interface GitRunStackedActionOptions {
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
interface SourceControlTextGenerationSettings {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly style: SourceControlWritingStyleSettings;
|
||||
}
|
||||
|
||||
export class GitManager extends Context.Service<
|
||||
GitManager,
|
||||
{
|
||||
@@ -565,11 +578,58 @@ export const make = Effect.gen(function* () {
|
||||
const gitCore = yield* GitVcsDriver.GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
|
||||
|
||||
const readRecentCommitSubjects = (cwd: string) =>
|
||||
gitCore
|
||||
.execute({
|
||||
operation: "GitManager.readRecentCommitSubjects",
|
||||
cwd,
|
||||
args: ["log", "-n", "20", "--no-merges", "--pretty=format:%s"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
Effect.orElseSucceed(() => []),
|
||||
);
|
||||
|
||||
const resolveStylePolicy = (cwd: string, style: SourceControlWritingStyleSettings) =>
|
||||
Effect.gen(function* () {
|
||||
switch (style.mode) {
|
||||
case "conventional_commits":
|
||||
return conventionalCommitsTextGenerationPolicy;
|
||||
case "custom":
|
||||
return customTextGenerationPolicy(
|
||||
style.customInstructions
|
||||
? {
|
||||
commitInstructions: style.customInstructions,
|
||||
changeRequestInstructions: style.customInstructions,
|
||||
}
|
||||
: {},
|
||||
);
|
||||
case "repo_conventions": {
|
||||
const subjects = yield* readRecentCommitSubjects(cwd);
|
||||
if (subjects.length === 0) {
|
||||
return repositoryConventionsTextGenerationPolicy;
|
||||
}
|
||||
const examples = ["Recent commit subjects from this repository:", ...subjects].join("\n");
|
||||
return {
|
||||
...repositoryConventionsTextGenerationPolicy,
|
||||
commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
|
||||
changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
const randomUUIDv4 = (cwd: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
@@ -1330,7 +1390,7 @@ export const make = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
modelSelection: ModelSelection;
|
||||
settings: SourceControlTextGenerationSettings;
|
||||
}) {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
if (!context) {
|
||||
@@ -1349,6 +1409,8 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
const policy = yield* resolveStylePolicy(input.cwd, input.settings.style);
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
@@ -1356,7 +1418,8 @@ export const make = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
modelSelection: input.modelSelection,
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: input.settings.modelSelection,
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -1370,7 +1433,7 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const runCommitStep = Effect.fn("runCommitStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
action: "commit" | "commit_push" | "commit_push_pr",
|
||||
branch: string | null,
|
||||
@@ -1405,7 +1468,7 @@ export const make = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
@@ -1483,7 +1546,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runPrStep = Effect.fn("runPrStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
@@ -1532,6 +1595,11 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
|
||||
const policy = yield* resolveStylePolicy(cwd, settings.style);
|
||||
const changeRequestTemplate =
|
||||
settings.style.followChangeRequestTemplates && provider.kind === "github"
|
||||
? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))
|
||||
: undefined;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd,
|
||||
@@ -1540,7 +1608,9 @@ export const make = Effect.gen(function* () {
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
modelSelection,
|
||||
...(changeRequestTemplate ? { changeRequestTemplate } : {}),
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: settings.modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(
|
||||
@@ -1820,7 +1890,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
@@ -1832,7 +1902,7 @@ export const make = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -1921,8 +1991,23 @@ export const make = Effect.gen(function* () {
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
const modelSelection = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.textGenerationModelSelection),
|
||||
const textGenerationSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? Effect.succeed({
|
||||
modelSelection: settings.textGenerationModelSelection,
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})
|
||||
: providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) => ({
|
||||
modelSelection: ServerSettings.resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
providers,
|
||||
),
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
@@ -1942,7 +2027,7 @@ export const make = Effect.gen(function* () {
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
@@ -1968,7 +2053,7 @@ export const make = Effect.gen(function* () {
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
Effect.flatMap(() =>
|
||||
runCommitStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
commitAction,
|
||||
currentBranch,
|
||||
@@ -2005,7 +2090,7 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
Effect.flatMap(() =>
|
||||
runPrStep(modelSelection, input.cwd, currentBranch, progress.emit),
|
||||
runPrStep(textGenerationSettings, input.cwd, currentBranch, progress.emit),
|
||||
),
|
||||
)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
@@ -23,7 +23,6 @@ const invocation = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
const client = McpSchema.McpServerClient.of({
|
||||
clientId: 1,
|
||||
|
||||
@@ -74,7 +74,15 @@ const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
|
||||
? authorization.slice("Bearer ".length).trim()
|
||||
: "";
|
||||
const invocation = yield* registry.resolve(token);
|
||||
if (!invocation) return unauthorized;
|
||||
if (!invocation) {
|
||||
// Without this the only symptom of a dead credential is the agent
|
||||
// quietly losing the whole `t3-code` toolkit for the rest of its
|
||||
// session, with nothing on the server to explain why.
|
||||
yield* Effect.logWarning("rejected MCP request with an unusable credential", {
|
||||
reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
|
||||
});
|
||||
return unauthorized;
|
||||
}
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.map(normalizeMcpHttpResponse),
|
||||
|
||||
@@ -17,7 +17,6 @@ it.effect("reports the scoped credential context when preview capability is unav
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -16,7 +16,6 @@ export interface McpInvocationScope {
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly capabilities: ReadonlySet<McpCapability>;
|
||||
readonly issuedAt: number;
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
export class McpInvocationContext extends Context.Service<
|
||||
|
||||
@@ -23,8 +23,7 @@ const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
||||
McpSessionRegistry.__testing
|
||||
.make({
|
||||
now,
|
||||
idleTimeoutMs: 100,
|
||||
maximumLifetimeMs: 1_000,
|
||||
livenessWindowMs: 100,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, httpServer),
|
||||
@@ -75,7 +74,7 @@ it.effect("builds MCP endpoints from the bound server host", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("expires credentials after inactivity", () =>
|
||||
it.effect("expires credentials once their session stops showing signs of life", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
@@ -88,3 +87,43 @@ it.effect("expires credentials after inactivity", () =>
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a credential alive across turns that never touch an MCP tool", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const threadId = ThreadId.make("thread-3");
|
||||
const issued = yield* registry.issue({
|
||||
threadId,
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
|
||||
// Well past the liveness window in total, but each turn reports in before
|
||||
// it lapses — this is the long-session case that used to lose the toolkit.
|
||||
for (let turn = 0; turn < 10; turn += 1) {
|
||||
timestamp += 99;
|
||||
yield* registry.touch(threadId);
|
||||
}
|
||||
|
||||
expect((yield* registry.resolve(token))?.threadId).toBe(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not keep credentials of other threads alive", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const issued = yield* registry.issue({
|
||||
threadId: ThreadId.make("thread-4"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
|
||||
timestamp += 99;
|
||||
yield* registry.touch(ThreadId.make("thread-unrelated"));
|
||||
timestamp += 2;
|
||||
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
@@ -18,7 +18,6 @@ export interface McpCredentialRequest {
|
||||
|
||||
export interface McpIssuedCredential {
|
||||
readonly config: McpProviderSession.McpProviderSessionConfig;
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryShape {
|
||||
@@ -26,6 +25,12 @@ export interface McpSessionRegistryShape {
|
||||
readonly resolve: (
|
||||
rawToken: string,
|
||||
) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
|
||||
/**
|
||||
* Records a sign of life for every credential bound to `threadId`. Provider
|
||||
* turns call this so that a session which is plainly alive keeps its
|
||||
* credential even when it goes a long time without touching an MCP tool.
|
||||
*/
|
||||
readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
|
||||
readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
readonly revokeAll: Effect.Effect<void>;
|
||||
@@ -39,7 +44,7 @@ export class McpSessionRegistry extends Context.Service<
|
||||
interface CredentialRecord {
|
||||
readonly tokenHash: string;
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly lastUsedAt: number;
|
||||
readonly lastAliveAt: number;
|
||||
}
|
||||
|
||||
interface RegistryState {
|
||||
@@ -47,13 +52,25 @@ interface RegistryState {
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryOptions {
|
||||
readonly idleTimeoutMs?: number;
|
||||
readonly maximumLifetimeMs?: number;
|
||||
readonly livenessWindowMs?: number;
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
|
||||
const DEFAULT_MAXIMUM_LIFETIME_MS = 8 * 60 * 60 * 1_000;
|
||||
/**
|
||||
* How long a credential outlives the last sign of life from its provider
|
||||
* session.
|
||||
*
|
||||
* Liveness is refreshed both by MCP traffic and by `touch` on every provider
|
||||
* turn, so a session that is still doing work never expires no matter how long
|
||||
* it goes between browser tool calls. This window therefore only bounds
|
||||
* credentials whose session died without a clean stop — the normal paths
|
||||
* (`stopSession`, `stopAll`) revoke eagerly and do not wait for it.
|
||||
*
|
||||
* The bound matters because `/mcp` is mounted outside the environment auth
|
||||
* stack and is reachable on whatever host the server binds to, so this token is
|
||||
* the only thing guarding the preview toolkit on a remote-reachable server.
|
||||
*/
|
||||
const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
|
||||
|
||||
const bytesToHex = (bytes: Uint8Array): string =>
|
||||
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
@@ -80,8 +97,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
const httpServer = yield* HttpServer.HttpServer;
|
||||
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
|
||||
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
|
||||
const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
||||
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
|
||||
const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
|
||||
const endpoint =
|
||||
httpServer.address._tag === "TcpAddress"
|
||||
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
|
||||
@@ -92,11 +108,10 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
.digest("SHA-256", new TextEncoder().encode(token))
|
||||
.pipe(Effect.map(bytesToHex), Effect.orDie);
|
||||
|
||||
const pruneExpired = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
|
||||
const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
|
||||
const next = new Map(
|
||||
Array.from(records).filter(
|
||||
([, record]) =>
|
||||
timestamp <= record.scope.expiresAt && timestamp - record.lastUsedAt <= idleTimeoutMs,
|
||||
([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs,
|
||||
),
|
||||
);
|
||||
return next.size === records.size ? records : next;
|
||||
@@ -108,7 +123,6 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
|
||||
const tokenHash = yield* hashToken(rawToken);
|
||||
const expiresAt = issuedAt + maximumLifetimeMs;
|
||||
const scope: McpInvocationContext.McpInvocationScope = {
|
||||
environmentId,
|
||||
threadId: ThreadId.make(request.threadId),
|
||||
@@ -116,11 +130,10 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
|
||||
capabilities: new Set(["preview"]),
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
};
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
const next = new Map(pruneExpired(records, issuedAt));
|
||||
next.set(tokenHash, { tokenHash, scope, lastUsedAt: issuedAt });
|
||||
const next = new Map(pruneDead(records, issuedAt));
|
||||
next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
|
||||
return { records: next };
|
||||
});
|
||||
return {
|
||||
@@ -132,7 +145,6 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
endpoint,
|
||||
authorizationHeader: `Bearer ${rawToken}`,
|
||||
},
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
);
|
||||
@@ -143,16 +155,32 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
const tokenHash = yield* hashToken(rawToken);
|
||||
const timestamp = yield* currentTimeMillis;
|
||||
return yield* SynchronizedRef.modify(state, ({ records }) => {
|
||||
const current = pruneExpired(records, timestamp);
|
||||
const current = pruneDead(records, timestamp);
|
||||
const record = current.get(tokenHash);
|
||||
if (!record) return [undefined, { records: current }] as const;
|
||||
const next = new Map(current);
|
||||
next.set(tokenHash, { ...record, lastUsedAt: timestamp });
|
||||
next.set(tokenHash, { ...record, lastAliveAt: timestamp });
|
||||
return [record.scope, { records: next }] as const;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
|
||||
function* (threadId) {
|
||||
const timestamp = yield* currentTimeMillis;
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
const current = pruneDead(records, timestamp);
|
||||
const next = new Map(current);
|
||||
for (const [tokenHash, record] of current) {
|
||||
if (record.scope.threadId === threadId) {
|
||||
next.set(tokenHash, { ...record, lastAliveAt: timestamp });
|
||||
}
|
||||
}
|
||||
return { records: next };
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
|
||||
SynchronizedRef.update(state, ({ records }) => ({
|
||||
records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
|
||||
@@ -161,6 +189,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
return McpSessionRegistry.of({
|
||||
issue,
|
||||
resolve,
|
||||
touch,
|
||||
revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
|
||||
function* (providerSessionId) {
|
||||
yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
|
||||
@@ -202,6 +231,13 @@ export const issueActiveMcpCredential = (
|
||||
.pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
|
||||
: Effect.sync((): McpIssuedCredential | undefined => undefined);
|
||||
|
||||
/**
|
||||
* Refreshes the liveness of a thread's MCP credential. Called on every provider
|
||||
* turn so an active session is never mistaken for an abandoned one.
|
||||
*/
|
||||
export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
|
||||
|
||||
export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type PreviewAutomationStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -75,11 +74,18 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* A lease pinning one provider session to one desktop runtime. It lives exactly
|
||||
* as long as the connection it names: `connectionId`/`queue` identity is what
|
||||
* makes a lease valid, so a disconnected or replaced host is dropped on the next
|
||||
* lookup. The lease deliberately has no clock of its own — it used to inherit
|
||||
* the MCP credential's expiry, which coupled host stickiness to an unrelated
|
||||
* auth deadline and could migrate a live session to another runtime mid-flow.
|
||||
*/
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly tabSequence?: number;
|
||||
}
|
||||
@@ -422,13 +428,11 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const route = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const assignments = new Map(
|
||||
Array.from(current.assignments).filter(([, assignment]) => {
|
||||
const connection = current.clients.get(assignment.clientId);
|
||||
return (
|
||||
assignment.expiresAt > now &&
|
||||
connection?.connectionId === assignment.connectionId &&
|
||||
connection.queue === assignment.queue
|
||||
);
|
||||
@@ -473,7 +477,6 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
queue: connection.queue,
|
||||
expiresAt: input.scope.expiresAt,
|
||||
...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),
|
||||
...(canReuseAssignedTab && assigned.tabSequence !== undefined
|
||||
? { tabSequence: assigned.tabSequence }
|
||||
|
||||
@@ -38,7 +38,10 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
resolveSourceControlWriterModelSelection,
|
||||
ServerSettingsService,
|
||||
} from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
||||
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
|
||||
@@ -688,8 +691,14 @@ const make = Effect.gen(function* () {
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
const settings = yield* serverSettingsService.getSettings;
|
||||
const modelSelection =
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? settings.textGenerationModelSelection
|
||||
: resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
yield* providerRegistry.getProviders,
|
||||
);
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd,
|
||||
|
||||
@@ -679,6 +679,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
"provider.kind": routed.adapter.provider,
|
||||
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
|
||||
});
|
||||
// A turn is the clearest sign a session is still alive. The MCP
|
||||
// credential is minted once at session start and cannot be rotated into
|
||||
// an already-spawned agent process, so we keep the existing token valid
|
||||
// rather than issuing a new one: sessions that go a long time between
|
||||
// browser tool calls used to lose the toolkit outright.
|
||||
yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
|
||||
@@ -73,6 +73,7 @@ const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
import { resolveAvailableEditorsForConfig } from "./ws.ts";
|
||||
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
|
||||
import * as GitManager from "./git/GitManager.ts";
|
||||
import * as Keybindings from "./keybindings.ts";
|
||||
@@ -3763,6 +3764,23 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("does not block server config when editor discovery never resolves", () =>
|
||||
Effect.gen(function* () {
|
||||
const discoveryInterrupted = yield* Deferred.make<void>();
|
||||
const responseFiber = yield* resolveAvailableEditorsForConfig(
|
||||
Effect.never.pipe(
|
||||
Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(5));
|
||||
|
||||
const availableEditors = yield* Fiber.join(responseFiber);
|
||||
yield* Deferred.await(discoveryInterrupted);
|
||||
assert.deepEqual(availableEditors, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"rejects websocket rpc handshake when a session token is only provided via query string",
|
||||
() =>
|
||||
|
||||
@@ -325,6 +325,73 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"preserves the source control writer selection when its provider instance is disabled",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const instanceId = ProviderInstanceId.make("codex_writer");
|
||||
const sourceControlWriterModelSelection = {
|
||||
instanceId,
|
||||
model: "gpt-5.4-mini",
|
||||
};
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
});
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(next),
|
||||
next.textGenerationModelSelection,
|
||||
);
|
||||
assert.deepEqual(
|
||||
(yield* serverSettings.getSettings).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.parse(raw).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const restored = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(restored),
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("drops stale text generation options when resetting model selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
|
||||
@@ -11,11 +11,10 @@
|
||||
* @module ServerSettings
|
||||
*/
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
isProviderDriverKind,
|
||||
type ModelSelection,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceEnvironmentVariable,
|
||||
@@ -47,9 +46,14 @@ import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
isModelSelectionProviderEnabled,
|
||||
} from "@t3tools/shared/serverSettings";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
|
||||
export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
|
||||
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
|
||||
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
|
||||
@@ -148,12 +152,13 @@ const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
Effect.map(resolveTextGenerationProvider),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsService["Service"];
|
||||
@@ -165,35 +170,10 @@ export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
const getLegacyProviderSettings = (
|
||||
settings: ServerSettings,
|
||||
provider: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined =>
|
||||
(settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
|
||||
|
||||
/**
|
||||
* Ensure the `textGenerationModelSelection` points to an enabled provider.
|
||||
* If the selected provider is disabled, fall back to the first enabled
|
||||
* provider with its default model. This is applied at read-time so the
|
||||
* persisted preference is preserved for when a provider is re-enabled.
|
||||
*/
|
||||
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
const selection = settings.textGenerationModelSelection;
|
||||
const instanceConfig = settings.providerInstances[selection.instanceId];
|
||||
if (instanceConfig !== undefined) {
|
||||
return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
if (
|
||||
isProviderDriverKind(selection.instanceId) &&
|
||||
getLegacyProviderSettings(settings, selection.instanceId)?.enabled
|
||||
) {
|
||||
return settings;
|
||||
}
|
||||
|
||||
return fallbackTextGenerationProvider(settings);
|
||||
return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
|
||||
? settings
|
||||
: fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
@@ -208,9 +188,9 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
textGenerationModelSelection: {
|
||||
instanceId: ProviderInstanceId.make(fallback),
|
||||
model:
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
} satisfies ModelSelection,
|
||||
};
|
||||
}
|
||||
@@ -218,6 +198,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"automaticGitFetchInterval",
|
||||
"sourceControlWriterModelSelection",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, 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 Path from "effect/Path";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { detectPrTemplate } from "./PrTemplateDetection.ts";
|
||||
|
||||
const SINGLE_TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const PrTemplateDetectionTestLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-pr-template-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* git.execute({
|
||||
operation: "PrTemplateDetection.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
});
|
||||
});
|
||||
|
||||
const runWithTempDirectory = <A, E, R>(
|
||||
test: (cwd: string) => Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
|
||||
) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-pr-template-" });
|
||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
return yield* test(cwd);
|
||||
}),
|
||||
).pipe(Effect.provide(PrTemplateDetectionTestLayer));
|
||||
|
||||
const writeTemplate = (cwd: string, relativePath: string, contents: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templatePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(templatePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(templatePath, contents);
|
||||
return templatePath;
|
||||
});
|
||||
|
||||
const commitTemplates = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["add", "-A"]);
|
||||
yield* runGit(cwd, ["commit", "--allow-empty", "-m", "Add pull request templates"]);
|
||||
});
|
||||
|
||||
const detectTemplate = (cwd: string, treeish = "HEAD") =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* detectPrTemplate(cwd, treeish, git.execute);
|
||||
});
|
||||
|
||||
it.effect.each(SINGLE_TEMPLATE_PATHS)("recognizes $0", (relativePath) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, relativePath, `template from ${relativePath}`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), `template from ${relativePath}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads templates from the requested base tree", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, "README.md", "initial\n");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["branch", "feature"]);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", "base template");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["checkout", "feature"]);
|
||||
|
||||
assert.isTrue(Option.isNone(yield* detectTemplate(cwd)));
|
||||
assert.strictEqual(
|
||||
Option.getOrUndefined(yield* detectTemplate(cwd, "main")),
|
||||
"base template",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses the first non-empty template in the configured path order", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", " \n");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE.md", " ## Preferred template \n");
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "## Later template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "## Preferred template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.each(TEMPLATE_DIRECTORIES)("recognizes the $0 directory", (relativeDirectory) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, `${relativeDirectory}/template.MD`, "directory template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "directory template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("skips unusable directory entries and uses the one valid template", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templateDirectory = path.join(cwd, ".github", "PULL_REQUEST_TEMPLATE");
|
||||
yield* fileSystem.makeDirectory(path.join(templateDirectory, "b-directory.md"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "a-empty.md"), " \n");
|
||||
yield* fileSystem.symlink(
|
||||
path.join(templateDirectory, "missing.md"),
|
||||
path.join(templateDirectory, "c-broken.md"),
|
||||
);
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "z-valid.md"), "valid");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "valid");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not guess between multiple directory templates", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/a.md", "first");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/b.md", "second");
|
||||
yield* writeTemplate(cwd, "PULL_REQUEST_TEMPLATE/fallback.md", "fallback");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.isTrue(Option.isNone(template));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects a committed template symlink escaping the repository", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const outsideTemplate = path.join(outsideDirectory, "secret.md");
|
||||
yield* fileSystem.writeFileString(outsideTemplate, "LOCAL_SECRET_SENTINEL");
|
||||
const escapedTemplatePath = path.join(cwd, ".github", "pull_request_template.md");
|
||||
yield* fileSystem.makeDirectory(path.dirname(escapedTemplatePath), { recursive: true });
|
||||
yield* fileSystem.symlink(outsideTemplate, escapedTemplatePath);
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "safe template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "safe template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads the committed template when a worktree parent is replaced", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const templatePath = yield* writeTemplate(
|
||||
cwd,
|
||||
".github/pull_request_template.md",
|
||||
"committed template",
|
||||
);
|
||||
yield* commitTemplates(cwd);
|
||||
yield* writeTemplate(outsideDirectory, "pull_request_template.md", "LOCAL_SECRET_SENTINEL");
|
||||
|
||||
const templateDirectory = path.dirname(templatePath);
|
||||
yield* fileSystem.rename(templateDirectory, path.join(cwd, ".github-original"));
|
||||
yield* fileSystem.symlink(outsideDirectory, templateDirectory);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "committed template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds template reads and marks truncated content", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = "a".repeat(8_000);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", `${prefix}SECRET_SENTINEL`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = Option.getOrThrow(yield* detectTemplate(cwd));
|
||||
assert.strictEqual(template, `${prefix}\n\n[truncated]`);
|
||||
assert.lengthOf(template.match(/\[truncated\]/g) ?? [], 1);
|
||||
assert.notInclude(template, "SECRET_SENTINEL");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
|
||||
const TEMPLATE_MAX_BYTES = 8_000;
|
||||
const TREE_LIST_MAX_BYTES = 100_000;
|
||||
const TRUNCATION_MARKER = "[truncated]";
|
||||
|
||||
const TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
|
||||
|
||||
type ExecuteGit = GitVcsDriver.GitVcsDriver["Service"]["execute"];
|
||||
|
||||
interface TemplateTreeEntry {
|
||||
readonly objectId: string;
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
|
||||
const entries: TemplateTreeEntry[] = [];
|
||||
for (const record of output.split("\0")) {
|
||||
if (record.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = record.indexOf("\t");
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [mode, type, objectId] = record.slice(0, separator).split(" ");
|
||||
if (
|
||||
type !== "blob" ||
|
||||
(mode !== "100644" && mode !== "100755") ||
|
||||
!objectId ||
|
||||
!/^[0-9a-f]{40,64}$/.test(objectId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
entries.push({ objectId, path: record.slice(separator + 1) });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function readTemplateBlob(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entry: TemplateTreeEntry;
|
||||
}): Effect.Effect<Option.Option<string>, GitCommandError> {
|
||||
return input
|
||||
.executeGit({
|
||||
operation: "PrTemplateDetection.readTemplateBlob",
|
||||
cwd: input.cwd,
|
||||
args: ["cat-file", "blob", input.entry.objectId],
|
||||
maxOutputBytes: TEMPLATE_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
const template = result.stdout.trim();
|
||||
if (template.length === 0) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some(
|
||||
result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
|
||||
? `${template}\n\n${TRUNCATION_MARKER}`
|
||||
: template,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type DirectoryTemplateResult =
|
||||
| { readonly _tag: "None" }
|
||||
| { readonly _tag: "Ambiguous" }
|
||||
| { readonly _tag: "Template"; readonly template: string };
|
||||
|
||||
function readTemplateDirectory(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entries: ReadonlyArray<TemplateTreeEntry>;
|
||||
readonly directory: string;
|
||||
}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
|
||||
return Effect.gen(function* () {
|
||||
const prefix = `${input.directory}/`;
|
||||
const candidates = input.entries.filter((entry) => {
|
||||
if (!entry.path.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
const relativePath = entry.path.slice(prefix.length);
|
||||
return !relativePath.includes("/") && relativePath.toLowerCase().endsWith(".md");
|
||||
});
|
||||
|
||||
const templates: string[] = [];
|
||||
for (const entry of candidates) {
|
||||
const template = yield* readTemplateBlob({ ...input, entry });
|
||||
if (Option.isSome(template)) {
|
||||
templates.push(template.value);
|
||||
if (templates.length > 1) {
|
||||
return { _tag: "Ambiguous" } as const;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return templates[0]
|
||||
? ({ _tag: "Template", template: templates[0] } as const)
|
||||
: ({ _tag: "None" } as const);
|
||||
});
|
||||
}
|
||||
|
||||
export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
|
||||
cwd: string,
|
||||
treeish: string,
|
||||
executeGit: ExecuteGit,
|
||||
) {
|
||||
return yield* Effect.gen(function* () {
|
||||
// Worktree paths can be replaced between validation and open. Read regular blobs from the
|
||||
// committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
|
||||
const result = yield* executeGit({
|
||||
operation: "PrTemplateDetection.listTemplates",
|
||||
cwd,
|
||||
args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
|
||||
maxOutputBytes: TREE_LIST_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
});
|
||||
if (result.stdoutTruncated) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const entries = parseTemplateTreeEntries(result.stdout);
|
||||
const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
|
||||
for (const templatePath of TEMPLATE_PATHS) {
|
||||
const entry = entriesByPath.get(templatePath);
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
const template = yield* readTemplateBlob({ cwd, executeGit, entry });
|
||||
if (Option.isSome(template)) {
|
||||
return template;
|
||||
}
|
||||
}
|
||||
|
||||
for (const directory of TEMPLATE_DIRECTORIES) {
|
||||
const directoryTemplate = yield* readTemplateDirectory({
|
||||
cwd,
|
||||
executeGit,
|
||||
entries,
|
||||
directory,
|
||||
});
|
||||
if (directoryTemplate._tag === "Template") {
|
||||
return Option.some(directoryTemplate.template);
|
||||
}
|
||||
if (directoryTemplate._tag === "Ambiguous") {
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
}).pipe(Effect.orElseSucceed(() => Option.none()));
|
||||
});
|
||||
@@ -272,6 +272,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
@@ -299,6 +300,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
|
||||
@@ -305,6 +305,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
@@ -332,6 +333,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
|
||||
@@ -172,6 +172,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
@@ -199,6 +200,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
|
||||
@@ -164,6 +164,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
@@ -191,6 +192,8 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
|
||||
@@ -530,6 +530,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateCommitMessage",
|
||||
@@ -556,6 +557,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generatePrContent",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
|
||||
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
|
||||
|
||||
@@ -16,6 +17,7 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -34,6 +36,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -77,7 +81,7 @@ export interface TextGenerationService {
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
* TextGeneration - Service tag for commit and change request text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<
|
||||
TextGeneration,
|
||||
@@ -90,7 +94,7 @@ export class TextGeneration extends Context.Service<
|
||||
) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate pull request title/body from branch and diff context.
|
||||
* Generate change request title/body from branch and diff context.
|
||||
*/
|
||||
readonly generatePrContent: (
|
||||
input: PrContentGenerationInput,
|
||||
|
||||
@@ -49,6 +49,23 @@ describe("buildCommitMessagePrompt", () => {
|
||||
|
||||
expect(result.prompt).toContain("Branch: (detached)");
|
||||
});
|
||||
|
||||
it("includes policy instructions", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: "main",
|
||||
stagedSummary: "M a.ts",
|
||||
stagedPatch: "diff",
|
||||
includeBranch: false,
|
||||
policy: {
|
||||
kind: "custom",
|
||||
commitInstructions: "Use a terse repository-specific subject.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Additional instructions:");
|
||||
expect(result.prompt).toContain("Use a terse repository-specific subject.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrContentPrompt", () => {
|
||||
@@ -69,6 +86,30 @@ describe("buildPrContentPrompt", () => {
|
||||
expect(result.prompt).toContain("3 files changed");
|
||||
expect(result.prompt).toContain("Diff patch:");
|
||||
expect(result.prompt).toContain("export function login()");
|
||||
expect(result.prompt).toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
|
||||
it("follows a repository PR template instead of the default body headings", () => {
|
||||
const result = buildPrContentPrompt({
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/auth",
|
||||
commitSummary: "feat: add login page",
|
||||
diffSummary: "3 files changed",
|
||||
diffPatch: "diff",
|
||||
changeRequestTemplate: "<!-- remove me -->\n## What changed\n\n## Verification",
|
||||
policy: {
|
||||
kind: "custom",
|
||||
changeRequestInstructions: "Keep the title in sentence case.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Keep the title in sentence case.");
|
||||
expect(result.prompt).toContain("follow the repository change request template structure");
|
||||
expect(result.prompt).toContain("drop HTML comments from the template");
|
||||
expect(result.prompt).toContain("Repository change request template:");
|
||||
expect(result.prompt).toContain("<!-- remove me -->\n## What changed\n\n## Verification");
|
||||
expect(result.prompt).not.toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ export interface CommitMessagePromptInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch: boolean;
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
const wantsBranch = input.includeBranch;
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
@@ -76,7 +76,7 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR content
|
||||
// Change request content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PrContentPromptInput {
|
||||
@@ -85,19 +85,34 @@ export interface PrContentPromptInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
const changeRequestTemplate = input.changeRequestTemplate?.trim();
|
||||
const bodyRules = changeRequestTemplate
|
||||
? [
|
||||
"- body must be markdown and follow the repository change request template structure",
|
||||
"- fill in the template sections appropriately for this change",
|
||||
"- drop HTML comments from the template in the generated body",
|
||||
"- keep the template's markdown structure",
|
||||
]
|
||||
: [
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
];
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"You write source control change request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
...bodyRules,
|
||||
...policyInstruction(input.policy?.changeRequestInstructions),
|
||||
...(changeRequestTemplate
|
||||
? ["", "Repository change request template:", limitSection(changeRequestTemplate, 8_000)]
|
||||
: []),
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
|
||||
+12
-1
@@ -123,6 +123,15 @@ import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
|
||||
|
||||
export const resolveAvailableEditorsForConfig = <A, E, R>(
|
||||
discovery: Effect.Effect<ReadonlyArray<A>, E, R>,
|
||||
) =>
|
||||
discovery.pipe(
|
||||
Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),
|
||||
Effect.map(Option.getOrElse(() => [])),
|
||||
);
|
||||
|
||||
function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
@@ -1087,7 +1096,9 @@ const makeWsRpcLayer = (
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors: yield* externalLauncher.resolveAvailableEditors(),
|
||||
availableEditors: yield* resolveAvailableEditorsForConfig(
|
||||
externalLauncher.resolveAvailableEditors(),
|
||||
),
|
||||
observability: {
|
||||
logsDirectoryPath: config.logsDir,
|
||||
localTracingEnabled: true,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useActivePreviewSessions } from "~/previewStateStore";
|
||||
import { readPreviewAnnotationTheme } from "./annotationTheme";
|
||||
import { useBrowserPointerStore } from "./browserPointerStore";
|
||||
import { HostedBrowserWebview } from "./HostedBrowserWebview";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
export function ElectronBrowserHost() {
|
||||
const { resolvedTheme } = useTheme();
|
||||
@@ -23,6 +24,11 @@ export function ElectronBrowserHost() {
|
||||
? Object.values(previewState.sessions).map((snapshot) => ({
|
||||
threadRef,
|
||||
snapshot,
|
||||
runtimeTabId: previewRuntimeTabId(
|
||||
threadRef,
|
||||
previewState.serverEpoch,
|
||||
snapshot.tabId,
|
||||
),
|
||||
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
|
||||
}))
|
||||
: [];
|
||||
@@ -74,13 +80,14 @@ export function ElectronBrowserHost() {
|
||||
if (!isElectron) return null;
|
||||
return (
|
||||
<div className="contents" data-electron-browser-host>
|
||||
{sessions.map(({ threadRef, snapshot, zoomFactor }) => {
|
||||
{sessions.map(({ threadRef, snapshot, runtimeTabId, zoomFactor }) => {
|
||||
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return (
|
||||
<HostedBrowserWebview
|
||||
key={snapshot.tabId}
|
||||
key={runtimeTabId}
|
||||
threadRef={threadRef}
|
||||
tabId={snapshot.tabId}
|
||||
runtimeTabId={runtimeTabId}
|
||||
initialUrl={url}
|
||||
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
|
||||
zoomFactor={zoomFactor}
|
||||
|
||||
@@ -9,7 +9,11 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { browserViewportSettingKey, resolveBrowserViewportLayout } from "./browserViewportLayout";
|
||||
import {
|
||||
browserViewportSettingKey,
|
||||
resolveBrowserViewportLayout,
|
||||
resolveFittedBrowserViewport,
|
||||
} from "./browserViewportLayout";
|
||||
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
|
||||
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
@@ -40,11 +44,12 @@ declare global {
|
||||
export function HostedBrowserWebview(props: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly tabId: string;
|
||||
readonly runtimeTabId: string;
|
||||
readonly initialUrl: string | null;
|
||||
readonly viewport: PreviewViewportSetting;
|
||||
readonly zoomFactor: number;
|
||||
}) {
|
||||
const { threadRef, tabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const { threadRef, tabId, runtimeTabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
@@ -54,27 +59,28 @@ export function HostedBrowserWebview(props: {
|
||||
const [aspectRatioLocked, setAspectRatioLocked] = useState(false);
|
||||
const presentation = useBrowserSurfaceStore(
|
||||
useShallow((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
const current = state.byTabId[runtimeTabId];
|
||||
return {
|
||||
content: current?.content ?? null,
|
||||
cornerRadius: current?.cornerRadius ?? 0,
|
||||
fitSourceContent: current?.fitSourceContent ?? false,
|
||||
fittedSourceContent: current?.fittedSourceContent ?? null,
|
||||
rect: resolveBrowserSurfacePanelRect(state.byTabId, tabId),
|
||||
rect: resolveBrowserSurfacePanelRect(state.byTabId, runtimeTabId),
|
||||
visible: current?.visible ?? false,
|
||||
};
|
||||
}),
|
||||
);
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
usePreviewBridge({ threadRef, tabId, runtimeTabId });
|
||||
|
||||
useEffect(() => {
|
||||
crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
|
||||
const lease = acquireDesktopTab(tabId);
|
||||
const lease = acquireDesktopTab(runtimeTabId);
|
||||
tabLeaseRef.current = lease;
|
||||
return () => {
|
||||
if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
|
||||
lease.release();
|
||||
};
|
||||
}, [tabId]);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const [webviewGeneration, setWebviewGeneration] = useState(0);
|
||||
const [recoverySrc, setRecoverySrc] = useState(initialSrc);
|
||||
@@ -107,7 +113,7 @@ export function HostedBrowserWebview(props: {
|
||||
if (disposed || webviewRef.current !== webview) return;
|
||||
const webContentsId = webview.getWebContentsId();
|
||||
if (Number.isInteger(webContentsId) && webContentsId > 0) {
|
||||
await bridge.registerWebview(tabId, webContentsId);
|
||||
await bridge.registerWebview(runtimeTabId, webContentsId);
|
||||
}
|
||||
} catch {
|
||||
// did-attach/dom-ready will retry if the guest was not ready yet.
|
||||
@@ -138,7 +144,7 @@ export function HostedBrowserWebview(props: {
|
||||
webview.removeEventListener("dom-ready", register);
|
||||
webview.removeEventListener("render-process-gone", recoverGuest);
|
||||
};
|
||||
}, [config, initialSrc, tabId, webviewGeneration]);
|
||||
}, [config, initialSrc, runtimeTabId, webviewGeneration]);
|
||||
|
||||
const active = presentation.visible && presentation.rect !== null;
|
||||
const lastRect = presentation.rect;
|
||||
@@ -152,13 +158,22 @@ export function HostedBrowserWebview(props: {
|
||||
const handleAspectRatioChange = useCallback((aspectRatio: number | null) => {
|
||||
setAspectRatioLocked(aspectRatio !== null);
|
||||
}, []);
|
||||
const hiddenContentSize = presentation.content
|
||||
? {
|
||||
width: presentation.content.width / presentation.content.scale,
|
||||
height: presentation.content.height / presentation.content.scale,
|
||||
}
|
||||
: null;
|
||||
const hiddenSize =
|
||||
viewport._tag !== "fill"
|
||||
? {
|
||||
width: viewport.width * normalizedZoomFactor,
|
||||
height: viewport.height * normalizedZoomFactor,
|
||||
}
|
||||
: { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };
|
||||
: {
|
||||
width: hiddenContentSize?.width ?? lastRect?.width ?? 1280,
|
||||
height: hiddenContentSize?.height ?? lastRect?.height ?? 800,
|
||||
};
|
||||
const containerSize = active && lastRect ? lastRect : hiddenSize;
|
||||
const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
|
||||
const {
|
||||
@@ -169,7 +184,7 @@ export function HostedBrowserWebview(props: {
|
||||
handleResizePointerDown,
|
||||
layout: viewportLayout,
|
||||
} = useBrowserViewportResize({
|
||||
tabId,
|
||||
tabId: runtimeTabId,
|
||||
viewport,
|
||||
zoomFactor,
|
||||
containerSize,
|
||||
@@ -178,31 +193,11 @@ export function HostedBrowserWebview(props: {
|
||||
});
|
||||
const fittedSourceViewport =
|
||||
presentation.fitSourceContent && lastRect
|
||||
? presentation.fittedSourceContent
|
||||
? {
|
||||
_tag: "freeform" as const,
|
||||
width: Math.max(
|
||||
1,
|
||||
Math.round(
|
||||
presentation.fittedSourceContent.width /
|
||||
presentation.fittedSourceContent.scale /
|
||||
normalizedZoomFactor,
|
||||
),
|
||||
),
|
||||
height: Math.max(
|
||||
1,
|
||||
Math.round(
|
||||
presentation.fittedSourceContent.height /
|
||||
presentation.fittedSourceContent.scale /
|
||||
normalizedZoomFactor,
|
||||
),
|
||||
),
|
||||
}
|
||||
: {
|
||||
_tag: "freeform" as const,
|
||||
width: viewport._tag === "fill" ? 1280 : viewport.width,
|
||||
height: viewport._tag === "fill" ? 800 : viewport.height,
|
||||
}
|
||||
? resolveFittedBrowserViewport(
|
||||
viewport,
|
||||
presentation.fittedSourceContent,
|
||||
normalizedZoomFactor,
|
||||
)
|
||||
: null;
|
||||
const layout =
|
||||
fittedSourceViewport && lastRect
|
||||
@@ -212,7 +207,7 @@ export function HostedBrowserWebview(props: {
|
||||
const syncContentPresentation = useCallback(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
useBrowserSurfaceStore.getState().presentContent(tabId, {
|
||||
useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
|
||||
x: layout.viewportX,
|
||||
y: layout.viewportY,
|
||||
width: layout.viewportWidth,
|
||||
@@ -221,7 +216,7 @@ export function HostedBrowserWebview(props: {
|
||||
scrollLeft: wrapper.scrollLeft,
|
||||
scrollTop: wrapper.scrollTop,
|
||||
});
|
||||
}, [layout, tabId]);
|
||||
}, [layout, runtimeTabId]);
|
||||
|
||||
useEffect(() => {
|
||||
const frameId = window.requestAnimationFrame(syncContentPresentation);
|
||||
@@ -232,7 +227,7 @@ export function HostedBrowserWebview(props: {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
wrapper.scrollTo({ left: 0, top: 0 });
|
||||
}, [tabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
}, [runtimeTabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
@@ -249,7 +244,7 @@ export function HostedBrowserWebview(props: {
|
||||
className="fixed overflow-hidden bg-muted/35"
|
||||
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
|
||||
onScroll={syncContentPresentation}
|
||||
data-preview-viewport={tabId}
|
||||
data-preview-viewport={runtimeTabId}
|
||||
>
|
||||
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
|
||||
{deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
|
||||
@@ -268,7 +263,8 @@ export function HostedBrowserWebview(props: {
|
||||
partition={config.partition}
|
||||
webpreferences={config.webPreferences}
|
||||
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
|
||||
data-preview-tab={tabId}
|
||||
data-preview-tab={runtimeTabId}
|
||||
data-preview-server-tab={tabId}
|
||||
data-preview-viewport-mode={effectiveViewport._tag}
|
||||
data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
|
||||
data-preview-css-width={
|
||||
|
||||
@@ -89,10 +89,13 @@ import {
|
||||
BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS,
|
||||
BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
|
||||
BrowserRecordingConflictError,
|
||||
findActiveBrowserRecordingRuntimeTabId,
|
||||
readActiveBrowserRecordingTabIds,
|
||||
readActiveBrowserRecordingTargets,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from "./browserRecording";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static isTypeSupported(): boolean {
|
||||
@@ -363,6 +366,46 @@ describe("browser recording", () => {
|
||||
expect(save).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps a recording reachable through its runtime id after a server epoch changes", async () => {
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("environment-recording"),
|
||||
threadId: ThreadId.make("thread-recording-scoped"),
|
||||
};
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, "epoch-a", "tab_1");
|
||||
surfaceState.byTabId = {
|
||||
[runtimeTabId]: {
|
||||
visible: false,
|
||||
rect: { x: 0, y: 0, width: 1280, height: 800 },
|
||||
content: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1280,
|
||||
height: 800,
|
||||
scale: 1,
|
||||
scrollLeft: 0,
|
||||
scrollTop: 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await startBrowserRecording(runtimeTabId, threadRef, "tab_1");
|
||||
|
||||
expect(startScreencast).toHaveBeenCalledWith(runtimeTabId);
|
||||
expect(readActiveBrowserRecordingTabIds(threadRef)).toEqual(new Set([runtimeTabId]));
|
||||
expect(readActiveBrowserRecordingTargets(threadRef)).toEqual([
|
||||
{ runtimeTabId, serverTabId: "tab_1" },
|
||||
]);
|
||||
expect(findActiveBrowserRecordingRuntimeTabId(threadRef, "tab_1")).toBe(runtimeTabId);
|
||||
|
||||
const replacementRuntimeTabId = previewRuntimeTabId(threadRef, "epoch-b", "tab_1");
|
||||
await expect(
|
||||
startBrowserRecording(replacementRuntimeTabId, threadRef, "tab_1"),
|
||||
).rejects.toBeInstanceOf(BrowserRecordingConflictError);
|
||||
expect(startScreencast).toHaveBeenCalledTimes(1);
|
||||
|
||||
await stopBrowserRecording(runtimeTabId);
|
||||
});
|
||||
|
||||
it("does not report success for a second start while the first is still starting", async () => {
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async (tabId: string) => {
|
||||
|
||||
@@ -82,7 +82,10 @@ type BrowserRecordingLifecycle =
|
||||
};
|
||||
|
||||
interface ActiveRecording {
|
||||
/** Desktop-scoped identity used by capture and surface stores. */
|
||||
readonly tabId: string;
|
||||
/** Server-local identity returned by preview automation tools. */
|
||||
readonly serverTabId: string;
|
||||
readonly threadRef: ScopedThreadRef | null;
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
readonly context: CanvasRenderingContext2D;
|
||||
@@ -99,6 +102,11 @@ interface ActiveRecording {
|
||||
lifecycle: BrowserRecordingLifecycle;
|
||||
}
|
||||
|
||||
export interface ActiveBrowserRecordingTarget {
|
||||
readonly runtimeTabId: string;
|
||||
readonly serverTabId: string;
|
||||
}
|
||||
|
||||
interface ActiveBrowserRecordingIndex {
|
||||
readonly tabIds: ReadonlySet<string>;
|
||||
}
|
||||
@@ -131,6 +139,28 @@ export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): R
|
||||
return tabIds;
|
||||
}
|
||||
|
||||
export function readActiveBrowserRecordingTargets(
|
||||
threadRef: ScopedThreadRef,
|
||||
): ReadonlyArray<ActiveBrowserRecordingTarget> {
|
||||
return Array.from(activeRecordings.values()).flatMap((recording) =>
|
||||
recording.threadRef?.environmentId === threadRef.environmentId &&
|
||||
recording.threadRef.threadId === threadRef.threadId
|
||||
? [{ runtimeTabId: recording.tabId, serverTabId: recording.serverTabId }]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
export function findActiveBrowserRecordingRuntimeTabId(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverTabId: string,
|
||||
): string | null {
|
||||
return (
|
||||
readActiveBrowserRecordingTargets(threadRef).find(
|
||||
(recording) => recording.serverTabId === serverTabId,
|
||||
)?.runtimeTabId ?? null
|
||||
);
|
||||
}
|
||||
|
||||
const preferredMimeType = (): string => {
|
||||
const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];
|
||||
return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";
|
||||
@@ -283,6 +313,7 @@ const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperatio
|
||||
export async function startBrowserRecording(
|
||||
tabId: string,
|
||||
threadRef: ScopedThreadRef | null = null,
|
||||
serverTabId = tabId,
|
||||
): Promise<string> {
|
||||
const bridge = previewBridge;
|
||||
if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
|
||||
@@ -296,6 +327,14 @@ export async function startBrowserRecording(
|
||||
activeTabId: activeRecording.tabId,
|
||||
});
|
||||
}
|
||||
const activeLogicalRecording =
|
||||
threadRef === null ? null : findActiveBrowserRecordingRuntimeTabId(threadRef, serverTabId);
|
||||
if (activeLogicalRecording !== null) {
|
||||
throw new BrowserRecordingConflictError({
|
||||
requestedTabId: tabId,
|
||||
activeTabId: activeLogicalRecording,
|
||||
});
|
||||
}
|
||||
const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
|
||||
const recordingSize = surface?.content ?? surface?.rect;
|
||||
const canvas = document.createElement("canvas");
|
||||
@@ -321,6 +360,7 @@ export async function startBrowserRecording(
|
||||
});
|
||||
const recording: ActiveRecording = {
|
||||
tabId,
|
||||
serverTabId,
|
||||
threadRef,
|
||||
canvas,
|
||||
context,
|
||||
|
||||
@@ -86,7 +86,7 @@ describe("browserSurfaceStore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the live panel rect for a hidden background tab", () => {
|
||||
it("keeps a hidden background tab on its own last rect", () => {
|
||||
const staleRect = { x: 0, y: 0, width: 500, height: 700 };
|
||||
const liveRect = { x: 10, y: 20, width: 900, height: 640 };
|
||||
expect(
|
||||
@@ -115,7 +115,7 @@ describe("browserSurfaceStore", () => {
|
||||
},
|
||||
"hidden",
|
||||
),
|
||||
).toEqual(liveRect);
|
||||
).toEqual(staleRect);
|
||||
});
|
||||
|
||||
it("ignores updates and releases from a stale surface lease", () => {
|
||||
|
||||
@@ -52,19 +52,7 @@ export function resolveBrowserSurfacePanelRect(
|
||||
tabId: string,
|
||||
): BrowserSurfaceRect | null {
|
||||
const current = byTabId[tabId];
|
||||
if (current?.visible && current.rect) return current.rect;
|
||||
|
||||
let latestVisible: BrowserSurfacePresentation | undefined;
|
||||
for (const presentation of Object.values(byTabId)) {
|
||||
if (
|
||||
presentation.visible &&
|
||||
presentation.rect &&
|
||||
(!latestVisible || presentation.updatedAt > latestVisible.updatedAt)
|
||||
) {
|
||||
latestVisible = presentation;
|
||||
}
|
||||
}
|
||||
return latestVisible?.rect ?? current?.rect ?? null;
|
||||
return current?.rect ?? null;
|
||||
}
|
||||
|
||||
const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect): boolean =>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
|
||||
commitBrowserViewportChange,
|
||||
runBrowserViewportMutation,
|
||||
subscribeBrowserViewportChange,
|
||||
} from "./browserViewportActions";
|
||||
|
||||
@@ -71,6 +72,33 @@ describe("browserViewportActions", () => {
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("serializes background mutations with visible viewport commits", async () => {
|
||||
let releaseBackground: (() => void) | undefined;
|
||||
const backgroundPending = new Promise<void>((resolve) => {
|
||||
releaseBackground = resolve;
|
||||
});
|
||||
const calls: string[] = [];
|
||||
const background = runBrowserViewportMutation("tab-shared", async () => {
|
||||
calls.push("background");
|
||||
await backgroundPending;
|
||||
});
|
||||
const unsubscribe = subscribeBrowserViewportChange("tab-shared", async () => {
|
||||
calls.push("visible");
|
||||
});
|
||||
const visible = commitBrowserViewportChange("tab-shared", {
|
||||
_tag: "freeform",
|
||||
width: 900,
|
||||
height: 700,
|
||||
});
|
||||
|
||||
await vi.waitFor(() => expect(calls).toEqual(["background"]));
|
||||
releaseBackground?.();
|
||||
await Promise.all([background, visible]);
|
||||
|
||||
expect(calls).toEqual(["background", "visible"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("does not let a timed-out handler overtake a newer viewport commit", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,41 @@ export class BrowserViewportCommitTimeoutError extends Error {
|
||||
const handlers = new Map<string, BrowserViewportHandler>();
|
||||
const commitTails = new Map<string, Promise<void>>();
|
||||
|
||||
const queueBrowserViewportMutation = <A>(
|
||||
tabId: string,
|
||||
start: () => Promise<A>,
|
||||
): {
|
||||
readonly started: Promise<{ readonly operation: Promise<A> }>;
|
||||
readonly execution: Promise<A>;
|
||||
} => {
|
||||
const previous = commitTails.get(tabId) ?? Promise.resolve();
|
||||
const started = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => ({
|
||||
operation: Promise.resolve().then(start),
|
||||
}));
|
||||
const execution = started.then(({ operation }) => operation);
|
||||
const tail = execution.then(() => undefined);
|
||||
commitTails.set(tabId, tail);
|
||||
const clear = () => {
|
||||
if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
|
||||
};
|
||||
void tail.then(clear, clear);
|
||||
return { started, execution };
|
||||
};
|
||||
|
||||
/**
|
||||
* Serializes every server-side viewport mutation for one desktop runtime tab.
|
||||
* Both visible UI commits and background automation use this queue so a
|
||||
* compensating rollback cannot overtake a newer resize.
|
||||
*/
|
||||
export function runBrowserViewportMutation<A>(
|
||||
tabId: string,
|
||||
mutation: () => Promise<A>,
|
||||
): Promise<A> {
|
||||
return queueBrowserViewportMutation(tabId, mutation).execution;
|
||||
}
|
||||
|
||||
const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
@@ -42,25 +77,14 @@ export function commitBrowserViewportChange(
|
||||
tabId: string,
|
||||
setting: PreviewViewportSetting,
|
||||
): Promise<void> {
|
||||
const previous = commitTails.get(tabId) ?? Promise.resolve();
|
||||
const started = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
const handler = handlers.get(tabId);
|
||||
const operation = handler
|
||||
? Promise.resolve().then(() => handler(setting))
|
||||
: Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
|
||||
return { operation };
|
||||
});
|
||||
// The queue follows the real handler lifetime, not the caller-facing timeout.
|
||||
// A slow commit therefore cannot time out, release the queue, and overwrite a
|
||||
// newer viewport after that newer request has already completed.
|
||||
const execution = started.then(({ operation }) => operation);
|
||||
const { started } = queueBrowserViewportMutation(tabId, () => {
|
||||
const handler = handlers.get(tabId);
|
||||
return handler
|
||||
? handler(setting)
|
||||
: Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
|
||||
});
|
||||
// The queue follows the real handler lifetime, while the caller-facing
|
||||
// timeout starts only once this commit reaches the front of that queue.
|
||||
const result = started.then(({ operation }) => runHandlerWithTimeout(tabId, operation));
|
||||
commitTails.set(tabId, execution);
|
||||
const clear = () => {
|
||||
if (commitTails.get(tabId) === execution) commitTails.delete(tabId);
|
||||
};
|
||||
void execution.then(clear, clear);
|
||||
return result;
|
||||
}
|
||||
@@ -4,11 +4,27 @@ import {
|
||||
resizeBrowserViewportFromRail,
|
||||
resizeFreeformViewport,
|
||||
resolveBrowserDeviceViewportLayout,
|
||||
resolveFittedBrowserViewport,
|
||||
resolveBrowserViewportLayout,
|
||||
resolveResponsiveBrowserViewportSize,
|
||||
} from "./browserViewportLayout";
|
||||
|
||||
describe("resolveBrowserViewportLayout", () => {
|
||||
it("uses the current fixed viewport instead of stale fitted source dimensions", () => {
|
||||
expect(
|
||||
resolveFittedBrowserViewport(
|
||||
{ _tag: "freeform", width: 900, height: 600 },
|
||||
{ width: 1280, height: 800, scale: 1 },
|
||||
),
|
||||
).toEqual({ _tag: "freeform", width: 900, height: 600 });
|
||||
});
|
||||
|
||||
it("preserves the last logical viewport when fitting a fill-mode surface", () => {
|
||||
expect(
|
||||
resolveFittedBrowserViewport({ _tag: "fill" }, { width: 320, height: 200, scale: 0.25 }),
|
||||
).toEqual({ _tag: "freeform", width: 1280, height: 800 });
|
||||
});
|
||||
|
||||
it("fills the available surface in fill mode", () => {
|
||||
expect(resolveBrowserViewportLayout({ width: 700, height: 500 }, { _tag: "fill" })).toEqual({
|
||||
canvasWidth: 700,
|
||||
|
||||
@@ -40,6 +40,33 @@ export const browserViewportSettingKey = (setting: PreviewViewportSetting): stri
|
||||
const normalizeZoomFactor = (zoomFactor: number): number =>
|
||||
Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
|
||||
|
||||
export function resolveFittedBrowserViewport(
|
||||
setting: PreviewViewportSetting,
|
||||
sourceContent: {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly scale: number;
|
||||
} | null,
|
||||
zoomFactor = 1,
|
||||
): Exclude<PreviewViewportSetting, { readonly _tag: "fill" }> {
|
||||
if (setting._tag !== "fill") return setting;
|
||||
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
|
||||
if (sourceContent) {
|
||||
return {
|
||||
_tag: "freeform",
|
||||
width: Math.max(
|
||||
1,
|
||||
Math.round(sourceContent.width / sourceContent.scale / normalizedZoomFactor),
|
||||
),
|
||||
height: Math.max(
|
||||
1,
|
||||
Math.round(sourceContent.height / sourceContent.scale / normalizedZoomFactor),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { _tag: "freeform", width: 1280, height: 800 };
|
||||
}
|
||||
|
||||
export function resolveBrowserDeviceViewportArea(container: {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const { closeTab, createTab, stopBrowserRecording } = vi.hoisted(() => ({
|
||||
@@ -15,6 +16,7 @@ vi.mock("./browserRecording", () => ({
|
||||
}));
|
||||
|
||||
import { acquireDesktopTab } from "./desktopTabLifetime";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
describe("desktopTabLifetime", () => {
|
||||
beforeEach(() => {
|
||||
@@ -55,6 +57,39 @@ describe("desktopTabLifetime", () => {
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps identical server tab ids from two environments in separate desktop slots", async () => {
|
||||
vi.useFakeTimers();
|
||||
createTab.mockResolvedValue(undefined);
|
||||
const tabA = previewRuntimeTabId(
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
},
|
||||
"epoch-a",
|
||||
"tab_1",
|
||||
);
|
||||
const tabB = previewRuntimeTabId(
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-b"),
|
||||
threadId: ThreadId.make("thread-b"),
|
||||
},
|
||||
"epoch-b",
|
||||
"tab_1",
|
||||
);
|
||||
|
||||
const first = acquireDesktopTab(tabA);
|
||||
const second = acquireDesktopTab(tabB);
|
||||
await Promise.all([first.ready, second.ready]);
|
||||
|
||||
expect(createTab).toHaveBeenCalledWith(tabA);
|
||||
expect(createTab).toHaveBeenCalledWith(tabB);
|
||||
expect(createTab).toHaveBeenCalledTimes(2);
|
||||
|
||||
first.release();
|
||||
second.release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
it("stops recording before closing the final desktop tab lease", async () => {
|
||||
vi.useFakeTimers();
|
||||
let resolveStop: (() => void) | undefined;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isCurrentPreviewRuntimeTab, previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
describe("previewRuntimeTabId", () => {
|
||||
it("scopes process-local tab ids to their environment, thread, and server epoch", () => {
|
||||
const base = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId(
|
||||
{ ...base, environmentId: EnvironmentId.make("environment-b") },
|
||||
"epoch-a",
|
||||
"tab_1",
|
||||
),
|
||||
);
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId({ ...base, threadId: ThreadId.make("thread-b") }, "epoch-a", "tab_1"),
|
||||
);
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId(base, "epoch-b", "tab_1"),
|
||||
);
|
||||
});
|
||||
|
||||
it("is stable for the same runtime tab", () => {
|
||||
const ref = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
expect(previewRuntimeTabId(ref, null, "tab_1")).toBe(previewRuntimeTabId(ref, null, "tab_1"));
|
||||
});
|
||||
|
||||
it("rejects a pinned operation target after the server epoch changes", () => {
|
||||
const ref = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
const runtimeTabId = previewRuntimeTabId(ref, "epoch-a", "tab_1");
|
||||
|
||||
expect(isCurrentPreviewRuntimeTab(ref, "epoch-a", "tab_1", runtimeTabId)).toBe(true);
|
||||
expect(isCurrentPreviewRuntimeTab(ref, "epoch-b", "tab_1", runtimeTabId)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* The server only guarantees preview tab ids are unique within one process.
|
||||
* Desktop resources live across every connected environment, so they need a
|
||||
* stronger identity that also changes when a server process restarts.
|
||||
*/
|
||||
export function previewRuntimeTabId(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverEpoch: string | null,
|
||||
tabId: string,
|
||||
): string {
|
||||
return JSON.stringify([threadRef.environmentId, threadRef.threadId, serverEpoch, tabId]);
|
||||
}
|
||||
|
||||
export function isCurrentPreviewRuntimeTab(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverEpoch: string | null,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
): boolean {
|
||||
return previewRuntimeTabId(threadRef, serverEpoch, tabId) === runtimeTabId;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchTriggerLabel,
|
||||
resolveBranchToolbarPrBranch,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
@@ -174,6 +175,101 @@ describe("resolveBranchToolbarValue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchTriggerLabel", () => {
|
||||
it("shows the origin ref when a new worktree will start from origin", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/main");
|
||||
});
|
||||
|
||||
it("shows the origin ref for local branch names that contain slashes", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "feature/demo",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/feature/demo");
|
||||
});
|
||||
|
||||
it("shows the local ref when start from origin is disabled", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
).toBe("From main");
|
||||
});
|
||||
|
||||
it("does not duplicate the origin prefix for an explicit remote ref", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "origin/feature/demo",
|
||||
resolvedActiveBranchIsRemote: true,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/feature/demo");
|
||||
});
|
||||
|
||||
it("preserves an explicit ref from a non-origin remote", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "upstream/feature/demo",
|
||||
resolvedActiveBranchIsRemote: true,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From upstream/feature/demo");
|
||||
});
|
||||
|
||||
it("keeps current-checkout labels and empty state unchanged", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "local",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("main");
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: null,
|
||||
resolvedActiveBranchIsRemote: null,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("Select ref");
|
||||
});
|
||||
|
||||
it("does not fabricate an origin ref while branch metadata is loading", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "upstream/feature/demo",
|
||||
resolvedActiveBranchIsRemote: null,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From upstream/feature/demo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarPrBranch", () => {
|
||||
it("uses the explicit thread branch when it matches the displayed branch", () => {
|
||||
expect(
|
||||
|
||||
@@ -156,6 +156,33 @@ export function resolveBranchToolbarValue(input: {
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
}
|
||||
|
||||
export function resolveBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
resolvedActiveBranch: string | null;
|
||||
resolvedActiveBranchIsRemote: boolean | null;
|
||||
startFromOrigin: boolean;
|
||||
}): string {
|
||||
const {
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
resolvedActiveBranchIsRemote,
|
||||
startFromOrigin,
|
||||
} = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
const baseRef =
|
||||
startFromOrigin && resolvedActiveBranchIsRemote === false
|
||||
? `origin/${resolvedActiveBranch}`
|
||||
: resolvedActiveBranch;
|
||||
return `From ${baseRef}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function resolveBranchToolbarPrBranch(input: {
|
||||
activeThreadBranch: string | null;
|
||||
resolvedActiveBranch: string | null;
|
||||
|
||||
@@ -234,10 +234,10 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
[environmentId, threadId],
|
||||
);
|
||||
const serverThread = useThread(threadRef);
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
|
||||
@@ -35,6 +35,7 @@ import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { getSourceControlPresentation } from "../sourceControlPresentation";
|
||||
import {
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveBranchTriggerLabel,
|
||||
resolveBranchToolbarPrBranch,
|
||||
resolveBranchSelectionTarget,
|
||||
resolveBranchToolbarValue,
|
||||
@@ -81,21 +82,6 @@ function toBranchActionErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "An error occurred.";
|
||||
}
|
||||
|
||||
function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: "local" | "worktree";
|
||||
resolvedActiveBranch: string | null;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function BranchToolbarBranchSelector({
|
||||
className,
|
||||
environmentId,
|
||||
@@ -129,11 +115,11 @@ export function BranchToolbarBranchSelector({
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
[environmentId, threadId],
|
||||
);
|
||||
const serverThread = useThread(threadRef);
|
||||
const serverSession = serverThread?.session ?? null;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
|
||||
const serverSession = serverThread?.session ?? null;
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
|
||||
const activeProjectRef = serverThread
|
||||
@@ -308,6 +294,29 @@ export function BranchToolbarBranchSelector({
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const listedActiveBranch =
|
||||
resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
|
||||
const activeBranchRefQuery = useEnvironmentQuery(
|
||||
branchCwd !== null && resolvedActiveBranch !== null
|
||||
? vcsEnvironment.listRefs({
|
||||
environmentId,
|
||||
input: {
|
||||
cwd: branchCwd,
|
||||
query: resolvedActiveBranch,
|
||||
limit: 10,
|
||||
},
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
|
||||
(refName) => refName.name === resolvedActiveBranch,
|
||||
);
|
||||
const resolvedActiveBranchIsRemote =
|
||||
listedActiveBranch !== null
|
||||
? listedActiveBranch.isRemote === true
|
||||
: queriedActiveBranch
|
||||
? queriedActiveBranch.isRemote === true
|
||||
: null;
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const totalBranchCount = branchRefState.data?.totalCount ?? 0;
|
||||
const branchStatusText = isInitialBranchesLoadPending
|
||||
@@ -584,10 +593,12 @@ export function BranchToolbarBranchSelector({
|
||||
maybeFetchNextBranchPage();
|
||||
}, [refs.length, maybeFetchNextBranchPage]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
const triggerLabel = resolveBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
resolvedActiveBranchIsRemote,
|
||||
startFromOrigin,
|
||||
});
|
||||
|
||||
// PR pill shown next to the branch selector when the active branch has one.
|
||||
|
||||
@@ -620,8 +620,8 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
|
||||
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
|
||||
const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
|
||||
const serverThread = useThread(threadRef);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
|
||||
const projectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -976,8 +976,8 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
|
||||
newShortcutLabel,
|
||||
closeShortcutLabel,
|
||||
}: PersistentThreadTerminalPanelProps) {
|
||||
const serverThread = useThread(threadRef);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
|
||||
const projectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -1181,7 +1181,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const composerDraftTarget: ScopedThreadRef | DraftId =
|
||||
routeKind === "server" ? routeThreadRef : props.draftId;
|
||||
const serverThread = useThread(routeThreadRef);
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
routeKind === "server"
|
||||
? store.getDraftSessionByRef(routeThreadRef)
|
||||
: draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: null,
|
||||
);
|
||||
const serverThread = useThread(routeThreadRef, { waitForShell: draftThread !== null });
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const activeThreadLastVisitedAt = useUiStateStore(
|
||||
(store) => store.threadLastVisitedAtById[routeThreadKey],
|
||||
@@ -1234,13 +1241,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const setLogicalProjectDraftThreadId = useComposerDraftStore(
|
||||
(store) => store.setLogicalProjectDraftThreadId,
|
||||
);
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
routeKind === "server"
|
||||
? store.getDraftSessionByRef(routeThreadRef)
|
||||
: draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: null,
|
||||
);
|
||||
const promptRef = useRef("");
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
|
||||
@@ -30,6 +30,7 @@ import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
buildFileDiffRenderKey,
|
||||
getDiffCollapseIconClassName,
|
||||
getDiffLineStat,
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
@@ -41,6 +42,7 @@ import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { DiffStatLabel } from "./chat/DiffStatLabel";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -452,6 +454,7 @@ export default function DiffPanel({
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -713,6 +716,14 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<DiffStatLabel
|
||||
additions={diffLineStat.additions}
|
||||
deletions={diffLineStat.deletions}
|
||||
className="mr-1 text-[11px]"
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
|
||||
@@ -986,7 +986,6 @@ export default function GitActionsControl({
|
||||
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
|
||||
[activeThreadRef],
|
||||
);
|
||||
const activeServerThread = useThread(activeThreadRef);
|
||||
const activeDraftThread = useComposerDraftStore((store) =>
|
||||
draftId
|
||||
? store.getDraftSession(draftId)
|
||||
@@ -994,6 +993,9 @@ export default function GitActionsControl({
|
||||
? store.getDraftThreadByRef(activeThreadRef)
|
||||
: null,
|
||||
);
|
||||
const activeServerThread = useThread(activeThreadRef, {
|
||||
waitForShell: activeDraftThread !== null,
|
||||
});
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
|
||||
@@ -138,6 +138,10 @@ export default function ProjectScriptsControl({
|
||||
}: ProjectScriptsControlProps) {
|
||||
const addScriptFormId = React.useId();
|
||||
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
|
||||
const [actionsMenuOpen, setActionsMenuOpen] = useState({
|
||||
scripts: false,
|
||||
imports: false,
|
||||
});
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [command, setCommand] = useState("");
|
||||
@@ -255,6 +259,7 @@ export default function ProjectScriptsControl({
|
||||
};
|
||||
|
||||
const openEditDialog = (script: ProjectScript) => {
|
||||
setActionsMenuOpen({ scripts: false, imports: false });
|
||||
setEditingScriptId(script.id);
|
||||
setName(script.name);
|
||||
setCommand(script.command);
|
||||
@@ -349,7 +354,11 @@ export default function ProjectScriptsControl({
|
||||
<TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<Menu
|
||||
highlightItemOnHover={false}
|
||||
open={actionsMenuOpen.scripts}
|
||||
onOpenChange={(open) => setActionsMenuOpen({ scripts: open, imports: false })}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
>
|
||||
@@ -408,7 +417,11 @@ export default function ProjectScriptsControl({
|
||||
</Menu>
|
||||
</Group>
|
||||
) : importableScripts.length > 0 ? (
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<Menu
|
||||
highlightItemOnHover={false}
|
||||
open={actionsMenuOpen.imports}
|
||||
onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
|
||||
>
|
||||
<MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
|
||||
@@ -68,6 +68,10 @@ function updateProviderUpdateToast(input: {
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
// Base UI merges toast updates with the existing toast. Explicitly clear
|
||||
// the prompt action so its guarded Update handler cannot linger as a
|
||||
// visible no-op while the update is running (or after it succeeds).
|
||||
actionProps: undefined,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
|
||||
@@ -96,7 +96,11 @@ import { threadEnvironment } from "../state/threads";
|
||||
import { projectEnvironment } from "../state/projects";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
buildThreadRouteParams,
|
||||
resolveActiveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "../threadRoutes";
|
||||
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -239,11 +243,8 @@ function SidebarV2ThreadTooltip({
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
className="dropdown-glass max-w-80 border-0! text-left whitespace-normal shadow-lg/10 before:hidden dark:shadow-none"
|
||||
style={{
|
||||
background:
|
||||
"color-mix(in srgb, var(--popover) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
|
||||
}}
|
||||
variant="glass"
|
||||
className="max-w-80 text-left whitespace-normal"
|
||||
>
|
||||
<div className="flex max-w-80 flex-col gap-2 p-2">
|
||||
<div className="whitespace-nowrap text-sm font-medium text-foreground">{thread.title}</div>
|
||||
@@ -1055,7 +1056,13 @@ export default function SidebarV2() {
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const routeDraftThread = useComposerDraftStore((store) =>
|
||||
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
|
||||
);
|
||||
const routeThreadRef = useMemo(
|
||||
() => resolveActiveThreadRouteRef(routeTarget, routeDraftThread),
|
||||
[routeDraftThread, routeTarget],
|
||||
);
|
||||
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
|
||||
const routeTargetRef = useRef(routeTarget);
|
||||
routeTargetRef.current = routeTarget;
|
||||
|
||||
@@ -39,6 +39,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
open?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
triggerAriaLabel?: string;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
|
||||
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
|
||||
@@ -146,6 +147,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
aria-label={props.triggerAriaLabel}
|
||||
size="sm"
|
||||
variant={props.triggerVariant ?? "ghost"}
|
||||
data-chat-provider-model-picker="true"
|
||||
|
||||
@@ -32,12 +32,14 @@ import {
|
||||
import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
|
||||
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
|
||||
import {
|
||||
readActiveBrowserRecordingTabIds,
|
||||
readActiveBrowserRecordingTargets,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from "~/browser/browserRecording";
|
||||
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
|
||||
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
|
||||
import { runBrowserViewportMutation } from "~/browser/browserViewportActions";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { isElectron } from "~/env";
|
||||
import { useEnvironments } from "~/state/environments";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
@@ -46,7 +48,6 @@ import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
import {
|
||||
PreviewAutomationNavigationTimeoutError,
|
||||
PreviewAutomationOperationError,
|
||||
PreviewAutomationOverlayTimeoutError,
|
||||
PreviewAutomationRecordingNotActiveError,
|
||||
@@ -54,9 +55,14 @@ import {
|
||||
PreviewAutomationViewportTimeoutError,
|
||||
} from "./previewAutomationErrors";
|
||||
import {
|
||||
previewAutomationDefaultViewport,
|
||||
previewAutomationOpenNeedsOverlay,
|
||||
shouldOpenPreviewMiniPlayer,
|
||||
} from "./previewAutomationOpenReadiness";
|
||||
import {
|
||||
assertPreviewRuntimeCurrent,
|
||||
waitForNavigationReadiness,
|
||||
} from "./previewNavigationReadiness";
|
||||
import { createPreviewAutomationRequestConsumerAtom } from "./previewAutomationRequestConsumer";
|
||||
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
|
||||
import {
|
||||
@@ -64,19 +70,39 @@ import {
|
||||
resolvePreviewAutomationOpenTab,
|
||||
resolvePreviewAutomationTarget,
|
||||
} from "./previewAutomationTarget";
|
||||
import { resolveHostWaitBudgetMs } from "./previewAutomationHostBudget";
|
||||
import { isPreviewViewportReady } from "./previewViewportReadiness";
|
||||
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
|
||||
|
||||
const PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS = 500;
|
||||
|
||||
const waitForPreviewPresentation = async (runtimeTabId: string): Promise<void> => {
|
||||
const deadline = Date.now() + PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS;
|
||||
while (Date.now() <= deadline) {
|
||||
if (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible) return;
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 16));
|
||||
}
|
||||
};
|
||||
|
||||
const waitForDesktopOverlay = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
operation: PreviewAutomationRequest["operation"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
// Expire before the broker does, so an unavailable overlay surfaces as
|
||||
// PreviewAutomationOverlayTimeoutError rather than a bare broker timeout.
|
||||
const waitBudgetMs = resolveHostWaitBudgetMs(timeoutMs);
|
||||
const deadline = Date.now() + waitBudgetMs;
|
||||
while (Date.now() <= deadline) {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, {
|
||||
operation,
|
||||
requestId,
|
||||
});
|
||||
if (state.desktopByTabId[tabId] && previewBridge) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
if (status.available) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
@@ -85,39 +111,7 @@ const waitForDesktopOverlay = async (
|
||||
requestId,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
timeoutMs,
|
||||
});
|
||||
};
|
||||
|
||||
const waitForNavigationReadiness = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
readiness: PreviewAutomationNavigateInput["readiness"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> => {
|
||||
const targetReadiness = readiness ?? "load";
|
||||
if (!previewBridge || targetReadiness === "none") return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
if (targetReadiness === "domContentLoaded") {
|
||||
const readyState = await previewBridge.automation.evaluate(tabId, {
|
||||
expression: "document.readyState",
|
||||
});
|
||||
if (readyState === "interactive" || readyState === "complete") return;
|
||||
} else {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
if (!status.loading) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
}
|
||||
throw new PreviewAutomationNavigationTimeoutError({
|
||||
requestId,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
readiness: targetReadiness,
|
||||
timeoutMs,
|
||||
timeoutMs: waitBudgetMs,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -148,8 +142,10 @@ const readWebviewViewport = async (
|
||||
: null;
|
||||
};
|
||||
|
||||
const readRenderedViewport = async (tabId: string): Promise<PreviewRenderedViewportSize | null> => {
|
||||
const webview = findPreviewWebview(tabId);
|
||||
const readRenderedViewport = async (
|
||||
runtimeTabId: string,
|
||||
): Promise<PreviewRenderedViewportSize | null> => {
|
||||
const webview = findPreviewWebview(runtimeTabId);
|
||||
if (!webview) return null;
|
||||
return await readWebviewViewport(webview);
|
||||
};
|
||||
@@ -165,19 +161,23 @@ const readDeclaredViewport = (
|
||||
};
|
||||
|
||||
const waitForRenderedViewport = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
setting: PreviewViewportSetting,
|
||||
timeoutMs: number,
|
||||
context: {
|
||||
readonly requestId: PreviewAutomationRequest["requestId"];
|
||||
readonly operation: PreviewAutomationRequest["operation"];
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: PreviewAutomationRequest["threadId"];
|
||||
},
|
||||
): Promise<PreviewRenderedViewportSize> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, context);
|
||||
try {
|
||||
const webview = findPreviewWebview(tabId);
|
||||
const webview = findPreviewWebview(runtimeTabId);
|
||||
const appliedSettingKey = webview?.getAttribute("data-preview-viewport-key") ?? null;
|
||||
const declaredViewport = readDeclaredViewport(webview);
|
||||
const renderedViewport = webview ? await readWebviewViewport(webview) : null;
|
||||
@@ -211,18 +211,19 @@ const currentStatus = async (
|
||||
): Promise<PreviewAutomationStatus> => {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const { snapshot, tabId } = resolvePreviewAutomationTarget(state, requestedTabId);
|
||||
const visible = tabId
|
||||
? (useBrowserSurfaceStore.getState().byTabId[tabId]?.visible ?? false)
|
||||
const runtimeTabId = tabId ? previewRuntimeTabId(threadRef, state.serverEpoch, tabId) : null;
|
||||
const visible = runtimeTabId
|
||||
? (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ?? false)
|
||||
: false;
|
||||
const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;
|
||||
const viewport = tabId ? await readRenderedViewport(tabId).catch(() => null) : null;
|
||||
const viewport = runtimeTabId ? await readRenderedViewport(runtimeTabId).catch(() => null) : null;
|
||||
const viewportStatus = {
|
||||
...(viewportSetting === undefined ? {} : { viewportSetting }),
|
||||
...(viewport === null ? {} : { viewport }),
|
||||
};
|
||||
if (tabId && previewBridge && state.desktopByTabId[tabId]) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
return { ...status, visible, ...viewportStatus };
|
||||
if (runtimeTabId && tabId && previewBridge && state.desktopByTabId[tabId]) {
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
return { ...status, tabId, visible, ...viewportStatus };
|
||||
}
|
||||
const navStatus = snapshot?.navStatus;
|
||||
return {
|
||||
@@ -340,8 +341,21 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
if (!bridge || !readyTabId) {
|
||||
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
|
||||
}
|
||||
await waitForDesktopOverlay(threadRef, request.requestId, readyTabId, request.timeoutMs);
|
||||
return { bridge, tabId: readyTabId };
|
||||
const readyState = readThreadPreviewState(threadRef);
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, readyState.serverEpoch, readyTabId);
|
||||
await waitForDesktopOverlay(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
readyTabId,
|
||||
runtimeTabId,
|
||||
request.operation,
|
||||
request.timeoutMs,
|
||||
);
|
||||
return {
|
||||
bridge,
|
||||
tabId: readyTabId,
|
||||
runtimeTabId,
|
||||
};
|
||||
};
|
||||
switch (request.operation) {
|
||||
case "status":
|
||||
@@ -381,7 +395,45 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
activeSnapshot = snapshot;
|
||||
tabId = activeTabId;
|
||||
}
|
||||
if (shouldOpenPreviewMiniPlayer(input)) {
|
||||
const activeRuntimeTabId = previewRuntimeTabId(
|
||||
threadRef,
|
||||
readThreadPreviewState(threadRef).serverEpoch,
|
||||
activeTabId,
|
||||
);
|
||||
if (activeSnapshot) {
|
||||
const defaultViewport = previewAutomationDefaultViewport(
|
||||
reusedExistingTab,
|
||||
activeSnapshot,
|
||||
);
|
||||
if (defaultViewport) {
|
||||
const resizeResult = await runBrowserViewportMutation(
|
||||
activeRuntimeTabId,
|
||||
async () => {
|
||||
assertPreviewRuntimeCurrent(
|
||||
threadRef,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request,
|
||||
);
|
||||
return await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: activeTabId,
|
||||
viewport: defaultViewport,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
if (resizeResult._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(resizeResult);
|
||||
}
|
||||
activeSnapshot = resizeResult.value;
|
||||
updatePreviewServerSnapshot(threadRef, resizeResult.value);
|
||||
}
|
||||
}
|
||||
const shouldPresentPreview = shouldOpenPreviewMiniPlayer(input);
|
||||
if (shouldPresentPreview) {
|
||||
usePreviewMiniPlayerStore.getState().open(threadRef, activeTabId);
|
||||
}
|
||||
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
|
||||
@@ -389,15 +441,27 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
threadRef,
|
||||
request.requestId,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request.operation,
|
||||
request.timeoutMs,
|
||||
);
|
||||
}
|
||||
if (shouldPresentPreview) {
|
||||
// React commits the thread-bound surface asynchronously. Settle
|
||||
// briefly so active-thread opens report visible=true, without
|
||||
// turning a background thread's offscreen mini player into an
|
||||
// operation failure.
|
||||
await waitForPreviewPresentation(activeRuntimeTabId);
|
||||
}
|
||||
if (reusedExistingTab && resolvedInputUrl && previewBridge) {
|
||||
await previewBridge.navigate(activeTabId, resolvedInputUrl);
|
||||
assertPreviewRuntimeCurrent(threadRef, activeTabId, activeRuntimeTabId, request);
|
||||
await previewBridge.navigate(activeRuntimeTabId, resolvedInputUrl);
|
||||
await waitForNavigationReadiness(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request.operation,
|
||||
"load",
|
||||
request.timeoutMs,
|
||||
);
|
||||
@@ -414,11 +478,13 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
url: input.url!,
|
||||
},
|
||||
);
|
||||
await ready.bridge.navigate(ready.tabId, resolution.resolvedUrl);
|
||||
await ready.bridge.navigate(ready.runtimeTabId, resolution.resolvedUrl);
|
||||
await waitForNavigationReadiness(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.operation,
|
||||
input.readiness ?? "load",
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
);
|
||||
@@ -428,28 +494,76 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationResizeInput;
|
||||
const setting = resolvePreviewViewport(input);
|
||||
const result = await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: setting,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(result);
|
||||
}
|
||||
updatePreviewServerSnapshot(threadRef, result.value);
|
||||
const viewport = await waitForRenderedViewport(
|
||||
ready.tabId,
|
||||
setting,
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
{
|
||||
requestId: request.requestId,
|
||||
const applied = await runBrowserViewportMutation(ready.runtimeTabId, async () => {
|
||||
const operationState = assertPreviewRuntimeCurrent(
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request,
|
||||
);
|
||||
const previousSetting =
|
||||
operationState.sessions[ready.tabId]?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
const result = await resize({
|
||||
environmentId,
|
||||
threadId: request.threadId,
|
||||
},
|
||||
);
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: setting,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(result);
|
||||
}
|
||||
updatePreviewServerSnapshot(threadRef, result.value);
|
||||
return {
|
||||
previousSetting,
|
||||
serverEpoch: operationState.serverEpoch,
|
||||
};
|
||||
});
|
||||
let viewport: PreviewRenderedViewportSize;
|
||||
try {
|
||||
viewport = await waitForRenderedViewport(
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
setting,
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
{
|
||||
requestId: request.requestId,
|
||||
operation: request.operation,
|
||||
environmentId,
|
||||
threadId: request.threadId,
|
||||
},
|
||||
);
|
||||
} catch (cause) {
|
||||
await runBrowserViewportMutation(ready.runtimeTabId, async () => {
|
||||
const latestState = readThreadPreviewState(threadRef);
|
||||
const latestSetting =
|
||||
latestState.sessions[ready.tabId]?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
if (
|
||||
shouldRollbackPreviewViewport(
|
||||
applied.previousSetting,
|
||||
setting,
|
||||
latestSetting,
|
||||
applied.serverEpoch,
|
||||
latestState.serverEpoch,
|
||||
)
|
||||
) {
|
||||
const rollback = await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: applied.previousSetting,
|
||||
},
|
||||
});
|
||||
if (rollback._tag !== "Failure") {
|
||||
updatePreviewServerSnapshot(threadRef, rollback.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
setting,
|
||||
@@ -459,7 +573,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
case "setColorScheme": {
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationSetColorSchemeInput;
|
||||
await ready.bridge.setColorScheme(ready.tabId, input.colorScheme);
|
||||
await ready.bridge.setColorScheme(ready.runtimeTabId, input.colorScheme);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
colorScheme: input.colorScheme,
|
||||
@@ -467,53 +581,57 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
}
|
||||
case "snapshot": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.snapshot(ready.tabId);
|
||||
return await ready.bridge.automation.snapshot(ready.runtimeTabId);
|
||||
}
|
||||
case "click": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.click(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.click>[1],
|
||||
);
|
||||
}
|
||||
case "type": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.type(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.type>[1],
|
||||
);
|
||||
}
|
||||
case "press": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.press(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.press>[1],
|
||||
);
|
||||
}
|
||||
case "scroll": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.scroll(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.scroll>[1],
|
||||
);
|
||||
}
|
||||
case "evaluate": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.evaluate(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.evaluate>[1],
|
||||
);
|
||||
}
|
||||
case "waitFor": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.waitFor(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.waitFor>[1],
|
||||
);
|
||||
}
|
||||
case "recordingStart": {
|
||||
const ready = await requireReadyTab();
|
||||
const startedAt = await startBrowserRecording(ready.tabId, threadRef);
|
||||
const startedAt = await startBrowserRecording(
|
||||
ready.runtimeTabId,
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
recording: true,
|
||||
@@ -521,15 +639,21 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
};
|
||||
}
|
||||
case "recordingStop": {
|
||||
const activeTabIds = readActiveBrowserRecordingTabIds(threadRef);
|
||||
const activeRecordings = readActiveBrowserRecordingTargets(threadRef);
|
||||
const activeTabIds = new Set(
|
||||
activeRecordings.map((recording) => recording.serverTabId),
|
||||
);
|
||||
const stopTabId = resolveBrowserRecordingStopTarget(
|
||||
activeTabIds,
|
||||
tabId,
|
||||
request.tabIdExplicit ? request.tabId : undefined,
|
||||
);
|
||||
tabId = stopTabId ?? tabId;
|
||||
const artifact = stopTabId ? await stopBrowserRecording(stopTabId) : null;
|
||||
if (!artifact) {
|
||||
const stopRuntimeTabId =
|
||||
activeRecordings.find((recording) => recording.serverTabId === stopTabId)
|
||||
?.runtimeTabId ?? null;
|
||||
const artifact = stopRuntimeTabId ? await stopBrowserRecording(stopRuntimeTabId) : null;
|
||||
if (!artifact || !stopTabId) {
|
||||
return raisePreviewAutomationHostError(
|
||||
new PreviewAutomationRecordingNotActiveError({
|
||||
requestId: request.requestId,
|
||||
@@ -539,7 +663,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
}),
|
||||
);
|
||||
}
|
||||
return artifact;
|
||||
return { ...artifact, tabId: stopTabId };
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
|
||||
@@ -90,6 +90,7 @@ vi.mock("~/state/use-atom-command", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/browser/browserRecording", () => ({
|
||||
findActiveBrowserRecordingRuntimeTabId: vi.fn(() => null),
|
||||
startBrowserRecording: vi.fn(),
|
||||
stopBrowserRecording: vi.fn(),
|
||||
useActiveBrowserRecordingTabIds: () => new Set(),
|
||||
@@ -188,6 +189,13 @@ vi.mock("./useLoadingProgress", () => ({ useLoadingProgress: () => 0 }));
|
||||
vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
|
||||
|
||||
import { PreviewView } from "./PreviewView";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
|
||||
const TEST_THREAD_REF = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
} as const;
|
||||
const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
|
||||
|
||||
describe("PreviewView navigation", () => {
|
||||
beforeEach(() => {
|
||||
@@ -230,7 +238,9 @@ describe("PreviewView navigation", () => {
|
||||
expect(mocks.submittedUrl).not.toBeNull();
|
||||
mocks.submittedUrl?.(submitted);
|
||||
|
||||
await vi.waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith("tab-1", expected));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
|
||||
);
|
||||
expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
|
||||
{
|
||||
environmentId: "environment-1",
|
||||
@@ -258,7 +268,7 @@ describe("PreviewView navigation", () => {
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.navigate).toHaveBeenCalledWith(
|
||||
"tab-1",
|
||||
TEST_RUNTIME_TAB_ID,
|
||||
"http://172.25.85.75:5173/app?mode=test#top",
|
||||
),
|
||||
);
|
||||
@@ -306,11 +316,15 @@ describe("PreviewView navigation", () => {
|
||||
|
||||
renderToStaticMarkup(<PreviewView {...props} />);
|
||||
mocks.toggleNativePictureInPicture?.();
|
||||
await vi.waitFor(() => expect(mocks.openPictureInPicture).toHaveBeenCalledWith("tab-1"));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
|
||||
);
|
||||
|
||||
mocks.pictureInPicture = true;
|
||||
renderToStaticMarkup(<PreviewView {...props} />);
|
||||
mocks.toggleNativePictureInPicture?.();
|
||||
await vi.waitFor(() => expect(mocks.closePictureInPicture).toHaveBeenCalledWith("tab-1"));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
subscribeBrowserViewportChange,
|
||||
} from "~/browser/browserViewportActions";
|
||||
import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { PreviewUnreachable } from "./PreviewUnreachable";
|
||||
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
|
||||
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
|
||||
@@ -47,6 +48,7 @@ import { usePreviewSession } from "./usePreviewSession";
|
||||
import { ZoomIndicator } from "./ZoomIndicator";
|
||||
import { AgentBrowserCursor } from "./AgentBrowserCursor";
|
||||
import {
|
||||
findActiveBrowserRecordingRuntimeTabId,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
useActiveBrowserRecordingTabIds,
|
||||
@@ -93,6 +95,15 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, []);
|
||||
|
||||
const tabId = requestedTabId ?? previewState.activeTabId;
|
||||
const runtimeTabId = tabId
|
||||
? previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId)
|
||||
: null;
|
||||
const recordingRuntimeTabId =
|
||||
tabId && runtimeTabId
|
||||
? activeRecordingTabIds.has(runtimeTabId)
|
||||
? runtimeTabId
|
||||
: findActiveBrowserRecordingRuntimeTabId(threadRef, tabId)
|
||||
: null;
|
||||
const snapshot = tabId ? (previewState.sessions[tabId] ?? null) : null;
|
||||
const desktopOverlay = tabId ? (previewState.desktopByTabId[tabId] ?? null) : null;
|
||||
const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
|
||||
@@ -115,15 +126,15 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
: undefined;
|
||||
const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
const panelRect = useBrowserSurfaceStore((state) =>
|
||||
tabId ? (state.byTabId[tabId]?.rect ?? null) : null,
|
||||
runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
|
||||
);
|
||||
|
||||
const navigateToResolvedUrl = useCallback(
|
||||
async (resolvedUrl: string) => {
|
||||
if (tabId && previewBridge) {
|
||||
if (runtimeTabId && previewBridge) {
|
||||
// Drive the webview imperatively; `usePreviewBridge` mirrors the
|
||||
// resolved URL back to the server so other clients stay in sync.
|
||||
await previewBridge.navigate(tabId, resolvedUrl);
|
||||
await previewBridge.navigate(runtimeTabId, resolvedUrl);
|
||||
rememberPreviewUrl(threadRef, resolvedUrl);
|
||||
} else {
|
||||
await openPreviewSession({
|
||||
@@ -133,7 +144,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
});
|
||||
}
|
||||
},
|
||||
[open, tabId, threadRef],
|
||||
[open, runtimeTabId, threadRef],
|
||||
);
|
||||
|
||||
const handleSubmitUrl = useCallback(
|
||||
@@ -159,20 +170,20 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.refresh(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleZoomIn = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.zoomIn(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleZoomOut = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.zoomOut(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleResetZoom = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleViewportChange = useCallback(
|
||||
async (nextViewport: PreviewViewportSetting) => {
|
||||
@@ -200,32 +211,32 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
|
||||
const handleToggleDeviceToolbar = () => {
|
||||
if (!tabId) return;
|
||||
if (!runtimeTabId) return;
|
||||
if (viewport._tag !== "fill") {
|
||||
void commitBrowserViewportChange(tabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
|
||||
void commitBrowserViewportChange(runtimeTabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const responsiveSize = panelRect
|
||||
? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)
|
||||
: { width: 1024, height: 768 };
|
||||
void commitBrowserViewportChange(tabId, { _tag: "freeform", ...responsiveSize }).catch(
|
||||
void commitBrowserViewportChange(runtimeTabId, { _tag: "freeform", ...responsiveSize }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!tabId) return;
|
||||
return subscribeBrowserViewportChange(tabId, handleViewportChange);
|
||||
}, [handleViewportChange, tabId]);
|
||||
if (!runtimeTabId) return;
|
||||
return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
|
||||
}, [handleViewportChange, runtimeTabId]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.goBack(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleForward = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.goForward(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
if (!localApi || !url) return;
|
||||
@@ -243,26 +254,25 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, [miniPlayer?.tabId, tabId, threadRef]);
|
||||
|
||||
const handleNativePictureInPicture = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId) return;
|
||||
const operation = desktopOverlay?.pictureInPicture
|
||||
? previewBridge.pictureInPicture.close
|
||||
: previewBridge.pictureInPicture.open;
|
||||
void operation(tabId).catch((error) => {
|
||||
void operation(runtimeTabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to update popped-out preview",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [desktopOverlay?.pictureInPicture, tabId]);
|
||||
}, [desktopOverlay?.pictureInPicture, runtimeTabId]);
|
||||
|
||||
const handleCapture = useCallback(
|
||||
(record: boolean) => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId || !tabId) return;
|
||||
const bridge = previewBridge;
|
||||
const recordingThisTab = activeRecordingTabIds.has(tabId);
|
||||
if (recordingThisTab) {
|
||||
void stopBrowserRecording(tabId).then(
|
||||
if (recordingRuntimeTabId) {
|
||||
void stopBrowserRecording(recordingRuntimeTabId).then(
|
||||
(artifact) => {
|
||||
if (!artifact) return;
|
||||
let pathCopied = false;
|
||||
@@ -354,7 +364,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
return;
|
||||
}
|
||||
if (record) {
|
||||
void startBrowserRecording(tabId, threadRef).catch((error) => {
|
||||
void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to start recording",
|
||||
@@ -363,7 +373,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
});
|
||||
return;
|
||||
}
|
||||
void bridge.captureScreenshot(tabId).then(
|
||||
void bridge.captureScreenshot(runtimeTabId).then(
|
||||
(artifact) => {
|
||||
const revealAction = {
|
||||
children: revealInFileExplorerLabel(navigator.platform),
|
||||
@@ -493,13 +503,13 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
},
|
||||
);
|
||||
},
|
||||
[activeRecordingTabIds, tabId, threadRef],
|
||||
[recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
|
||||
);
|
||||
|
||||
const handlePickElement = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId) return;
|
||||
if (pickActiveRef.current) {
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// Snapshot whatever the user was focused on (typically the chat
|
||||
@@ -513,7 +523,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
setPickActive(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const annotation = await previewBridge.pickElement(tabId);
|
||||
const annotation = await previewBridge.pickElement(runtimeTabId);
|
||||
if (!annotation) return;
|
||||
addPreviewAnnotation(threadRef, annotation);
|
||||
const screenshotFile = await previewAnnotationScreenshotFile(annotation);
|
||||
@@ -551,7 +561,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [addImage, addPreviewAnnotation, tabId, threadRef]);
|
||||
}, [addImage, addPreviewAnnotation, runtimeTabId, threadRef]);
|
||||
|
||||
// If the active tab changes mid-pick (close, thread switch, hot restart),
|
||||
// tell main to tear down the in-flight session AND reset our local toggle
|
||||
@@ -560,12 +570,12 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
return () => {
|
||||
if (!pickActiveRef.current) return;
|
||||
pickActiveRef.current = false;
|
||||
if (previewBridge && tabId) {
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
if (previewBridge && runtimeTabId) {
|
||||
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
|
||||
}
|
||||
if (isMountedRef.current) setPickActive(false);
|
||||
};
|
||||
}, [tabId]);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
// Subscribe only while visible; `toggle-panel` is owned by ChatView's
|
||||
// URL-aware handler regardless of whether the panel is currently mounted.
|
||||
@@ -615,7 +625,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
|
||||
onCapture={previewBridge && tabId ? handleCapture : undefined}
|
||||
captureDisabled={!desktopOverlay || isUnreachable}
|
||||
recording={tabId !== null && activeRecordingTabIds.has(tabId)}
|
||||
recording={recordingRuntimeTabId !== null}
|
||||
onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}
|
||||
pictureInPicture={miniPlayer?.tabId === tabId}
|
||||
pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}
|
||||
@@ -631,7 +641,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
trailingActions={
|
||||
previewBridge ? (
|
||||
<PreviewMoreMenu
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
hasWebContents={desktopOverlay?.hasWebContents ?? false}
|
||||
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
|
||||
colorScheme={desktopOverlay?.colorScheme ?? "system"}
|
||||
@@ -645,10 +655,10 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
/>
|
||||
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
{tabId && snapshot && !showEmptyState ? (
|
||||
{runtimeTabId && snapshot && !showEmptyState ? (
|
||||
<BrowserSurfaceSlot
|
||||
key={tabId}
|
||||
tabId={tabId}
|
||||
key={runtimeTabId}
|
||||
tabId={runtimeTabId}
|
||||
visible={visible && !isUnreachable}
|
||||
className="absolute inset-0 h-full w-full"
|
||||
/>
|
||||
@@ -664,9 +674,9 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
{snapshot && desktopOverlay ? (
|
||||
<ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
|
||||
) : null}
|
||||
{tabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
|
||||
{runtimeTabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
|
||||
<AgentBrowserCursor
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
zoomFactor={desktopOverlay.zoomFactor}
|
||||
controller={controller}
|
||||
/>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
|
||||
import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef } from "react";
|
||||
|
||||
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { useThreadPreviewState } from "~/previewStateStore";
|
||||
@@ -49,6 +50,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
);
|
||||
const previewState = useThreadPreviewState(threadRef);
|
||||
const snapshot = previewState.sessions[tabId] ?? null;
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
|
||||
const desktopOverlay = previewState.desktopByTabId[tabId] ?? null;
|
||||
const position = miniPlayer?.tabId === tabId ? miniPlayer.position : null;
|
||||
const size =
|
||||
@@ -69,7 +71,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
const operation = desktopOverlay?.pictureInPicture
|
||||
? previewBridge.pictureInPicture.close
|
||||
: previewBridge.pictureInPicture.open;
|
||||
void operation(tabId).catch((error) => {
|
||||
void operation(runtimeTabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to update popped-out preview",
|
||||
@@ -284,7 +286,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
<div className="relative h-full min-h-0">
|
||||
<div className="absolute inset-0 z-[29] rounded-xl bg-muted shadow-2xl/35" />
|
||||
<BrowserSurfaceSlot
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
visible={Boolean(desktopOverlay?.hasWebContents)}
|
||||
cornerRadius={12}
|
||||
fitSourceContent
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
PREVIEW_HOST_RESPONSE_MARGIN_MS,
|
||||
resolveHostWaitBudgetMs,
|
||||
} from "./previewAutomationHostBudget";
|
||||
|
||||
describe("resolveHostWaitBudgetMs", () => {
|
||||
it("always expires before the broker deadline, at every request budget", () => {
|
||||
// The whole point of the helper: the host must lose no race, at any scale.
|
||||
for (const requestTimeoutMs of [1, 2, 10, 100, 249, 250, 999, 1_500, 3_000, 15_000, 60_000]) {
|
||||
expect(resolveHostWaitBudgetMs(requestTimeoutMs)).toBeLessThan(requestTimeoutMs);
|
||||
}
|
||||
});
|
||||
|
||||
it("reserves the full response margin once the request budget allows it", () => {
|
||||
expect(resolveHostWaitBudgetMs(15_000)).toBe(15_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
|
||||
expect(resolveHostWaitBudgetMs(60_000)).toBe(60_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
|
||||
});
|
||||
|
||||
it("keeps most of a short request budget instead of collapsing it", () => {
|
||||
expect(resolveHostWaitBudgetMs(1_000)).toBe(800);
|
||||
expect(resolveHostWaitBudgetMs(100)).toBe(80);
|
||||
});
|
||||
|
||||
it("grows monotonically with the request budget", () => {
|
||||
const budgets = [1, 10, 100, 1_000, 3_000, 15_000].map(resolveHostWaitBudgetMs);
|
||||
for (let index = 1; index < budgets.length; index += 1) {
|
||||
expect(budgets[index]!).toBeGreaterThanOrEqual(budgets[index - 1]!);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a non-negative budget for invalid input", () => {
|
||||
for (const invalid of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
||||
expect(resolveHostWaitBudgetMs(invalid)).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Reserve for delivering the host's response back to the broker once a wait
|
||||
* gives up. Without it a host wait that runs the full request budget always
|
||||
* loses the race to the broker's own deadline, so the agent sees an opaque
|
||||
* "timed out" instead of the specific failure the host was about to report.
|
||||
*/
|
||||
export const PREVIEW_HOST_RESPONSE_MARGIN_MS = 1_500;
|
||||
|
||||
/**
|
||||
* Share of the request budget reserved when the request is too short for the
|
||||
* full margin, so the host still expires first rather than being clamped past
|
||||
* the broker's deadline.
|
||||
*/
|
||||
const HOST_RESPONSE_MARGIN_FRACTION = 0.2;
|
||||
|
||||
/**
|
||||
* Budget a host-side wait so it always expires before the broker's deadline
|
||||
* for the same request.
|
||||
*/
|
||||
export function resolveHostWaitBudgetMs(requestTimeoutMs: number): number {
|
||||
if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {
|
||||
return 0;
|
||||
}
|
||||
const reservedMs = Math.min(
|
||||
PREVIEW_HOST_RESPONSE_MARGIN_MS,
|
||||
Math.ceil(requestTimeoutMs * HOST_RESPONSE_MARGIN_FRACTION),
|
||||
);
|
||||
return Math.max(0, requestTimeoutMs - reservedMs);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tool
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DEFAULT_PREVIEW_AUTOMATION_VIEWPORT,
|
||||
previewAutomationDefaultViewport,
|
||||
previewAutomationOpenNeedsOverlay,
|
||||
shouldOpenPreviewMiniPlayer,
|
||||
} from "./previewAutomationOpenReadiness";
|
||||
@@ -58,4 +60,20 @@ describe("preview automation open readiness", () => {
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("gives newly-created automation tabs a stable desktop viewport", () => {
|
||||
expect(previewAutomationDefaultViewport(false, snapshot({ _tag: "Idle" }))).toEqual(
|
||||
DEFAULT_PREVIEW_AUTOMATION_VIEWPORT,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves reused and already-fixed browser viewports", () => {
|
||||
expect(previewAutomationDefaultViewport(true, snapshot({ _tag: "Idle" }))).toBeNull();
|
||||
expect(
|
||||
previewAutomationDefaultViewport(false, {
|
||||
...snapshot({ _tag: "Idle" }),
|
||||
viewport: { _tag: "freeform", width: 900, height: 600 },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
|
||||
import {
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
type PreviewAutomationOpenInput,
|
||||
type PreviewSessionSnapshot,
|
||||
type PreviewViewportSetting,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export const DEFAULT_PREVIEW_AUTOMATION_VIEWPORT = {
|
||||
_tag: "freeform",
|
||||
width: 1280,
|
||||
height: 800,
|
||||
} as const satisfies PreviewViewportSetting;
|
||||
|
||||
export function shouldOpenPreviewMiniPlayer(input: PreviewAutomationOpenInput): boolean {
|
||||
return input.open ?? input.show ?? true;
|
||||
@@ -10,3 +21,13 @@ export function previewAutomationOpenNeedsOverlay(
|
||||
): boolean {
|
||||
return input.url !== undefined || snapshot.navStatus._tag !== "Idle";
|
||||
}
|
||||
|
||||
export function previewAutomationDefaultViewport(
|
||||
reusedExistingTab: boolean,
|
||||
snapshot: PreviewSessionSnapshot,
|
||||
): PreviewViewportSetting | null {
|
||||
const viewport = snapshot.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
return !reusedExistingTab && viewport._tag === "fill"
|
||||
? DEFAULT_PREVIEW_AUTOMATION_VIEWPORT
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readThreadPreviewState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/previewStateStore", () => ({
|
||||
applyPreviewServerSnapshot: vi.fn(),
|
||||
readThreadPreviewState: mocks.readThreadPreviewState,
|
||||
reconcilePreviewServerSessions: vi.fn(),
|
||||
updatePreviewServerSnapshot: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./previewBridge", () => ({
|
||||
previewBridge: {
|
||||
automation: {
|
||||
evaluate: vi.fn(),
|
||||
status: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
|
||||
import { PreviewAutomationTargetUnavailableError } from "./previewAutomationErrors";
|
||||
import { waitForNavigationReadiness } from "./previewNavigationReadiness";
|
||||
|
||||
describe("waitForNavigationReadiness", () => {
|
||||
it("rejects a replaced runtime target even when readiness polling is disabled", async () => {
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
const tabId = "tab_1";
|
||||
const staleRuntimeTabId = previewRuntimeTabId(threadRef, "epoch-1", tabId);
|
||||
mocks.readThreadPreviewState.mockReturnValue({
|
||||
serverEpoch: "epoch-2",
|
||||
sessions: {
|
||||
[tabId]: { tabId },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForNavigationReadiness(
|
||||
threadRef,
|
||||
"request-1",
|
||||
tabId,
|
||||
staleRuntimeTabId,
|
||||
"navigate",
|
||||
"none",
|
||||
100,
|
||||
),
|
||||
).rejects.toBeInstanceOf(PreviewAutomationTargetUnavailableError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
type PreviewAutomationNavigateInput,
|
||||
type PreviewAutomationRequest,
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { isCurrentPreviewRuntimeTab } from "~/browser/previewRuntimeTabId";
|
||||
import { readThreadPreviewState } from "~/previewStateStore";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
import {
|
||||
PreviewAutomationNavigationTimeoutError,
|
||||
PreviewAutomationTargetUnavailableError,
|
||||
} from "./previewAutomationErrors";
|
||||
|
||||
export function assertPreviewRuntimeCurrent(
|
||||
threadRef: ScopedThreadRef,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
request: Pick<PreviewAutomationRequest, "operation" | "requestId">,
|
||||
) {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
if (
|
||||
state.sessions[tabId] &&
|
||||
isCurrentPreviewRuntimeTab(threadRef, state.serverEpoch, tabId, runtimeTabId)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
throw new PreviewAutomationTargetUnavailableError({
|
||||
requestId: request.requestId,
|
||||
operation: request.operation,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
bridgeAvailable: Boolean(previewBridge),
|
||||
});
|
||||
}
|
||||
|
||||
export async function waitForNavigationReadiness(
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
operation: PreviewAutomationRequest["operation"],
|
||||
readiness: PreviewAutomationNavigateInput["readiness"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
const targetReadiness = readiness ?? "load";
|
||||
if (!previewBridge) return;
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
|
||||
if (targetReadiness === "none") return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
|
||||
if (targetReadiness === "domContentLoaded") {
|
||||
const readyState = await previewBridge.automation.evaluate(runtimeTabId, {
|
||||
expression: "document.readyState",
|
||||
});
|
||||
if (readyState === "interactive" || readyState === "complete") return;
|
||||
} else {
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
if (status.available && !status.loading) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
}
|
||||
throw new PreviewAutomationNavigationTimeoutError({
|
||||
requestId,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
readiness: targetReadiness,
|
||||
timeoutMs,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
|
||||
|
||||
describe("shouldRollbackPreviewViewport", () => {
|
||||
const fill = { _tag: "fill" } as const;
|
||||
const requested = { _tag: "freeform", width: 900, height: 600 } as const;
|
||||
|
||||
it("rolls back a timed-out request that still owns the latest setting", () => {
|
||||
expect(shouldRollbackPreviewViewport(fill, requested, requested, "server-a", "server-a")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not overwrite a newer resize, replacement server, or repeated setting", () => {
|
||||
expect(
|
||||
shouldRollbackPreviewViewport(
|
||||
fill,
|
||||
requested,
|
||||
{
|
||||
_tag: "freeform",
|
||||
width: 1024,
|
||||
height: 768,
|
||||
},
|
||||
"server-a",
|
||||
"server-a",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(shouldRollbackPreviewViewport(fill, requested, requested, "server-a", "server-b")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
shouldRollbackPreviewViewport(requested, requested, requested, "server-a", "server-a"),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PreviewViewportSetting } from "@t3tools/contracts";
|
||||
|
||||
import { browserViewportSettingKey } from "~/browser/browserViewportLayout";
|
||||
|
||||
export function shouldRollbackPreviewViewport(
|
||||
previous: PreviewViewportSetting,
|
||||
requested: PreviewViewportSetting,
|
||||
latest: PreviewViewportSetting,
|
||||
operationServerEpoch: string | null,
|
||||
currentServerEpoch: string | null,
|
||||
): boolean {
|
||||
const requestedKey = browserViewportSettingKey(requested);
|
||||
return (
|
||||
currentServerEpoch === operationServerEpoch &&
|
||||
browserViewportSettingKey(latest) === requestedKey &&
|
||||
browserViewportSettingKey(previous) !== requestedKey
|
||||
);
|
||||
}
|
||||
@@ -19,8 +19,12 @@ import { previewBridge } from "./previewBridge";
|
||||
* Mirrors low-latency desktop state into the store and reflects navigation
|
||||
* events back to the server. Webview lifetime is owned by ElectronBrowserHost.
|
||||
*/
|
||||
export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: string }): void {
|
||||
const { threadRef, tabId } = input;
|
||||
export function usePreviewBridge(input: {
|
||||
threadRef: ScopedThreadRef;
|
||||
tabId: string;
|
||||
runtimeTabId: string;
|
||||
}): void {
|
||||
const { threadRef, tabId, runtimeTabId } = input;
|
||||
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
|
||||
const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
|
||||
const bridge = previewBridge;
|
||||
@@ -36,9 +40,9 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
|
||||
lastReportedKind.current = null;
|
||||
lastDesktopNavStatus.current = null;
|
||||
const unsubscribe = bridge.onStateChange((changedTabId, state) => {
|
||||
if (changedTabId !== tabId) return;
|
||||
if (changedTabId !== runtimeTabId) return;
|
||||
if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
|
||||
clearBrowserPointer(tabId);
|
||||
clearBrowserPointer(runtimeTabId);
|
||||
}
|
||||
lastDesktopNavStatus.current = state.navStatus;
|
||||
applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
|
||||
@@ -58,7 +62,7 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
|
||||
});
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [bridge, clearBrowserPointer, reportStatus, tabId, threadRef]);
|
||||
}, [bridge, clearBrowserPointer, reportStatus, runtimeTabId, tabId, threadRef]);
|
||||
}
|
||||
|
||||
function shouldClearBrowserPointer(
|
||||
|
||||
@@ -39,7 +39,6 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
|
||||
return Atom.make((get) => {
|
||||
let disposed = false;
|
||||
let sessionsVersion = 0;
|
||||
let eventsVersion = 0;
|
||||
|
||||
const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
|
||||
@@ -60,10 +59,8 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
get.addFinalizer(() => {
|
||||
disposed = true;
|
||||
});
|
||||
const initialSessions = get.once(sessionsAtom);
|
||||
const initialEvent = get.once(eventsAtom);
|
||||
get.subscribe(sessionsAtom, (result) => {
|
||||
sessionsVersion += 1;
|
||||
reconcileSessions(result);
|
||||
});
|
||||
get.subscribe(eventsAtom, (result) => {
|
||||
@@ -72,7 +69,10 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
if (disposed) return;
|
||||
if (sessionsVersion === 0) reconcileSessions(initialSessions);
|
||||
// The cached list can predate an automation-created tab. Keep the local
|
||||
// snapshot visible until an authoritative refresh arrives instead of
|
||||
// reconciling against a stale empty result when the panel first mounts.
|
||||
get.refresh(sessionsAtom);
|
||||
if (eventsVersion === 0) applyLatestEvent(initialEvent);
|
||||
});
|
||||
}).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));
|
||||
|
||||
@@ -392,7 +392,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -445,10 +445,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(isTextGenerationModelDirty ? ["Text generation model"] : []),
|
||||
],
|
||||
[
|
||||
isGitWritingModelDirty,
|
||||
isTextGenerationModelDirty,
|
||||
settings.autoOpenPlanSidebar,
|
||||
settings.confirmThreadArchive,
|
||||
settings.confirmThreadDelete,
|
||||
@@ -533,21 +533,21 @@ export function GeneralSettingsPanel() {
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const gitModelInstanceEntries = sortProviderInstanceEntries(
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = gitModelInstanceEntries.find(
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const gitModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -1000,9 +1000,9 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Text generation model"
|
||||
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
description="Default model for generated text like thread titles and source control content. Source control settings can override it with a dedicated source control writer model."
|
||||
resetAction={
|
||||
isGitWritingModelDirty ? (
|
||||
isTextGenerationModelDirty ? (
|
||||
<SettingResetButton
|
||||
label="text generation model"
|
||||
onClick={() =>
|
||||
@@ -1020,8 +1020,8 @@ export function GeneralSettingsPanel() {
|
||||
activeInstanceId={textGenInstanceId}
|
||||
model={textGenModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={gitModelInstanceEntries}
|
||||
modelOptionsByInstance={gitModelOptionsByInstance}
|
||||
instanceEntries={textGenerationModelInstanceEntries}
|
||||
modelOptionsByInstance={textGenerationModelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
type Icon,
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
@@ -195,7 +196,7 @@ function itemSummary({
|
||||
<span>
|
||||
{item.label} is not authenticated on this server. Sign in or configure credentials using
|
||||
the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
|
||||
tool on the server host to enable pull request features.
|
||||
tool on the server host to enable change request features.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -513,6 +514,8 @@ export function SourceControlSettingsPanel() {
|
||||
onScan={handleScan}
|
||||
/>
|
||||
)}
|
||||
|
||||
{environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useRef } from "react";
|
||||
import type { SourceControlWritingStyleMode } from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import {
|
||||
getCustomModelOptionsByInstance,
|
||||
resolveAppModelSelectionState,
|
||||
} from "../../modelSelection";
|
||||
import { primaryServerProvidersAtom } from "../../state/server";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
|
||||
{
|
||||
repo_conventions: {
|
||||
label: "Repository conventions",
|
||||
description: "In each project, matches recent change descriptions and change request titles.",
|
||||
},
|
||||
conventional_commits: {
|
||||
label: "Conventional Commits",
|
||||
description:
|
||||
"Uses Conventional Commit prefixes for change descriptions; change request titles and descriptions stay concise.",
|
||||
},
|
||||
custom: {
|
||||
label: "Custom instructions",
|
||||
description:
|
||||
"Applies your instructions to change descriptions and change request titles and descriptions in every project.",
|
||||
},
|
||||
};
|
||||
|
||||
export function SourceControlWritingSettingsSection() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
|
||||
const style = settings.sourceControlWritingStyle;
|
||||
const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
|
||||
const isSourceControlWritingStyleDirty =
|
||||
style.mode !== defaults.mode || style.customInstructions !== defaults.customInstructions;
|
||||
|
||||
const defaultModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
|
||||
const resolvedSourceControlWriterSelection = resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
serverProviders,
|
||||
);
|
||||
const activeSelection =
|
||||
resolvedSourceControlWriterSelection === settings.textGenerationModelSelection
|
||||
? defaultModelSelection
|
||||
: resolvedSourceControlWriterSelection;
|
||||
const instanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const modelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
activeSelection.instanceId,
|
||||
activeSelection.model,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Text generation">
|
||||
<SettingsRow
|
||||
title="Source control writing style"
|
||||
description={MODE_OPTIONS[style.mode].description}
|
||||
resetAction={
|
||||
isSourceControlWritingStyleDirty ? (
|
||||
<SettingResetButton
|
||||
label="source control writing style"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: defaults.mode,
|
||||
customInstructions: defaults.customInstructions,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={style.mode}
|
||||
onValueChange={(value) => {
|
||||
const customInstructions = customInstructionsRef.current?.value.trim();
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: value as SourceControlWritingStyleMode,
|
||||
...(customInstructions !== undefined ? { customInstructions } : {}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-56" aria-label="Source control writing style">
|
||||
<SelectValue>{MODE_OPTIONS[style.mode].label}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
|
||||
<SelectItem key={mode} hideIndicator value={mode}>
|
||||
{MODE_OPTIONS[mode].label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
>
|
||||
{style.mode === "custom" ? (
|
||||
<div className="mt-3 max-w-2xl pb-3.5">
|
||||
<Textarea
|
||||
key={style.customInstructions}
|
||||
ref={customInstructionsRef}
|
||||
defaultValue={style.customInstructions}
|
||||
onBlur={(event) => {
|
||||
const customInstructions = event.target.value.trim();
|
||||
if (customInstructions !== style.customInstructions) {
|
||||
updateSettings({ sourceControlWritingStyle: { customInstructions } });
|
||||
}
|
||||
}}
|
||||
rows={4}
|
||||
placeholder="Keep titles concise. Use short bullet points in descriptions."
|
||||
aria-label="Custom source control writing instructions"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
title="Follow change request templates"
|
||||
description="Structures change request descriptions using the current repository's template when one is available."
|
||||
resetAction={
|
||||
style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
|
||||
<SettingResetButton
|
||||
label="change request templates"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: defaults.followChangeRequestTemplates,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={style.followChangeRequestTemplates}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: Boolean(checked),
|
||||
},
|
||||
})
|
||||
}
|
||||
aria-label="Follow change request templates"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Source control writer model"
|
||||
description="Optional model override for change descriptions, change request titles and descriptions, and branch or bookmark names. Off uses the global text generation model."
|
||||
control={
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{usesDedicatedModel ? (
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeSelection.instanceId}
|
||||
model={activeSelection.model}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
triggerAriaLabel="Source control writer model"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: createModelSelection(instanceId, model),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<Switch
|
||||
checked={usesDedicatedModel}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: checked
|
||||
? createModelSelection(
|
||||
defaultModelSelection.instanceId,
|
||||
defaultModelSelection.model,
|
||||
defaultModelSelection.options,
|
||||
)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
aria-label="Use a separate source control writer model"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -587,7 +587,7 @@ function Toasts({ position }: { position: ToastPosition }) {
|
||||
return (
|
||||
<Toast.Root
|
||||
className={cn(
|
||||
"absolute z-[calc(9999-var(--toast-index))] w-full overflow-visible select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
"dropdown-glass absolute z-[calc(9999-var(--toast-index))] w-full overflow-visible select-none rounded-lg text-popover-foreground shadow-xl shadow-black/25 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s]",
|
||||
// Base positioning using data-position
|
||||
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
|
||||
"data-[position*=left]:right-auto data-[position*=left]:left-0",
|
||||
@@ -739,10 +739,8 @@ function AnchoredToasts() {
|
||||
>
|
||||
<Toast.Root
|
||||
className={cn(
|
||||
"relative overflow-visible text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
tooltipStyle
|
||||
? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
|
||||
: "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
|
||||
"dropdown-glass relative overflow-visible text-balance text-popover-foreground text-xs shadow-xl shadow-black/25 transition-[scale,opacity] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
||||
tooltipStyle ? "rounded-md" : "rounded-lg",
|
||||
)}
|
||||
data-slot="toast-popup"
|
||||
toast={toast}
|
||||
|
||||
@@ -17,6 +17,7 @@ function TooltipPopup({
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
side = "top",
|
||||
variant = "default",
|
||||
anchor,
|
||||
children,
|
||||
...props
|
||||
@@ -24,6 +25,7 @@ function TooltipPopup({
|
||||
align?: TooltipPrimitive.Positioner.Props["align"];
|
||||
side?: TooltipPrimitive.Positioner.Props["side"];
|
||||
sideOffset?: TooltipPrimitive.Positioner.Props["sideOffset"];
|
||||
variant?: "default" | "glass";
|
||||
anchor?: TooltipPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
return (
|
||||
@@ -38,7 +40,10 @@ function TooltipPopup({
|
||||
>
|
||||
<TooltipPrimitive.Popup
|
||||
className={cn(
|
||||
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) text-balance rounded-md border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs shadow-md/5 transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 data-instant:duration-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) text-balance rounded-md text-popover-foreground text-xs transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 data-instant:duration-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
variant === "glass"
|
||||
? "dropdown-glass shadow-xl shadow-black/25 before:hidden"
|
||||
: "border bg-popover not-dark:bg-clip-padding shadow-md/5",
|
||||
className,
|
||||
)}
|
||||
data-slot="tooltip-popup"
|
||||
|
||||
@@ -32,6 +32,8 @@ import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
@@ -144,7 +146,7 @@ function persistClientSettings(settings: ClientSettings): void {
|
||||
|
||||
const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
|
||||
|
||||
function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
function splitPatch(patch: UnifiedSettingsPatch): {
|
||||
serverPatch: ServerSettingsPatch;
|
||||
clientPatch: ClientSettingsPatch;
|
||||
} {
|
||||
@@ -246,7 +248,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
|
||||
"server settings update",
|
||||
);
|
||||
const updateSettings = useCallback(
|
||||
(patch: Partial<UnifiedSettings>) => {
|
||||
(patch: UnifiedSettingsPatch) => {
|
||||
const { serverPatch, clientPatch } = splitPatch(patch);
|
||||
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { buildPatchCacheKey, getRenderablePatch } from "./diffRendering";
|
||||
import { buildPatchCacheKey, getDiffLineStat, getRenderablePatch } from "./diffRendering";
|
||||
|
||||
describe("buildPatchCacheKey", () => {
|
||||
it("returns a stable cache key for identical content", () => {
|
||||
@@ -82,3 +82,33 @@ describe("getRenderablePatch", () => {
|
||||
expect(parsed.files[0]?.hunks[0]?.unifiedLineStart).toBe(47);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDiffLineStat", () => {
|
||||
it("totals additions and deletions across every file and hunk", () => {
|
||||
const patch = [
|
||||
"diff --git a/example.ts b/example.ts",
|
||||
"--- a/example.ts",
|
||||
"+++ b/example.ts",
|
||||
"@@ -1,2 +1,3 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"+added",
|
||||
" context",
|
||||
"@@ -10,2 +11,1 @@",
|
||||
"-removed",
|
||||
" context",
|
||||
"diff --git a/README.md b/README.md",
|
||||
"--- a/README.md",
|
||||
"+++ b/README.md",
|
||||
"@@ -1 +1,2 @@",
|
||||
" title",
|
||||
"+description",
|
||||
].join("\n");
|
||||
|
||||
const parsed = getRenderablePatch(patch);
|
||||
expect(parsed?.kind).toBe("files");
|
||||
if (parsed?.kind !== "files") return;
|
||||
|
||||
expect(getDiffLineStat(parsed.files)).toEqual({ additions: 3, deletions: 2 });
|
||||
});
|
||||
});
|
||||
@@ -52,6 +52,25 @@ export type RenderablePatch =
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export interface DiffLineStat {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
export function getDiffLineStat(files: ReadonlyArray<FileDiffMetadata>): DiffLineStat {
|
||||
return files.reduce<DiffLineStat>(
|
||||
(total, file) => {
|
||||
for (const hunk of file.hunks) {
|
||||
total.additions += hunk.additionLines;
|
||||
total.deletions += hunk.deletionLines;
|
||||
}
|
||||
|
||||
return total;
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
}
|
||||
|
||||
interface RenderablePatchOptions {
|
||||
/**
|
||||
* Pierre's partial-patch parser keeps hunk render starts in source-file
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
defaultInstanceIdForDriver,
|
||||
type ModelSelection,
|
||||
ProviderDriverKind,
|
||||
@@ -281,7 +281,7 @@ export function resolveAppModelSelectionState(
|
||||
): ModelSelection {
|
||||
const selection = settings.textGenerationModelSelection ?? {
|
||||
instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
model: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
};
|
||||
const entries = deriveProviderInstanceEntries(providers);
|
||||
const selectedEntry = entries.find(
|
||||
@@ -296,7 +296,7 @@ export function resolveAppModelSelectionState(
|
||||
const model =
|
||||
resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??
|
||||
entry.models[0]?.slug ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
|
||||
if (!model) {
|
||||
return createModelSelection(entry.instanceId, "", []);
|
||||
}
|
||||
|
||||
@@ -480,6 +480,48 @@ describe("previewStateStore (single-tab)", () => {
|
||||
expect(state.serverRevision).toBe(0);
|
||||
});
|
||||
|
||||
it("does not carry raw-tab state across a server restart", () => {
|
||||
const previous = makeSnapshot({
|
||||
navStatus: { _tag: "Success", url: "https://old.example", title: "Old" },
|
||||
updatedAt: "2026-01-01T00:00:02.000Z",
|
||||
});
|
||||
applyPreviewServerEventImpl(ref, {
|
||||
type: "opened",
|
||||
threadId: "thread-1",
|
||||
tabId: previous.tabId,
|
||||
createdAt: previous.updatedAt,
|
||||
serverEpoch,
|
||||
revision: 12,
|
||||
snapshot: previous,
|
||||
});
|
||||
beginPreviewSessionClose(ref, previous.tabId);
|
||||
applyPreviewDesktopState(ref, previous.tabId, {
|
||||
hasWebContents: true,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
const restarted = makeSnapshot({
|
||||
navStatus: { _tag: "Success", url: "https://new.example", title: "New" },
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
reconcilePreviewServerSessions(ref, {
|
||||
sessions: [restarted],
|
||||
serverEpoch: "server-b",
|
||||
revision: 0,
|
||||
});
|
||||
|
||||
const state = readThreadPreviewState(ref);
|
||||
expect(state.sessions[restarted.tabId]).toEqual(restarted);
|
||||
expect(state.suppressedTabIds).toEqual(new Set());
|
||||
expect(state.desktopByTabId).toEqual({});
|
||||
expect(state.desktopOverlay).toBeNull();
|
||||
});
|
||||
|
||||
it("applyServerSnapshot null clears snapshot for a thread that had one", () => {
|
||||
const snapshot = makeSnapshot();
|
||||
applyPreviewServerSnapshot(ref, snapshot);
|
||||
|
||||
@@ -323,10 +323,11 @@ export function reconcilePreviewServerSessions(
|
||||
if (sameServer && result.revision < current.serverRevision) return current;
|
||||
const snapshots = result.sessions;
|
||||
const sessions: Record<string, PreviewSessionSnapshot> = {};
|
||||
const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set<string>();
|
||||
let recentlySeenUrls = current.recentlySeenUrls;
|
||||
for (const snapshot of snapshots) {
|
||||
if (current.suppressedTabIds.has(snapshot.tabId)) continue;
|
||||
const existing = current.sessions[snapshot.tabId];
|
||||
if (currentSuppressedTabIds.has(snapshot.tabId)) continue;
|
||||
const existing = sameServer ? current.sessions[snapshot.tabId] : undefined;
|
||||
const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
|
||||
sessions[next.tabId] = next;
|
||||
recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
|
||||
@@ -338,11 +339,13 @@ export function reconcilePreviewServerSessions(
|
||||
? current.activeTabId
|
||||
: (fallback?.tabId ?? null);
|
||||
const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
|
||||
const desktopByTabId = Object.fromEntries(
|
||||
Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
|
||||
);
|
||||
const desktopByTabId = sameServer
|
||||
? Object.fromEntries(
|
||||
Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
|
||||
)
|
||||
: {};
|
||||
const suppressedTabIds = new Set(
|
||||
[...current.suppressedTabIds].filter((tabId) =>
|
||||
[...currentSuppressedTabIds].filter((tabId) =>
|
||||
snapshots.some((snapshot) => snapshot.tabId === tabId),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -52,6 +52,12 @@ function SettingsContentLayout() {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
|
||||
const activeElement = document.activeElement;
|
||||
if (activeElement instanceof HTMLElement) {
|
||||
activeElement.blur();
|
||||
}
|
||||
|
||||
navigateBackWithinApp();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveThreadDetailRef } from "./entities";
|
||||
|
||||
const threadRef = scopeThreadRef(EnvironmentId.make("environment-1"), ThreadId.make("thread-1"));
|
||||
|
||||
describe("resolveThreadDetailRef", () => {
|
||||
it("does not subscribe to a reserved draft thread before it enters the shell index", () => {
|
||||
expect(
|
||||
resolveThreadDetailRef(threadRef, {
|
||||
shellExists: false,
|
||||
waitForShell: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("subscribes once the reserved draft thread enters the shell index", () => {
|
||||
expect(
|
||||
resolveThreadDetailRef(threadRef, {
|
||||
shellExists: true,
|
||||
waitForShell: true,
|
||||
}),
|
||||
).toBe(threadRef);
|
||||
});
|
||||
|
||||
it("keeps direct server-thread lookups enabled when the shell has not loaded it", () => {
|
||||
expect(
|
||||
resolveThreadDetailRef(threadRef, {
|
||||
shellExists: false,
|
||||
waitForShell: false,
|
||||
}),
|
||||
).toBe(threadRef);
|
||||
});
|
||||
});
|
||||
@@ -152,10 +152,35 @@ export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadS
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveThreadDetailRef(
|
||||
ref: ScopedThreadRef | null,
|
||||
options: {
|
||||
shellExists: boolean;
|
||||
waitForShell: boolean;
|
||||
},
|
||||
): ScopedThreadRef | null {
|
||||
return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
|
||||
}
|
||||
|
||||
/** Detail collections composed with shell-authoritative thread/workspace metadata. */
|
||||
export function useThread(ref: ScopedThreadRef | null): EnvironmentThread | null {
|
||||
export function useThread(
|
||||
ref: ScopedThreadRef | null,
|
||||
options?: {
|
||||
/**
|
||||
* Client-reserved draft thread ids do not exist on the server until the
|
||||
* first send. Waiting for the shell index avoids polling the detail
|
||||
* endpoint for an intentionally missing thread during that window.
|
||||
*/
|
||||
waitForShell?: boolean;
|
||||
},
|
||||
): EnvironmentThread | null {
|
||||
const shell = useThreadShell(ref);
|
||||
const detail = useThreadDetail(ref);
|
||||
const detail = useThreadDetail(
|
||||
resolveThreadDetailRef(ref, {
|
||||
shellExists: shell !== null,
|
||||
waitForShell: options?.waitForShell === true,
|
||||
}),
|
||||
);
|
||||
return useMemo(() => mergeEnvironmentThread(detail, shell), [detail, shell]);
|
||||
}
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
];
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
export const DEFAULT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
|
||||
@@ -155,10 +155,10 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
};
|
||||
|
||||
/** Per-provider text generation model defaults. */
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
export const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
Record<ProviderDriverKind, string>
|
||||
> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
[CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",
|
||||
[CURSOR_DRIVER_KIND]: "composer-2",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
|
||||
@@ -136,6 +136,33 @@ describe("ServerSettings worktree defaults", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettings.sourceControlWritingStyle", () => {
|
||||
it("defaults all style settings for legacy configs", () => {
|
||||
const settings = decodeServerSettings({});
|
||||
|
||||
expect(settings.sourceControlWritingStyle).toEqual({
|
||||
mode: "repo_conventions",
|
||||
customInstructions: "",
|
||||
followChangeRequestTemplates: true,
|
||||
});
|
||||
expect(settings.sourceControlWriterModelSelection).toBeNull();
|
||||
});
|
||||
|
||||
it("trims partial style updates", () => {
|
||||
const patch = decodeServerSettingsPatch({
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom",
|
||||
customInstructions: " Prefer concise wording. ",
|
||||
},
|
||||
});
|
||||
|
||||
expect(patch.sourceControlWritingStyle).toEqual({
|
||||
mode: "custom",
|
||||
customInstructions: "Prefer concise wording.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettingsPatch.providerInstances", () => {
|
||||
it("treats providerInstances as an optional whole-map replacement", () => {
|
||||
const patch = decodeServerSettingsPatch({});
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
|
||||
import { DEFAULT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
|
||||
import { ModelSelection } from "./orchestration.ts";
|
||||
import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
@@ -395,6 +395,24 @@ export const ObservabilitySettings = Schema.Struct({
|
||||
});
|
||||
export type ObservabilitySettings = typeof ObservabilitySettings.Type;
|
||||
|
||||
export const SourceControlWritingStyleMode = Schema.Literals([
|
||||
"repo_conventions",
|
||||
"conventional_commits",
|
||||
"custom",
|
||||
]);
|
||||
export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
|
||||
|
||||
export const SourceControlWritingStyleSettings = Schema.Struct({
|
||||
mode: SourceControlWritingStyleMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
|
||||
),
|
||||
customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
followChangeRequestTemplates: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
),
|
||||
});
|
||||
export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
|
||||
|
||||
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
@@ -416,10 +434,16 @@ export const ServerSettings = Schema.Struct({
|
||||
Schema.withDecodingDefault(
|
||||
Effect.succeed({
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
model: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
}),
|
||||
),
|
||||
),
|
||||
sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed({})),
|
||||
),
|
||||
sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
|
||||
// Legacy single-instance-per-driver settings. Continues to be the source
|
||||
// of truth until `providerInstances` (below) lands per-driver migration
|
||||
@@ -545,6 +569,14 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
|
||||
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
sourceControlWritingStyle: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
mode: Schema.optionalKey(SourceControlWritingStyleMode),
|
||||
customInstructions: Schema.optionalKey(TrimmedString),
|
||||
followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
|
||||
observability: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
otlpTracesUrl: Schema.optionalKey(TrimmedString),
|
||||
|
||||
@@ -2,14 +2,17 @@ import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { createModelSelection } from "./model.ts";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
extractPersistedServerObservabilitySettings,
|
||||
isModelSelectionProviderEnabled,
|
||||
normalizePersistedServerSettingString,
|
||||
parsePersistedServerObservabilitySettings,
|
||||
resolveSourceControlWriterModelSelection,
|
||||
} from "./serverSettings.ts";
|
||||
|
||||
describe("serverSettings helpers", () => {
|
||||
@@ -161,6 +164,104 @@ describe("serverSettings helpers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces source control writer selection without retaining stale options", () => {
|
||||
const current = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
sourceControlWriterModelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
"gpt-5.4-mini",
|
||||
[{ id: "reasoningEffort", value: "high" }],
|
||||
),
|
||||
};
|
||||
|
||||
expect(
|
||||
applyServerSettingsPatch(current, {
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
}).sourceControlWriterModelSelection,
|
||||
).toEqual({
|
||||
instanceId: "opencode",
|
||||
model: "openai/gpt-5",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears source control writer selection with null", () => {
|
||||
const current = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
sourceControlWriterModelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
"gpt-5.4-mini",
|
||||
),
|
||||
};
|
||||
|
||||
expect(
|
||||
applyServerSettingsPatch(current, {
|
||||
sourceControlWriterModelSelection: null,
|
||||
}).sourceControlWriterModelSelection,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back from a disabled source control writer provider without clearing its selection", () => {
|
||||
const instanceId = ProviderInstanceId.make("codex_writer");
|
||||
const sourceControlWriterModelSelection = createModelSelection(instanceId, "gpt-5.4-mini");
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
};
|
||||
|
||||
expect(isModelSelectionProviderEnabled(settings, sourceControlWriterModelSelection)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(resolveSourceControlWriterModelSelection(settings)).toBe(
|
||||
settings.textGenerationModelSelection,
|
||||
);
|
||||
expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
|
||||
});
|
||||
|
||||
it("falls back from an unavailable source control writer provider", () => {
|
||||
const instanceId = ProviderInstanceId.make("missing_writer");
|
||||
const sourceControlWriterModelSelection = createModelSelection(instanceId, "missing-model");
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
};
|
||||
const unavailableProvider = {
|
||||
instanceId,
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-27T00:00:00.000Z",
|
||||
availability: "unavailable",
|
||||
unavailableReason: "This provider driver is not available in this build.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
expect(resolveSourceControlWriterModelSelection(settings, [unavailableProvider])).toBe(
|
||||
settings.textGenerationModelSelection,
|
||||
);
|
||||
expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
|
||||
});
|
||||
|
||||
it("replaces providerInstances maps so omitted instance fields are cleared", () => {
|
||||
const codexId = ProviderInstanceId.make("codex");
|
||||
const current = {
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
isProviderAvailable,
|
||||
type ModelSelection,
|
||||
type ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
ServerSettings,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { deepMerge } from "./Struct.ts";
|
||||
@@ -8,6 +16,47 @@ import { createModelSelection } from "./model.ts";
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
const getLegacyProviderSettings = (
|
||||
settings: ServerSettings,
|
||||
provider: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined =>
|
||||
(settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
|
||||
|
||||
export function isModelSelectionProviderEnabled(
|
||||
settings: ServerSettings,
|
||||
selection: ModelSelection,
|
||||
): boolean {
|
||||
const instanceConfig = settings.providerInstances[selection.instanceId];
|
||||
if (instanceConfig !== undefined) {
|
||||
return instanceConfig.enabled ?? true;
|
||||
}
|
||||
|
||||
return (
|
||||
isProviderDriverKind(selection.instanceId) &&
|
||||
getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveSourceControlWriterModelSelection(
|
||||
settings: ServerSettings,
|
||||
providers?: ReadonlyArray<ServerProvider>,
|
||||
): ModelSelection {
|
||||
const selection = settings.sourceControlWriterModelSelection;
|
||||
if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
|
||||
return settings.textGenerationModelSelection;
|
||||
}
|
||||
if (providers === undefined) {
|
||||
return selection;
|
||||
}
|
||||
|
||||
const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
|
||||
return provider?.enabled === true && isProviderAvailable(provider)
|
||||
? selection
|
||||
: settings.textGenerationModelSelection;
|
||||
}
|
||||
|
||||
export interface PersistedServerObservabilitySettings {
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
@@ -66,11 +115,6 @@ function mergeModelSelectionOptionsById(input: {
|
||||
return [...merged.entries()].map(([id, value]) => ({ id, value }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a server settings patch while treating textGenerationModelSelection as
|
||||
* replace-on-provider/model updates. This prevents stale nested options from
|
||||
* surviving a reset patch that intentionally omits options.
|
||||
*/
|
||||
export function applyServerSettingsPatch(
|
||||
current: ServerSettings,
|
||||
patch: ServerSettingsPatch,
|
||||
@@ -83,6 +127,9 @@ export function applyServerSettingsPatch(
|
||||
...(patch.providerInstances !== undefined
|
||||
? { providerInstances: patch.providerInstances }
|
||||
: {}),
|
||||
...(patch.sourceControlWriterModelSelection !== undefined
|
||||
? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
|
||||
: {}),
|
||||
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
|
||||
};
|
||||
if (!selectionPatch) {
|
||||
|
||||
Generated
+1059
-222
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user