From 0e19c103ef07b6a2c143839d2d2a9cf223915d1e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Jul 2026 19:57:22 +0200 Subject: [PATCH 01/19] Keep MCP credentials alive across provider turns (#4659) --- apps/server/src/mcp/McpHttpServer.test.ts | 1 - apps/server/src/mcp/McpHttpServer.ts | 10 ++- .../src/mcp/McpInvocationContext.test.ts | 1 - apps/server/src/mcp/McpInvocationContext.ts | 1 - .../server/src/mcp/McpSessionRegistry.test.ts | 45 +++++++++++- apps/server/src/mcp/McpSessionRegistry.ts | 72 ++++++++++++++----- .../src/mcp/PreviewAutomationBroker.test.ts | 1 - .../server/src/mcp/PreviewAutomationBroker.ts | 13 ++-- .../src/provider/Layers/ProviderService.ts | 6 ++ 9 files changed, 119 insertions(+), 31 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index ca3341be7f..e1cdf992f0 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -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, diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 6774731a73..3ead607489 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -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), diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index 39c6868904..569917325b 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -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* () { diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index b13bf2d312..49273485a4 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -16,7 +16,6 @@ export interface McpInvocationScope { readonly providerInstanceId: ProviderInstanceId; readonly capabilities: ReadonlySet; readonly issuedAt: number; - readonly expiresAt: number; } export class McpInvocationContext extends Context.Service< diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index a91d98febd..1d8aead99d 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -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(); + }), +); diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 67c4f2f0ff..f19a4f4e8c 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -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; + /** + * 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; readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect; readonly revokeThread: (threadId: ThreadId) => Effect.Effect; readonly revokeAll: Effect.Effect; @@ -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({ 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, timestamp: number) => { + const pruneDead = (records: ReadonlyMap, 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 => + activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void; + export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect => activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void; diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 5bd665e517..3bc0fd7130 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -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 => ({ diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index 5a95280303..3e9bfaac26 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -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 { const timeoutMs = input.timeoutMs ?? 15_000; const deferred = yield* Deferred.make(); - 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 } diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 2eaaeb8ce3..ecf26a914c 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -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, From f0121f31d0e7c069f4007480fc13907c28efd4d5 Mon Sep 17 00:00:00 2001 From: jan Date: Mon, 27 Jul 2026 19:59:21 +0200 Subject: [PATCH 02/19] fix: close actions dropdown when editing (#4660) --- .../src/components/ProjectScriptsControl.tsx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 79e43f4c04..3a4e59edbe 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -138,6 +138,10 @@ export default function ProjectScriptsControl({ }: ProjectScriptsControlProps) { const addScriptFormId = React.useId(); const [editingScriptId, setEditingScriptId] = useState(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({ Run {primaryScript.name} - + setActionsMenuOpen({ scripts: open, imports: false })} + > } > @@ -408,7 +417,11 @@ export default function ProjectScriptsControl({ ) : importableScripts.length > 0 ? ( - + setActionsMenuOpen({ scripts: false, imports: open })} + > }> From 32af2f002468c320d40ab730b575dea872f1d86d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Jul 2026 20:08:28 +0200 Subject: [PATCH 03/19] fix(preview): stabilize PiP viewport identity (#4661) Co-authored-by: codex --- apps/desktop/src/preview/Manager.test.ts | 16 +- apps/desktop/src/preview/Manager.ts | 10 +- apps/web/src/browser/ElectronBrowserHost.tsx | 11 +- apps/web/src/browser/HostedBrowserWebview.tsx | 78 +++-- apps/web/src/browser/browserRecording.test.ts | 43 +++ apps/web/src/browser/browserRecording.ts | 40 +++ .../src/browser/browserSurfaceStore.test.ts | 4 +- apps/web/src/browser/browserSurfaceStore.ts | 14 +- .../browser/browserViewportActions.test.ts | 28 ++ .../web/src/browser/browserViewportActions.ts | 62 ++-- .../src/browser/browserViewportLayout.test.ts | 16 + apps/web/src/browser/browserViewportLayout.ts | 27 ++ .../src/browser/desktopTabLifetime.test.ts | 35 +++ .../src/browser/previewRuntimeTabId.test.ts | 46 +++ apps/web/src/browser/previewRuntimeTabId.ts | 23 ++ .../preview/PreviewAutomationHosts.tsx | 288 +++++++++++++----- .../components/preview/PreviewView.test.tsx | 22 +- .../src/components/preview/PreviewView.tsx | 102 ++++--- .../preview/ThreadPreviewMiniPlayer.tsx | 6 +- .../previewAutomationOpenReadiness.test.ts | 18 ++ .../preview/previewAutomationOpenReadiness.ts | 23 +- .../previewNavigationReadiness.test.ts | 56 ++++ .../preview/previewNavigationReadiness.ts | 74 +++++ .../preview/previewViewportRollback.test.ts | 36 +++ .../preview/previewViewportRollback.ts | 18 ++ .../components/preview/usePreviewBridge.ts | 14 +- .../components/preview/usePreviewSession.ts | 8 +- apps/web/src/previewStateStore.test.ts | 42 +++ apps/web/src/previewStateStore.ts | 15 +- 29 files changed, 939 insertions(+), 236 deletions(-) create mode 100644 apps/web/src/browser/previewRuntimeTabId.test.ts create mode 100644 apps/web/src/browser/previewRuntimeTabId.ts create mode 100644 apps/web/src/components/preview/previewNavigationReadiness.test.ts create mode 100644 apps/web/src/components/preview/previewNavigationReadiness.ts create mode 100644 apps/web/src/components/preview/previewViewportRollback.test.ts create mode 100644 apps/web/src/components/preview/previewViewportRollback.ts diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index cae6c8940d..fa962f58ce 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -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]); }); }); @@ -1065,7 +1073,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, ); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index d8fa674916..4321cf9dcf 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -104,6 +104,7 @@ 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 +165,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, @@ -2074,7 +2075,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", diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx index 51fa73a721..fbf7c14b73 100644 --- a/apps/web/src/browser/ElectronBrowserHost.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.tsx @@ -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 (
- {sessions.map(({ threadRef, snapshot, zoomFactor }) => { + {sessions.map(({ threadRef, snapshot, runtimeTabId, zoomFactor }) => { const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url; return ( initialUrl ?? "about:blank"); const tabLeaseRef = useRef(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} >
{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={ diff --git a/apps/web/src/browser/browserRecording.test.ts b/apps/web/src/browser/browserRecording.test.ts index c7208055da..b5ef77dd2d 100644 --- a/apps/web/src/browser/browserRecording.test.ts +++ b/apps/web/src/browser/browserRecording.test.ts @@ -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) => { diff --git a/apps/web/src/browser/browserRecording.ts b/apps/web/src/browser/browserRecording.ts index 5b88dfd413..69297cfdbb 100644 --- a/apps/web/src/browser/browserRecording.ts +++ b/apps/web/src/browser/browserRecording.ts @@ -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; } @@ -131,6 +139,28 @@ export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): R return tabIds; } +export function readActiveBrowserRecordingTargets( + threadRef: ScopedThreadRef, +): ReadonlyArray { + 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 { 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, diff --git a/apps/web/src/browser/browserSurfaceStore.test.ts b/apps/web/src/browser/browserSurfaceStore.test.ts index 0379f1382e..12b34dd4b5 100644 --- a/apps/web/src/browser/browserSurfaceStore.test.ts +++ b/apps/web/src/browser/browserSurfaceStore.test.ts @@ -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", () => { diff --git a/apps/web/src/browser/browserSurfaceStore.ts b/apps/web/src/browser/browserSurfaceStore.ts index c9b7cae544..43ae0037c0 100644 --- a/apps/web/src/browser/browserSurfaceStore.ts +++ b/apps/web/src/browser/browserSurfaceStore.ts @@ -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 => diff --git a/apps/web/src/browser/browserViewportActions.test.ts b/apps/web/src/browser/browserViewportActions.test.ts index fd8f7809f3..a7633fd096 100644 --- a/apps/web/src/browser/browserViewportActions.test.ts +++ b/apps/web/src/browser/browserViewportActions.test.ts @@ -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((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 { diff --git a/apps/web/src/browser/browserViewportActions.ts b/apps/web/src/browser/browserViewportActions.ts index eea176ebbf..b80f68af3f 100644 --- a/apps/web/src/browser/browserViewportActions.ts +++ b/apps/web/src/browser/browserViewportActions.ts @@ -15,6 +15,41 @@ export class BrowserViewportCommitTimeoutError extends Error { const handlers = new Map(); const commitTails = new Map>(); +const queueBrowserViewportMutation = ( + tabId: string, + start: () => Promise, +): { + readonly started: Promise<{ readonly operation: Promise }>; + readonly execution: Promise; +} => { + 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( + tabId: string, + mutation: () => Promise, +): Promise { + return queueBrowserViewportMutation(tabId, mutation).execution; +} + const runHandlerWithTimeout = (tabId: string, operation: Promise): Promise => { let timeoutId: ReturnType | undefined; const timeout = new Promise((_resolve, reject) => { @@ -42,25 +77,14 @@ export function commitBrowserViewportChange( tabId: string, setting: PreviewViewportSetting, ): Promise { - 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; } diff --git a/apps/web/src/browser/browserViewportLayout.test.ts b/apps/web/src/browser/browserViewportLayout.test.ts index edd432a4e9..23c8a2996c 100644 --- a/apps/web/src/browser/browserViewportLayout.test.ts +++ b/apps/web/src/browser/browserViewportLayout.test.ts @@ -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, diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index ed5529fe13..414701a816 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -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 { + 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; diff --git a/apps/web/src/browser/desktopTabLifetime.test.ts b/apps/web/src/browser/desktopTabLifetime.test.ts index 8f7b2ca7d6..feb015c91a 100644 --- a/apps/web/src/browser/desktopTabLifetime.test.ts +++ b/apps/web/src/browser/desktopTabLifetime.test.ts @@ -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; diff --git a/apps/web/src/browser/previewRuntimeTabId.test.ts b/apps/web/src/browser/previewRuntimeTabId.test.ts new file mode 100644 index 0000000000..7518ede3e5 --- /dev/null +++ b/apps/web/src/browser/previewRuntimeTabId.test.ts @@ -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); + }); +}); diff --git a/apps/web/src/browser/previewRuntimeTabId.ts b/apps/web/src/browser/previewRuntimeTabId.ts new file mode 100644 index 0000000000..64dc4f9839 --- /dev/null +++ b/apps/web/src/browser/previewRuntimeTabId.ts @@ -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; +} diff --git a/apps/web/src/components/preview/PreviewAutomationHosts.tsx b/apps/web/src/components/preview/PreviewAutomationHosts.tsx index 165fb6136a..2a007fb4ce 100644 --- a/apps/web/src/components/preview/PreviewAutomationHosts.tsx +++ b/apps/web/src/components/preview/PreviewAutomationHosts.tsx @@ -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 { @@ -65,18 +71,34 @@ import { resolvePreviewAutomationTarget, } from "./previewAutomationTarget"; import { isPreviewViewportReady } from "./previewViewportReadiness"; +import { shouldRollbackPreviewViewport } from "./previewViewportRollback"; + +const PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS = 500; + +const waitForPreviewPresentation = async (runtimeTabId: string): Promise => { + const deadline = Date.now() + PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS; + while (Date.now() <= deadline) { + if (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible) return; + await new Promise((resolve) => window.setTimeout(resolve, 16)); + } +}; const waitForDesktopOverlay = async ( threadRef: ScopedThreadRef, requestId: string, tabId: string, + runtimeTabId: string, + operation: PreviewAutomationRequest["operation"], timeoutMs: number, ): Promise => { const deadline = Date.now() + timeoutMs; 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((resolve) => window.setTimeout(resolve, 50)); @@ -89,38 +111,6 @@ const waitForDesktopOverlay = async ( }); }; -const waitForNavigationReadiness = async ( - threadRef: ScopedThreadRef, - requestId: string, - tabId: string, - readiness: PreviewAutomationNavigateInput["readiness"], - timeoutMs: number, -): Promise => { - 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((resolve) => window.setTimeout(resolve, 50)); - } - throw new PreviewAutomationNavigationTimeoutError({ - requestId, - environmentId: threadRef.environmentId, - threadId: threadRef.threadId, - tabId, - readiness: targetReadiness, - timeoutMs, - }); -}; - interface ExecutablePreviewWebview extends Element { readonly executeJavaScript: (code: string, userGesture?: boolean) => Promise; } @@ -148,8 +138,10 @@ const readWebviewViewport = async ( : null; }; -const readRenderedViewport = async (tabId: string): Promise => { - const webview = findPreviewWebview(tabId); +const readRenderedViewport = async ( + runtimeTabId: string, +): Promise => { + const webview = findPreviewWebview(runtimeTabId); if (!webview) return null; return await readWebviewViewport(webview); }; @@ -165,19 +157,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 => { 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 +207,19 @@ const currentStatus = async ( ): Promise => { 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 +337,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 +391,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 +437,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 +474,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 +490,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 +569,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 +577,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[1], ); } case "type": { const ready = await requireReadyTab(); return await ready.bridge.automation.type( - ready.tabId, + ready.runtimeTabId, request.input as Parameters[1], ); } case "press": { const ready = await requireReadyTab(); return await ready.bridge.automation.press( - ready.tabId, + ready.runtimeTabId, request.input as Parameters[1], ); } case "scroll": { const ready = await requireReadyTab(); return await ready.bridge.automation.scroll( - ready.tabId, + ready.runtimeTabId, request.input as Parameters[1], ); } case "evaluate": { const ready = await requireReadyTab(); return await ready.bridge.automation.evaluate( - ready.tabId, + ready.runtimeTabId, request.input as Parameters[1], ); } case "waitFor": { const ready = await requireReadyTab(); return await ready.bridge.automation.waitFor( - ready.tabId, + ready.runtimeTabId, request.input as Parameters[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 +635,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 +659,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId }) }), ); } - return artifact; + return { ...artifact, tabId: stopTabId }; } } } catch (cause) { diff --git a/apps/web/src/components/preview/PreviewView.test.tsx b/apps/web/src/components/preview/PreviewView.test.tsx index 2532b8c89e..576c37d77b 100644 --- a/apps/web/src/components/preview/PreviewView.test.tsx +++ b/apps/web/src/components/preview/PreviewView.test.tsx @@ -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(); 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(); mocks.toggleNativePictureInPicture?.(); - await vi.waitFor(() => expect(mocks.closePictureInPicture).toHaveBeenCalledWith("tab-1")); + await vi.waitFor(() => + expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID), + ); }); }); diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index db72111d1c..a3e23c2c41 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -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 ? (
- {tabId && snapshot && !showEmptyState ? ( + {runtimeTabId && snapshot && !showEmptyState ? ( @@ -664,9 +674,9 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls, {snapshot && desktopOverlay ? ( ) : null} - {tabId && desktopOverlay && !showEmptyState && !isUnreachable ? ( + {runtimeTabId && desktopOverlay && !showEmptyState && !isUnreachable ? ( diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 3f1b5dbf4b..3e7c46ef0e 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -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
{ ), ).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(); + }); }); diff --git a/apps/web/src/components/preview/previewAutomationOpenReadiness.ts b/apps/web/src/components/preview/previewAutomationOpenReadiness.ts index 1f78c22621..c9d29fd44e 100644 --- a/apps/web/src/components/preview/previewAutomationOpenReadiness.ts +++ b/apps/web/src/components/preview/previewAutomationOpenReadiness.ts @@ -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; +} diff --git a/apps/web/src/components/preview/previewNavigationReadiness.test.ts b/apps/web/src/components/preview/previewNavigationReadiness.test.ts new file mode 100644 index 0000000000..cefff71841 --- /dev/null +++ b/apps/web/src/components/preview/previewNavigationReadiness.test.ts @@ -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); + }); +}); diff --git a/apps/web/src/components/preview/previewNavigationReadiness.ts b/apps/web/src/components/preview/previewNavigationReadiness.ts new file mode 100644 index 0000000000..dd5e7247b7 --- /dev/null +++ b/apps/web/src/components/preview/previewNavigationReadiness.ts @@ -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, +) { + 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 { + 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((resolve) => window.setTimeout(resolve, 50)); + } + throw new PreviewAutomationNavigationTimeoutError({ + requestId, + environmentId: threadRef.environmentId, + threadId: threadRef.threadId, + tabId, + readiness: targetReadiness, + timeoutMs, + }); +} diff --git a/apps/web/src/components/preview/previewViewportRollback.test.ts b/apps/web/src/components/preview/previewViewportRollback.test.ts new file mode 100644 index 0000000000..287e2d87ce --- /dev/null +++ b/apps/web/src/components/preview/previewViewportRollback.test.ts @@ -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); + }); +}); diff --git a/apps/web/src/components/preview/previewViewportRollback.ts b/apps/web/src/components/preview/previewViewportRollback.ts new file mode 100644 index 0000000000..c36bf52fd0 --- /dev/null +++ b/apps/web/src/components/preview/previewViewportRollback.ts @@ -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 + ); +} diff --git a/apps/web/src/components/preview/usePreviewBridge.ts b/apps/web/src/components/preview/usePreviewBridge.ts index 4e7fccd3f2..259748c41d 100644 --- a/apps/web/src/components/preview/usePreviewBridge.ts +++ b/apps/web/src/components/preview/usePreviewBridge.ts @@ -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( diff --git a/apps/web/src/components/preview/usePreviewSession.ts b/apps/web/src/components/preview/usePreviewSession.ts index b2865c4eac..7f1a997f2c 100644 --- a/apps/web/src/components/preview/usePreviewSession.ts +++ b/apps/web/src/components/preview/usePreviewSession.ts @@ -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) => { @@ -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}`)); diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts index a4d709e2f2..50bda95c91 100644 --- a/apps/web/src/previewStateStore.test.ts +++ b/apps/web/src/previewStateStore.test.ts @@ -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); diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts index 02b66922a4..f3dced0a75 100644 --- a/apps/web/src/previewStateStore.ts +++ b/apps/web/src/previewStateStore.ts @@ -323,10 +323,11 @@ export function reconcilePreviewServerSessions( if (sameServer && result.revision < current.serverRevision) return current; const snapshots = result.sessions; const sessions: Record = {}; + const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set(); 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), ), ); From 80ead5f3a7743010cdab6ad84fa4dcbd4c021038 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Jul 2026 20:28:01 +0200 Subject: [PATCH 04/19] Add glass styling for thread tooltips and simplify preview tab handling (#4665) --- apps/web/src/components/SidebarV2.tsx | 7 ++----- apps/web/src/components/ui/tooltip.tsx | 7 ++++++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index a5f9eca5f4..8677ee1149 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -239,11 +239,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" >
{thread.title}
diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 442c394ec2..23c4a370ef 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -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({ > Date: Mon, 27 Jul 2026 21:15:40 +0200 Subject: [PATCH 05/19] Use tarball archiving for hosted web deploys (#4669) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 668d1fcb59..f6e876bde5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -864,6 +864,7 @@ jobs: echo "Deploying hosted web app for $channel_name channel." deployment_url="$( vp dlx vercel@53.1.1 deploy \ + --archive=tgz \ --prod \ --skip-domain \ --yes \ From 6e3b73884bf40eeb2859cb16f1200c8e2f9cf7c3 Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 27 Jul 2026 15:18:55 -0400 Subject: [PATCH 06/19] fix(server): bound editor discovery during config loading (#4291) --- apps/server/src/server.test.ts | 18 ++++++++++++++++++ apps/server/src/ws.ts | 13 ++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 4a9e730621..a3b2e3715f 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -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(); + 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", () => diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b8f4b07124..2a8be25a72 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -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 = ( + discovery: Effect.Effect, 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, From e77f42c111dc40e0b208393957ebb23863330e2e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Jul 2026 21:52:11 +0200 Subject: [PATCH 07/19] Prevent draft thread detail polling before shell registration (#4670) Co-authored-by: codex --- apps/web/src/components/BranchToolbar.tsx | 2 +- .../BranchToolbarBranchSelector.tsx | 4 +-- apps/web/src/components/ChatView.tsx | 20 +++++------ apps/web/src/components/GitActionsControl.tsx | 4 ++- apps/web/src/state/entities.test.ts | 36 +++++++++++++++++++ apps/web/src/state/entities.ts | 29 +++++++++++++-- 6 files changed, 79 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/state/entities.test.ts diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 2a1d0d1ec0..3a83f5c9a0 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -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) diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index a61427f207..74138fa529 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -129,11 +129,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 diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b234d0765f..bdde62a3e0 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -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([]); const composerTerminalContextsRef = useRef([]); diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 11716e935a..4f2bd19952 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -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(""); diff --git a/apps/web/src/state/entities.test.ts b/apps/web/src/state/entities.test.ts new file mode 100644 index 0000000000..0d7611ec41 --- /dev/null +++ b/apps/web/src/state/entities.test.ts @@ -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); + }); +}); diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 9bd20070c2..552468e04d 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -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]); } From 10bca3f44e1be6a874438fe80badbad45cd00279 Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 27 Jul 2026 16:02:15 -0400 Subject: [PATCH 08/19] feat: add configurable source control writing settings (#4204) Co-authored-by: Claude Co-authored-by: Julius Marminge Co-authored-by: codex --- apps/server/src/git/GitManager.test.ts | 207 ++++++++++++--- apps/server/src/git/GitManager.ts | 111 +++++++- .../Layers/ProviderCommandReactor.ts | 15 +- apps/server/src/serverSettings.test.ts | 67 +++++ apps/server/src/serverSettings.ts | 51 ++-- .../sourceControl/PrTemplateDetection.test.ts | 248 ++++++++++++++++++ .../src/sourceControl/PrTemplateDetection.ts | 177 +++++++++++++ .../textGeneration/ClaudeTextGeneration.ts | 3 + .../src/textGeneration/CodexTextGeneration.ts | 3 + .../textGeneration/CursorTextGeneration.ts | 3 + .../src/textGeneration/GrokTextGeneration.ts | 3 + .../textGeneration/OpenCodeTextGeneration.ts | 3 + .../src/textGeneration/TextGeneration.ts | 8 +- .../TextGenerationPrompts.test.ts | 41 +++ .../textGeneration/TextGenerationPrompts.ts | 29 +- .../components/chat/ProviderModelPicker.tsx | 2 + .../components/settings/SettingsPanels.tsx | 22 +- .../settings/SourceControlSettings.tsx | 5 +- .../settings/SourceControlWritingSettings.tsx | 213 +++++++++++++++ apps/web/src/hooks/useSettings.ts | 6 +- apps/web/src/modelSelection.ts | 8 +- apps/web/src/routes/settings.tsx | 6 + packages/contracts/src/model.ts | 6 +- packages/contracts/src/settings.test.ts | 27 ++ packages/contracts/src/settings.ts | 36 ++- packages/shared/src/serverSettings.test.ts | 101 +++++++ packages/shared/src/serverSettings.ts | 59 ++++- 27 files changed, 1335 insertions(+), 125 deletions(-) create mode 100644 apps/server/src/sourceControl/PrTemplateDetection.test.ts create mode 100644 apps/server/src/sourceControl/PrTemplateDetection.ts create mode 100644 apps/web/src/components/settings/SourceControlWritingSettings.tsx diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 256f10fb3b..695c7b76f6 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -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; @@ -640,6 +615,7 @@ function preparePullRequestThread( function makeManager(input?: { ghScenario?: FakeGhScenario; textGeneration?: Partial; + serverSettings?: Parameters[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", "test@example.com"]); + 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")), diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 86e10d9f93..95e5affc21 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -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 }; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index b6bff8c766..3044cc6029 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -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, diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 487ae9b45b..50ca810a95 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -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; diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 4119a72640..82fd2f29f0 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -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 = {}) => 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 = {}) => 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)[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 = new Set([ "automaticGitFetchInterval", + "sourceControlWriterModelSelection", "textGenerationModelSelection", ]); diff --git a/apps/server/src/sourceControl/PrTemplateDetection.test.ts b/apps/server/src/sourceControl/PrTemplateDetection.test.ts new file mode 100644 index 0000000000..34112c9c52 --- /dev/null +++ b/apps/server/src/sourceControl/PrTemplateDetection.test.ts @@ -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) => + Effect.gen(function* () { + const git = yield* GitVcsDriver.GitVcsDriver; + return yield* git.execute({ + operation: "PrTemplateDetection.test.runGit", + cwd, + args, + }); + }); + +const runWithTempDirectory = ( + test: (cwd: string) => Effect.Effect, +) => + 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", "test@example.com"]); + 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"); + }), + ), +); diff --git a/apps/server/src/sourceControl/PrTemplateDetection.ts b/apps/server/src/sourceControl/PrTemplateDetection.ts new file mode 100644 index 0000000000..6872708fec --- /dev/null +++ b/apps/server/src/sourceControl/PrTemplateDetection.ts @@ -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 { + 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, 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; + readonly directory: string; +}): Effect.Effect { + 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())); +}); diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 453bb62b72..a27b2c8bd3 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -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({ diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 6a5c0df43c..6ea710cd5a 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -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({ diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts index 6d1e5d02db..be0fc858ac 100644 --- a/apps/server/src/textGeneration/CursorTextGeneration.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.ts @@ -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({ diff --git a/apps/server/src/textGeneration/GrokTextGeneration.ts b/apps/server/src/textGeneration/GrokTextGeneration.ts index fd367acdf4..d26a2ebe01 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.ts @@ -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({ diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts index 1f94f97069..2adbb829b8 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts @@ -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", diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index e62a79afe7..ead0963877 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -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; /** - * Generate pull request title/body from branch and diff context. + * Generate change request title/body from branch and diff context. */ readonly generatePrContent: ( input: PrContentGenerationInput, diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts index b67e8b93c4..65b61b99bf 100644 --- a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts +++ b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts @@ -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: "\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("\n## What changed\n\n## Verification"); + expect(result.prompt).not.toContain("include headings '## Summary' and '## Testing'"); }); }); diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.ts b/apps/server/src/textGeneration/TextGenerationPrompts.ts index 6015e83b5d..efa251963a 100644 --- a/apps/server/src/textGeneration/TextGenerationPrompts.ts +++ b/apps/server/src/textGeneration/TextGenerationPrompts.ts @@ -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}`, diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 74c92a044b..4e3fa7abcd 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -39,6 +39,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { open?: boolean; triggerVariant?: VariantProps["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: { 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() { @@ -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) => { diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index e0387f1973..764f682fbc 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -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({ {item.label} is not authenticated on this server. Sign in or configure credentials using the {item.executable}{" "} - tool on the server host to enable pull request features. + tool on the server host to enable change request features. ); } @@ -513,6 +514,8 @@ export function SourceControlSettingsPanel() { onScan={handleScan} /> )} + + {environmentId !== null ? : null} ); } diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.tsx new file mode 100644 index 0000000000..d7c094af37 --- /dev/null +++ b/apps/web/src/components/settings/SourceControlWritingSettings.tsx @@ -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 = + { + 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(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 ( + + + updateSettings({ + sourceControlWritingStyle: { + mode: defaults.mode, + customInstructions: defaults.customInstructions, + }, + }) + } + /> + ) : null + } + control={ + + } + > + {style.mode === "custom" ? ( +
+