From c69f4b780bdb3fd7b3d6a06f41b7017f77298c5e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:07:30 -0800 Subject: [PATCH 001/280] fix(web): model picker lists a model reported twice once (#31590) --- .../components/chat/ModelPickerContent.tsx | 4 ++ .../chat/ProviderModelPicker.browser.test.tsx | 68 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e9a884fde6a1..87bacfd7ca2a 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -548,13 +548,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const flatModels = (() => { const out: ModelPickerItem[] = []; + const seenKeys = new Set(); for (const [instanceId, models] of modelOptionsByInstance) { const entry = entryByInstanceId.get(instanceId); if (!entry) { continue; } for (const model of models) { + const key = modelPickerModelKey(instanceId, model.slug); if ( + seenKeys.has(key) || !shouldIncludeModelPickerOption({ entry, option: model, @@ -564,6 +567,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) { continue; } + seenKeys.add(key); out.push({ slug: model.slug, name: model.name, diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index bf196f52542c..06bb36a34c07 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -4,6 +4,7 @@ import { ProviderInstanceId, type ModelSelection, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -176,6 +177,73 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(search).not.toBeInTheDocument(); }); +it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => { + const instanceId = ProviderInstanceId.make("claude"); + const entries = deriveProviderInstanceEntries([ + { + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }, + ]); + const options = new Map([ + [ + instanceId, + ["a", "b", "c", "c", "d", "d"].map((slug) => ({ + slug, + name: `Model ${slug.toUpperCase()}`, + })), + ], + ]); + const keybindings = compileResolvedKeybindingsConfig( + ([1, 2, 3, 4, 5, 6] as const).map((index) => ({ + key: `mod+${index}`, + command: `modelPicker.jump.${index}` as const, + when: "modelPickerOpen", + })), + ); + + await using screen = await render( + {}} + />, + ); + await screen.getByRole("button", { name: "Choose model" }).click(); + await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible(); + await vi.waitFor(() => + expect( + page + .getByRole("option") + .elements() + .map((row) => [ + row.textContent?.match(/Model [A-Z]/)?.[0], + row.querySelector("kbd")?.textContent?.slice(-1), + ]), + ).toEqual([ + ["Model A", "1"], + ["Model B", "2"], + ["Model C", "3"], + ["Model D", "4"], + ]), + ); +}); + it("opens on the active provider when every favorite belongs to a disabled provider", async () => { const entries = deriveProviderInstanceEntries( ["Codex", "Claude"].map((name) => ({ From ca432d7ed645a8ebd032456b7bac95c0a0590ced Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:11:10 -0800 Subject: [PATCH 002/280] fix(server): log the connections the private-network gate closes (#31647) --- apps/server/src/server.ts | 9 ++--- apps/server/src/startupAccess.test.ts | 55 +++++++++++++++++++++++++++ apps/server/src/startupAccess.ts | 41 ++++++++++++++++++++ 3 files changed, 99 insertions(+), 6 deletions(-) diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47c4a4c9a20e..01b659b0944a 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -219,7 +219,7 @@ import * as RunFinalizationService from "./orchestration-v2/RunFinalizationServi import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts"; import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts"; -import { acceptsPrivateNetworkConnection, loopbackUrlHostForAddress } from "./startupAccess.ts"; +import { closeNonPrivateNetworkConnections, loopbackUrlHostForAddress } from "./startupAccess.ts"; import * as OrchestrationHttp from "./orchestration-v2/http.ts"; import * as ProjectHttp from "./project/http.ts"; import * as NetService from "@t3tools/shared/Net"; @@ -364,17 +364,14 @@ const layerHttpServer = Layer.unwrap( privateNetworkOnly: config.privateNetworkOnly, }); yield* ManagedLimits.closeTailscaleServeTo(policy, { host: bindHost, port: config.port }); + const runSync = Effect.runSyncWith(yield* Effect.context()); return NodeHttpServer.layer( () => { const server = rejectRequestsUntilServing( keepIdleConnections(guardHttpResponseWriteErrors(NodeHttp.createServer())), ); if (config.privateNetworkOnly) { - server.on("connection", (socket) => { - if (!acceptsPrivateNetworkConnection(socket)) { - socket.destroy(); - } - }); + runSync(closeNonPrivateNetworkConnections(server)); } return server; }, diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 159778b3c7e0..7290d6063db9 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -1,10 +1,17 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeHttp from "node:http"; +import * as NodeNet from "node:net"; import type * as NodeOS from "node:os"; import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Logger from "effect/Logger"; import * as NetAddress from "effect/net/NetAddress"; +import * as TestClock from "effect/testing/TestClock"; import { acceptsPrivateNetworkConnection, + closeNonPrivateNetworkConnections, loopbackUrlHostForAddress, resolveHeadlessConnectionString, } from "./startupAccess.ts"; @@ -104,3 +111,51 @@ describe("acceptsPrivateNetworkConnection", () => { expect(accepts(undefined, "192.168.1.31")).toBe(false); }); }); + +describe("closeNonPrivateNetworkConnections", () => { + it.effect("logs the local and remote address of a connection it closes", () => + Effect.gen(function* () { + const warnings: Array> = []; + const server = NodeHttp.createServer(); + yield* closeNonPrivateNetworkConnections(server).pipe( + Effect.provide( + Logger.layer([Logger.make((entry) => warnings.push(entry))], { + mergeWithExisting: false, + }), + ), + ); + + // An unconnected socket: Node reports neither address. + const socket = new NodeNet.Socket(); + server.emit("connection", socket); + + expect(socket.destroyed).toBe(true); + expect(warnings.map((entry) => entry.logLevel)).toEqual(["Warn"]); + const line = Logger.formatLogFmt.log(warnings[0]!); + expect(line).toMatch(/localAddress\W+undefined/); + expect(line).toMatch(/remoteAddress\W+undefined/); + }), + ); + + it.effect("logs a flood of closed connections at most once a minute, with a count", () => + Effect.gen(function* () { + const warnings: Array> = []; + const server = NodeHttp.createServer(); + yield* closeNonPrivateNetworkConnections(server).pipe( + Effect.provide( + Logger.layer([Logger.make((entry) => warnings.push(entry))], { + mergeWithExisting: false, + }), + ), + ); + const sockets = Array.from({ length: 1000 }, () => new NodeNet.Socket()); + for (const socket of sockets) server.emit("connection", socket); + yield* TestClock.adjust("1 minute"); + server.emit("connection", new NodeNet.Socket()); + + expect(sockets.every((socket) => socket.destroyed)).toBe(true); + expect(warnings).toHaveLength(2); + expect(Logger.formatLogFmt.log(warnings[1]!)).toMatch(/closedSinceLastLog\W+999/); + }), + ); +}); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index 1720300bd7be..ee372a1ab151 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - The private-network gate guards the node:http server. +import type * as NodeHttp from "node:http"; import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; @@ -10,6 +12,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { QrCode } from "@t3tools/shared/qrCode"; import { buildPairingAppLink } from "@t3tools/shared/remote"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; import * as NetAddress from "effect/net/NetAddress"; @@ -81,6 +84,44 @@ export const acceptsPrivateNetworkConnection = (socket: { (address) => address !== undefined && isPrivateNetworkAddress(address), ); +const CLOSED_CONNECTION_LOG_INTERVAL_NANOS = 60_000_000_000n; + +/** + * Closing is silent to the client, so closed connections are logged with both + * addresses: the first at once, then at most one line a minute with a count, so + * a connect flood from outside cannot grow the service log without bound. + */ +// Untraced: the captured context would otherwise tie every later warning to a span that ended at startup. +export const closeNonPrivateNetworkConnections = Effect.fnUntraced(function* ( + server: NodeHttp.Server, +) { + const runSync = Effect.runSyncWith(yield* Effect.context()); + let nextLogAt: bigint | undefined; + let closedSinceLastLog = 0; + server.on("connection", (socket) => { + if (acceptsPrivateNetworkConnection(socket)) return; + // Read before destroy: Node forgets localAddress once the handle closes. + const addresses = { localAddress: socket.localAddress, remoteAddress: socket.remoteAddress }; + socket.destroy(); + runSync( + Effect.gen(function* () { + // Monotonic: a wall clock set backwards must not silence the warnings. + const now = yield* Clock.monotonicTimeNanos; + if (nextLogAt !== undefined && now < nextLogAt) { + closedSinceLastLog += 1; + return; + } + nextLogAt = now + CLOSED_CONNECTION_LOG_INTERVAL_NANOS; + yield* Effect.logWarning("closed a connection outside the private network", { + ...addresses, + ...(closedSinceLastLog > 0 ? { closedSinceLastLog } : {}), + }); + closedSinceLastLog = 0; + }), + ); + }); +}); + export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string => NetAddress.isUnspecified(address.address) ? "127.0.0.1" From 991c62d0d7cf2b29beca05e2fe56eb3227af4fae Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 16 Nov 2026 15:14:26 -0600 Subject: [PATCH 003/280] fix(web): project picker rows no longer jump when the palette opens (#37764) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../hooks/useLegendListRef.browser.test.tsx | 26 ++++- patches/@legendapp__list@3.7.2.patch | 106 ++++++++++++++++++ pnpm-lock.yaml | 8 +- 3 files changed, 135 insertions(+), 5 deletions(-) diff --git a/apps/web/src/hooks/useLegendListRef.browser.test.tsx b/apps/web/src/hooks/useLegendListRef.browser.test.tsx index 22e258f30a06..d74ac578b8b0 100644 --- a/apps/web/src/hooks/useLegendListRef.browser.test.tsx +++ b/apps/web/src/hooks/useLegendListRef.browser.test.tsx @@ -1,6 +1,6 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { createRef, useState, type RefObject } from "react"; -import { expect, it } from "vite-plus/test"; +import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../test/render"; import { useLegendListRef } from "./useLegendListRef"; @@ -30,6 +30,30 @@ function ListProbe({ ); } +it("keeps rows at their layout height when they re-render while an ancestor is scaled", async () => { + const items = Array.from({ length: 6 }, (_, index) => `Row ${index}`); + // Dialogs and popovers scale in from 0.98; a re-render mid-animation must not record scaled sizes. + const list = (highlighted: string) => ( +
+ item} + renderItem={({ item }) =>
{item}
} + style={{ height: 300, width: 300 }} + /> +
+ ); + await using screen = await render(list("Row 0")); + await expect.element(screen.getByText("Row 5")).toBeVisible(); + await screen.rerender(list("Row 1")); + await vi.waitFor(() => { + const first = screen.getByText("Row 0").element().getBoundingClientRect(); + const last = screen.getByText("Row 5").element().getBoundingClientRect(); + expect((last.top - first.top) / 0.98).toBeCloseTo(200, 0); + }); +}); + it("refreshes list edges after content shrinks without scrolling and after the list reopens", async () => { const listRef = createRef(); const items = Array.from({ length: 20 }, (_, index) => `Row ${index}`); diff --git a/patches/@legendapp__list@3.7.2.patch b/patches/@legendapp__list@3.7.2.patch index beafc1c4a6fc..a9a1d31a3982 100644 --- a/patches/@legendapp__list@3.7.2.patch +++ b/patches/@legendapp__list@3.7.2.patch @@ -102,3 +102,109 @@ index 9ebfddc183a9b202d35c990a387c9b628feeb185..489050190144997ac72de8f4f7c62194 const ownsMeasuredItem = measurement.containerId === void 0 || isContainerItemCurrent(ctx, measurement.containerId, measurement.itemKey); if (ownsMeasuredItem) { const index = state.indexByKey.get(measurement.itemKey); +diff --git a/react.js b/react.js +index 515545471e08426fc90856256db9491db0ca4b92..b741735df1fbc0c954ed48f15590abce727d5336 100644 +--- a/react.js ++++ b/react.js +@@ -5635,6 +5635,19 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif + } + + // src/core/measureContainersInLayoutEffect.ts ++// T3 patch: measure rows by their layout box, as ResizeObserver does. getBoundingClientRect ++// includes ancestor transforms, so rows that mount while a dialog scales in measure short and ++// stay packed too tightly until they re-render. ++function measureContainerLayoutSize(element) { ++ const rect = element.getBoundingClientRect(); ++ if (Math.abs(rect.width - element.offsetWidth) < 1 && Math.abs(rect.height - element.offsetHeight) < 1) { ++ return { height: rect.height, width: rect.width }; ++ } ++ const style = getComputedStyle(element); ++ const height = Number.parseFloat(style.height); ++ const width = Number.parseFloat(style.width); ++ return Number.isFinite(height) && Number.isFinite(width) ? { height, width } : { height: rect.height, width: rect.width }; ++} + function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { + var _a3, _b, _c; + const dataChangeEpoch = ctx.state.dataChangeEpoch; +@@ -5646,13 +5659,13 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { + const element = viewRef == null ? void 0 : viewRef.current; + if (itemKey !== void 0 && element && isContainerItemCurrent(ctx, containerId, itemKey)) { + const generation = (_b = ctx.state.containerItemGenerations[containerId]) != null ? _b : 0; +- const rect = element.getBoundingClientRect(); +- setContainerLayoutBaseline(element, rect); ++ const size = measureContainerLayoutSize(element); ++ setContainerLayoutBaseline(element, size); + measurements.push({ + containerId, + generation, + itemKey, +- size: { height: rect.height, width: rect.width } ++ size + }); + } + } +@@ -6296,9 +6309,8 @@ function processContainerLayout({ containerId, ctx, rectangle, ref, state }) { + var _a4; + if (state.itemKey === currentItemKey) { + const element = ref.current; +- const rect = (_a4 = element == null ? void 0 : element.getBoundingClientRect) == null ? void 0 : _a4.call(element); +- if (rect) { +- layout = { height: rect.height, width: rect.width }; ++ if (element) { ++ layout = measureContainerLayoutSize(element); + } + applyLayout(); + } +diff --git a/react.mjs b/react.mjs +index ce08abe7ee62e8940f9c6ff169829244bd6bb736..fce79caef8387e517cbab8051b213cb57b1df590 100644 +--- a/react.mjs ++++ b/react.mjs +@@ -5614,6 +5614,19 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif + } + + // src/core/measureContainersInLayoutEffect.ts ++// T3 patch: measure rows by their layout box, as ResizeObserver does. getBoundingClientRect ++// includes ancestor transforms, so rows that mount while a dialog scales in measure short and ++// stay packed too tightly until they re-render. ++function measureContainerLayoutSize(element) { ++ const rect = element.getBoundingClientRect(); ++ if (Math.abs(rect.width - element.offsetWidth) < 1 && Math.abs(rect.height - element.offsetHeight) < 1) { ++ return { height: rect.height, width: rect.width }; ++ } ++ const style = getComputedStyle(element); ++ const height = Number.parseFloat(style.height); ++ const width = Number.parseFloat(style.width); ++ return Number.isFinite(height) && Number.isFinite(width) ? { height, width } : { height: rect.height, width: rect.width }; ++} + function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { + var _a3, _b, _c; + const dataChangeEpoch = ctx.state.dataChangeEpoch; +@@ -5625,13 +5638,13 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { + const element = viewRef == null ? void 0 : viewRef.current; + if (itemKey !== void 0 && element && isContainerItemCurrent(ctx, containerId, itemKey)) { + const generation = (_b = ctx.state.containerItemGenerations[containerId]) != null ? _b : 0; +- const rect = element.getBoundingClientRect(); +- setContainerLayoutBaseline(element, rect); ++ const size = measureContainerLayoutSize(element); ++ setContainerLayoutBaseline(element, size); + measurements.push({ + containerId, + generation, + itemKey, +- size: { height: rect.height, width: rect.width } ++ size + }); + } + } +@@ -6275,9 +6288,8 @@ function processContainerLayout({ containerId, ctx, rectangle, ref, state }) { + var _a4; + if (state.itemKey === currentItemKey) { + const element = ref.current; +- const rect = (_a4 = element == null ? void 0 : element.getBoundingClientRect) == null ? void 0 : _a4.call(element); +- if (rect) { +- layout = { height: rect.height, width: rect.width }; ++ if (element) { ++ layout = measureContainerLayoutSize(element); + } + applyLayout(); + } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 07806d3cac65..5256d97fe149 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -370,7 +370,7 @@ patchedDependencies: '@effect/vitest@4.1.2': 299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 - '@legendapp/list@3.7.2': 8f361e44c0756d883f8b8b5964f918f37b514a436c5058b773a1dc57eee5bfcc + '@legendapp/list@3.7.2': fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 241563d810c29250e0e92f3eda74214393726d46667fedbf1f91a5f5bea07d1e '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d @@ -567,7 +567,7 @@ importers: version: 4.2.13 '@legendapp/list': specifier: 3.7.2 - version: 3.7.2(patch_hash=8f361e44c0756d883f8b8b5964f918f37b514a436c5058b773a1dc57eee5bfcc)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1088,7 +1088,7 @@ importers: version: 5.3.0 '@legendapp/list': specifier: 3.7.2 - version: 3.7.2(patch_hash=8f361e44c0756d883f8b8b5964f918f37b514a436c5058b773a1dc57eee5bfcc)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -15564,7 +15564,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.2(patch_hash=8f361e44c0756d883f8b8b5964f918f37b514a436c5058b773a1dc57eee5bfcc)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': + '@legendapp/list@3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) From fb89ce1680bcaa16d5c564369543ffefda755529 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 16 Nov 2026 15:14:46 -0600 Subject: [PATCH 004/280] feat(desktop): drag file pills into Finder on macOS (#37768) Co-authored-by: Cursor --- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 2 + apps/desktop/src/ipc/channels.ts | 2 + apps/desktop/src/ipc/methods/fileDrag.test.ts | 51 +++++++++++++++++++ apps/desktop/src/ipc/methods/fileDrag.ts | 36 +++++++++++++ apps/desktop/src/preload.ts | 1 + .../ChatMarkdown.permissions.browser.test.tsx | 1 + apps/web/src/components/ChatMarkdown.tsx | 4 ++ .../components/ComposerPromptEditorTiptap.tsx | 6 +++ .../src/components/chat/MarkdownFileLink.tsx | 7 +++ .../chat/UserMessageContextChips.tsx | 6 +++ apps/web/src/useNativeFileDrag.ts | 47 +++++++++++++++++ packages/contracts/src/ipc.ts | 1 + 12 files changed, 164 insertions(+) create mode 100644 apps/desktop/src/ipc/methods/fileDrag.test.ts create mode 100644 apps/desktop/src/ipc/methods/fileDrag.ts create mode 100644 apps/web/src/useNativeFileDrag.ts diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 60b72deb293a..fe65edd0ee1e 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,3 +1,4 @@ +import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; @@ -110,6 +111,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(startFileDrag); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 9e5c7296a3a0..d8652bd19971 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -142,3 +142,5 @@ export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-stor export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; + +export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts new file mode 100644 index 000000000000..04b75c9be98a --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -0,0 +1,51 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; + +const { startDrag, getFileIcon } = vi.hoisted(() => ({ + startDrag: vi.fn(), + getFileIcon: vi.fn(async () => "file-icon"), +})); +vi.mock("electron", () => ({ app: { getFileIcon } })); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { startFileDrag } from "./fileDrag.ts"; + +it.effect("only drags existing absolute paths from the Mac host environment and app window", () => + Effect.gen(function* () { + startDrag.mockClear(); + getFileIcon.mockClear(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const filePath = path.join(stateDir, "file with spaces.txt"); + yield* fs.writeFileString(filePath, "file"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "host\n"); + const run = (environmentId: string, target: string, platform = "darwin", sender = 1) => + startFileDrag.handler({ environmentId, path: target }, { sender: { id: sender } }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + path, + stateDir, + platform, + } as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ); + assert.isFalse(yield* run("remote", filePath)); + assert.isFalse(yield* run("host", "relative.txt")); + assert.isFalse(yield* run("host", `${filePath}:12`)); + assert.isFalse(yield* run("host", filePath, "linux")); + assert.isFalse(yield* run("host", filePath, "darwin", 2)); + assert.strictEqual(startDrag.mock.calls.length, 0); + assert.isTrue(yield* run("host", filePath)); + assert.deepEqual(startDrag.mock.calls, [[{ file: filePath, icon: "file-icon" }]]); + yield* fs.remove(path.join(stateDir, "environment-id")); + assert.isFalse(yield* run("host", filePath)); + assert.strictEqual(startDrag.mock.calls.length, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts new file mode 100644 index 000000000000..9701dfafcda3 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -0,0 +1,36 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Electron from "electron"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; +import { getHostEnvironmentId } from "./localEnvironment.ts"; + +export const startFileDrag = makeIpcMethod({ + channel: IpcChannels.START_FILE_DRAG_CHANNEL, + payload: Schema.Struct({ environmentId: Schema.String, path: Schema.String }), + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" || !environment.path.isAbsolute(input.path)) return false; + const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); + if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(input.path))) return false; + return yield* Effect.promise(async () => { + try { + const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); + window.value.webContents.startDrag({ file: input.path, icon }); + return true; + } catch { + return false; + } + }); + }), +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ba9c17aae269..c215c4b2e639 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -255,6 +255,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index 324c2c839ccd..a072ecc107e2 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -308,6 +308,7 @@ it("preserves keyboard activation of a file-options button", async () => { copyMarkdown="[Readme](readme.md)" theme="dark" onOpenInPanel={vi.fn()} + resolveDragPath={async () => "/work/readme.md"} resolveCopyPaths={async () => ({ relativePath: "readme.md", fullPath: "/work/readme.md" })} openInEditorMenuLabel="Open in editor" />, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index b48485fc6121..455f18304ab2 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1,3 +1,4 @@ +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment"; import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks"; import { @@ -941,6 +942,9 @@ function useChatMarkdownState({ ) : undefined } + resolveDragPath={async () => + resolvePathLinkTarget((await resolveHostPath()).absolutePath, cwd ?? "") + } resolveCopyPaths={async () => markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd) } diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index d89f57068e9c..20ea35168d21 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { useAtomValue } from "@effect/atom-react"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills"; @@ -281,8 +283,12 @@ const ComposerMentionExtension = Node.create({ function ComposerMentionNodeView({ node }: NodeViewProps) { const actions = use(ComposerContextActionsContext); const path = (node.attrs.path as string) ?? ""; + const nativeDrag = useNativeFileDrag(actions.environmentId, () => + resolvePathLinkTarget(path, actions.cwd ?? ""), + ); const chip = ( } diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 5d0238fb1f3a..53e575bd5bc9 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -1,3 +1,4 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; import { useAssetUrlState } from "../../assets/assetUrls"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { @@ -42,6 +43,7 @@ interface MarkdownFileLinkProps { threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; onOpenInPanel: (panelPath: string, line: number | undefined) => void; + resolveDragPath: () => Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; @@ -73,7 +75,9 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ onReveal, revealLabel, resolveCopyPaths, + resolveDragPath, }: MarkdownFileLinkProps) { + const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath); const handleOpenInEditor = () => { if (!onOpen) { return; @@ -328,6 +332,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ render={ hasPrimaryAction ? ( } @@ -362,6 +367,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ ) : ( } @@ -418,6 +424,7 @@ function areMarkdownFileLinkPropsEqual( previous.onOpenMedia === next.onOpenMedia && previous.onReveal === next.onReveal && previous.resolveCopyPaths === next.resolveCopyPaths && + previous.resolveDragPath === next.resolveDragPath && previous.revealLabel === next.revealLabel ); } diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 39801a908b95..e345472b1f97 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isSvgAttachment } from "@t3tools/shared/image"; import { useRenderedAppearance } from "../../hooks/useTheme"; @@ -68,11 +70,15 @@ function UserMessageMentionChip(props: { copyMarkdown: string; }) { const ctx = use(TimelineRowCtx); + const nativeDrag = useNativeFileDrag(ctx.activeThreadEnvironmentId, () => + resolvePathLinkTarget(props.record.path, ctx.workspaceRoot ?? ""), + ); return ( } aria-label={`Preview ${props.record.path}`} diff --git a/apps/web/src/useNativeFileDrag.ts b/apps/web/src/useNativeFileDrag.ts new file mode 100644 index 000000000000..3195b5ef677b --- /dev/null +++ b/apps/web/src/useNativeFileDrag.ts @@ -0,0 +1,47 @@ +import { splitFilePathPosition } from "@t3tools/shared/fileLinks"; +import { isMacPlatform } from "./lib/utils"; +import { useAtomValue } from "@effect/atom-react"; +import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts"; +import type { DragEvent } from "react"; + +import { hostEnvironmentIdAtom } from "./state/primaryEnvironment"; +import { useEnvironmentScope } from "./state/session"; +import { toastManager } from "./components/ui/toast"; + +export function useNativeFileDrag( + environmentId: EnvironmentId | null | undefined, + resolvePath: () => string | Promise, +) { + const hostEnvironmentId = useAtomValue(hostEnvironmentIdAtom); + const canOperate = useEnvironmentScope(environmentId ?? null, AuthOrchestrationOperateScope); + const enabled = + typeof window.desktopBridge?.startFileDrag === "function" && + isMacPlatform(navigator.platform) && + environmentId != null && + environmentId === hostEnvironmentId && + canOperate; + return { + draggable: enabled || undefined, + onDragStart: (event: DragEvent) => { + if (!enabled) return; + // Electron replaces the HTML drag with a native file drag. + event.preventDefault(); + event.stopPropagation(); + let released = false; + window.addEventListener("pointerup", () => (released = true), { once: true }); + void (async () => { + const { path } = splitFilePathPosition(await resolvePath()); + if (released) return; + const started = await window.desktopBridge?.startFileDrag({ environmentId, path }); + if (!started) throw new Error("The file is unavailable on this Mac."); + })().catch((error: unknown) => { + if (released) return; + toastManager.add({ + type: "error", + title: "Unable to drag file", + description: error instanceof Error ? error.message : "An error occurred.", + }); + }); + }, + }; +} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 25339cb3216b..96942123f56d 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1151,6 +1151,7 @@ export interface DesktopBridge { ) => Promise; receiveProviderAuthCallback: (authorizationUrl: string) => Promise; cancelProviderAuthCallback: (authorizationUrl: string) => Promise; + startFileDrag: (input: { environmentId: EnvironmentId; path: string }) => Promise; openExternal: (url: string) => Promise; /** Reads http(s) media in the main process, outside renderer CORS and CSP; null on network failure. */ readMedia: (url: string) => Promise; From e05b087a34b71a8fe14cc99d4f5b5041e1096e51 Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Mon, 16 Nov 2026 22:16:48 +0100 Subject: [PATCH 005/280] fix(server): creating a thread no longer records a failed projection read span (#37763) Co-authored-by: Julius Marminge --- .../Orchestrator.control-reads.test.ts | 19 ++++++++- .../src/orchestration-v2/Orchestrator.ts | 25 +++--------- .../src/orchestration-v2/ProjectionStore.ts | 39 +++++++++++-------- .../ProviderTurnControlService.test.ts | 1 + 4 files changed, 47 insertions(+), 37 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 214f6cf360e2..ff96b2fbac1a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -23,14 +23,15 @@ import { import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Metric from "effect/Metric"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; -import type * as Tracer from "effect/Tracer"; import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; import { @@ -1880,7 +1881,21 @@ it.effect.each([false, true])("rejects thread.create for an existing id (deleted ref: { driver: adapter.driver, nativeId: "native-original", strength: "strong" }, }, } as const; - yield* orchestrator.dispatch(create); + const failedSpans: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (Exit.isFailure(exit)) failedSpans.push(span.name); + }; + return span; + }, + }); + yield* orchestrator.dispatch(create).pipe(Effect.withTracer(tracer)); + // The id check expects a miss; a failed span there reads as an error in Tempo. + assert.deepEqual(failedSpans, []); if (deleted) { yield* orchestrator.dispatch({ type: "thread.delete", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2805935d3889..f047fe771f1d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1821,10 +1821,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio /** Includes tombstones, which still reserve their id. */ const findThread = (threadId: ThreadId) => - projectionStore.getThread(threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), - ); + projectionStore + .findThread(threadId) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); /** Side chats live inside their parent, so deleting the parent deletes them too. */ const liveSideChatIds = Effect.fn("Orchestrator.liveSideChatIds")( @@ -1839,11 +1838,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const sideChatIds: Array = []; for (const transfer of contextTransfers) { if (transfer.type !== "fork" || transfer.sourceThreadId !== threadId) continue; - const child = yield* projectionStore - .getThread(transfer.targetThreadId) - .pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - ); + const child = yield* projectionStore.findThread(transfer.targetThreadId); if (child?.lineage.sideChat === true && child.deletedAt === null) { sideChatIds.push(child.id); } @@ -3762,12 +3757,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); // Tombstones reserve their ids too; recreating one would overwrite its history. - const existing = yield* projectionStore.getThread(command.threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), - ); + const existing = yield* findThread(command.threadId); if (existing !== null) { return yield* new OrchestratorThreadAlreadyExistsError({ commandId: command.commandId, @@ -5643,10 +5633,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (runtimeModeCeiling === undefined) return; const runtimeModes = new Map(); for (const threadId of threadsStartingWork(events)) { - const thread = yield* projectionStore.getThread(threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), - ); + const thread = yield* findThread(threadId); if (thread !== null) runtimeModes.set(threadId, thread.runtimeMode); } const refusal = runtimeModeCeilingRefusal( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5b71a6ac042f..25a86d351548 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -625,6 +625,10 @@ export interface ProjectionStoreV2Shape { readonly getThread: ( threadId: ThreadId, ) => Effect.Effect; + /** Like getThread, but a missing thread is null, so an expected miss is not an error span. */ + readonly findThread: ( + threadId: ThreadId, + ) => Effect.Effect; readonly getLimitRecoveryCandidates: (options: { readonly now: DateTime.Utc; readonly autoResume: boolean; @@ -5611,27 +5615,29 @@ export const layer: Layer.Layer = ), ); + const selectThread = (threadId: ThreadId) => + sql` + SELECT payload_json FROM orchestration_v2_projection_threads + WHERE thread_id = ${threadId} + `.pipe( + Effect.flatMap((rows) => + rows[0] === undefined ? Effect.succeed(null) : decodeThreadPayload(rows[0].payload_json), + ), + Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })), + ); + const getThread: ProjectionStoreV2Shape["getThread"] = Effect.fn("ProjectionStore.getThread")( function* (threadId) { - const rows = yield* sql` - SELECT payload_json FROM orchestration_v2_projection_threads - WHERE thread_id = ${threadId} - `; - if (rows[0] === undefined) { - return yield* new ProjectionStoreThreadNotFoundError({ threadId }); - } - return yield* decodeThreadPayload(rows[0].payload_json); + const thread = yield* selectThread(threadId); + if (thread === null) return yield* new ProjectionStoreThreadNotFoundError({ threadId }); + return thread; }, - (effect, threadId) => - effect.pipe( - Effect.mapError((cause) => - isProjectionStoreThreadNotFoundError(cause) - ? cause - : new ProjectionStoreReadError({ threadId, cause }), - ), - ), ); + const findThread: ProjectionStoreV2Shape["findThread"] = Effect.fn( + "ProjectionStore.findThread", + )(selectThread); + const requireThread = Effect.fn("ProjectionStore.requireThread")(function* ( threadId: ThreadId, ) { @@ -9292,6 +9298,7 @@ export const layer: Layer.Layer = getThreadShell: readOnReader(getThreadShell), findGuestShareThreadId: readOnReader(findGuestShareThreadId), getThread: readOnReader(getThread), + findThread: readOnReader(findThread), getSettlementCandidates: readOnReader(getSettlementCandidates), getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests), getThreadTitles: readOnReader(getThreadTitles), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 532d019ddd6f..069e36ceef91 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -226,6 +226,7 @@ it.effect( getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"), findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"), getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)), + findThread: () => Effect.die("unused findThread"), getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"), getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"), From 80b9620454f29df388659468eb7cc0b213a520ef Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:17:19 -0800 Subject: [PATCH 006/280] fix(gitlab): Create MR works with snap-installed glab (#31763) --- packages/source-control-gitlab/package.json | 1 + .../src/server/GitLabCli.test.ts | 64 +++++++++++++++++-- .../src/server/GitLabCli.ts | 36 ++++++++++- .../GitLabPullRequestCli.legacy.test.ts | 2 + ...itLabPullRequestProvider.rateLimit.test.ts | 2 + .../server/GitLabPullRequestProvider.test.ts | 3 +- .../GitLabSourceControlProvider.git.test.ts | 2 + .../GitLabSourceControlProvider.test.ts | 14 +++- pnpm-lock.yaml | 3 + 9 files changed, 119 insertions(+), 8 deletions(-) diff --git a/packages/source-control-gitlab/package.json b/packages/source-control-gitlab/package.json index 592ca6e9d0d8..ec9e4705ace7 100644 --- a/packages/source-control-gitlab/package.json +++ b/packages/source-control-gitlab/package.json @@ -23,6 +23,7 @@ "effect": "catalog:" }, "devDependencies": { + "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@t3tools/source-control-testing": "workspace:*", "@types/node": "catalog:", diff --git a/packages/source-control-gitlab/src/server/GitLabCli.test.ts b/packages/source-control-gitlab/src/server/GitLabCli.test.ts index 884556c67f04..4ec945afb149 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.test.ts @@ -1,6 +1,9 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it, afterEach, expect, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import { ChildProcessSpawner } from "effect/process"; import { VcsProcessExitError } from "@t3tools/contracts"; @@ -11,7 +14,10 @@ import * as GitLabCli from "./GitLabCli.ts"; const mockedRun = vi.fn(); const layer = it.layer( - GitLabCli.layer.pipe(Layer.provide(TestSourceControlHost.layer({ process: { run: mockedRun } }))), + GitLabCli.layer.pipe( + Layer.provide(TestSourceControlHost.layer({ process: { run: mockedRun } })), + Layer.provideMerge(NodeServices.layer), + ), ); function processOutput(stdout: string): SourceControlHost.SourceControlProcessOutput { @@ -98,6 +104,54 @@ layer("GitLabCli.layer", (it) => { }), ); + // A strictly confined glab (Snap) has a private /tmp, so it cannot open the server's body file. + it.effect("sends the merge request description to glab on stdin, not as a file path", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" }); + const bodyFile = path.join(bodyDir, "t3code-pr-body.md"); + yield* fileSystem.writeFileString(bodyFile, "## Summary\n\nFixes the thing.\n"); + mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}"))); + + const glab = yield* GitLabCli.GitLabCli; + yield* glab.createMergeRequest({ + cwd: "/repo", + baseBranch: "main", + headSelector: "feature/mr", + title: "Add MR", + bodyFile, + }); + + const call = mockedRun.mock.calls.at(-1)?.[0]; + expect(call?.args.join(" ")).not.toContain(bodyFile); + expect(call?.args).toContain("description=@-"); + assert.strictEqual(call?.stdin, "## Summary\n\nFixes the thing.\n"); + }).pipe(Effect.scoped), + ); + + it.effect("fails with a typed error and skips glab when the description cannot be read", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" }); + const glab = yield* GitLabCli.GitLabCli; + const error = yield* glab + .createMergeRequest({ + cwd: "/repo", + baseBranch: "main", + headSelector: "feature/mr", + title: "Add MR", + bodyFile: path.join(bodyDir, "missing.md"), + }) + .pipe(Effect.flip); + + assert.strictEqual(error._tag, "GitLabMergeRequestBodyReadError"); + assert.strictEqual(error.detail, "The merge request description could not be read."); + expect(mockedRun).not.toHaveBeenCalled(); + }).pipe(Effect.scoped), + ); + it.effect("skips invalid entries when parsing MR lists", () => Effect.gen(function* () { mockedRun.mockReturnValueOnce( @@ -209,6 +263,8 @@ layer("GitLabCli.layer", (it) => { it.effect("creates same-project MRs without a repository lookup", () => Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitlab-mr-body-" }); mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}"))); const glab = yield* GitLabCli.GitLabCli; yield* glab.createMergeRequest({ @@ -216,7 +272,7 @@ layer("GitLabCli.layer", (it) => { baseBranch: "main", headSelector: "feature/fix", title: "Fix remote flow", - bodyFile: "/tmp/body.md", + bodyFile, }); expect(mockedRun).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ @@ -232,11 +288,11 @@ layer("GitLabCli.layer", (it) => { "--raw-field", "title=Fix remote flow", "--field", - "description=@/tmp/body.md", + "description=@-", ], }), ); - }), + }).pipe(Effect.scoped), ); it.effect("surfaces a friendly error when the merge request is not found", () => diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index 649b33cd4133..8b6d7e1ab3c6 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -1,6 +1,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Match from "effect/Match"; import * as Option from "effect/Option"; @@ -238,6 +239,24 @@ export class GitLabNamespaceDecodeError extends Schema.TaggedError()( + "GitLabMergeRequestBodyReadError", + { + operation: Schema.Literal("createMergeRequest"), + command: Schema.Literal("glab"), + cwd: Schema.String, + cause: Schema.Defect(), + }, +) { + get detail(): string { + return "The merge request description could not be read."; + } + + override get message(): string { + return `GitLab CLI failed in ${this.operation}: ${this.detail}`; + } +} + export const GitLabCliError = Schema.Union([ GitLabCliUnavailableError, GitLabCliAuthenticationError, @@ -248,6 +267,7 @@ export const GitLabCliError = Schema.Union([ GitLabMergeRequestDecodeError, GitLabRepositoryDecodeError, GitLabNamespaceDecodeError, + GitLabMergeRequestBodyReadError, ]); export type GitLabCliError = typeof GitLabCliError.Type; @@ -459,6 +479,7 @@ const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null = /** @public */ export const make = Effect.gen(function* () { const { process } = yield* SourceControlHost.SourceControlHost; + const fileSystem = yield* FileSystem.FileSystem; const run = ( input: Parameters[0], @@ -681,6 +702,18 @@ export const make = Effect.gen(function* () { ); }), createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function* (input) { + // A confined glab (Snap) has a private /tmp, so it cannot open the server's body file. + const description = yield* fileSystem.readFileString(input.bodyFile).pipe( + Effect.mapError( + (cause) => + new GitLabMergeRequestBodyReadError({ + operation: "createMergeRequest", + command: "glab", + cwd: input.cwd, + cause, + }), + ), + ); let project = ":fullpath"; let targetProjectId: number | undefined; if (input.source?.repository || input.source?.owner) { @@ -718,8 +751,9 @@ export const make = Effect.gen(function* () { "--raw-field", `title=${input.title}`, "--field", - `description=@${input.bodyFile}`, + "description=@-", ], + stdin: description, }); }), getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) { diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts index cf21ac0c2403..5888836ace13 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts @@ -1,5 +1,6 @@ import { afterEach, expect, it, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import { ChildProcessSpawner } from "effect/process"; import { VcsProcessExitError } from "@t3tools/contracts"; @@ -14,6 +15,7 @@ const layer = it.layer( GitLabPullRequestCli.layer.pipe( Layer.provide(GitLabCli.layer), Layer.provide(TestSourceControlHost.layer({ process: { run } })), + Layer.provide(FileSystem.layerNoop({})), ), ); const input = { cwd: "/repo", repository: "acme/nested/web", number: 7 }; diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.rateLimit.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.rateLimit.test.ts index 9c59f2320326..c6e18a77e61c 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.rateLimit.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.rateLimit.test.ts @@ -1,6 +1,7 @@ import { VcsProcessExitError } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -33,6 +34,7 @@ it.effect("reports activity as rate limited when only the reactions endpoint is" }, }), ), + Layer.provide(FileSystem.layerNoop({})), ), ), ); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts index c8f684ff8999..5b0b41f6c574 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts @@ -1,5 +1,6 @@ import { assert, describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as TestClock from "effect/testing/TestClock"; @@ -75,7 +76,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)( ); }, }, - }), + }).pipe(Layer.merge(FileSystem.layerNoop({}))), ), ); const cli = yield* GitLabPullRequestCli.make.pipe( diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index ab6a77dae5bb..7038e6a82d63 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -7,6 +7,7 @@ import type { GitCommandError } from "@t3tools/contracts"; import { assert, expect, 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 SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; @@ -59,6 +60,7 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }, }), ), + Layer.provide(FileSystem.layerNoop({})), ), ), ); diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index bc503c9db46a..8e5077044c6b 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -4,6 +4,7 @@ import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost"; 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 { ChildProcessSpawner } from "effect/process"; @@ -333,14 +334,23 @@ it.effect.each([ "--raw-field", "title=Fix remote flow", "--field", - "description=@/tmp/body.md", + "description=@-", ]); + assert.strictEqual(input.stdin, "Body"); return Effect.succeed(processOutput("{}")); }, }, }); const provider = yield* GitLabSourceControlProvider.make.pipe( - Effect.provide(Layer.merge(host, GitLabCli.layer.pipe(Layer.provide(host)))), + Effect.provide( + Layer.merge( + host, + GitLabCli.layer.pipe( + Layer.provide(host), + Layer.provide(FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") })), + ), + ), + ), ); yield* provider.createChangeRequest({ cwd: "/repo", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5256d97fe149..9c1a4a064933 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2437,6 +2437,9 @@ importers: specifier: 4.1.3 version: 4.1.3 devDependencies: + '@effect/platform-node': + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.3)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.3)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) From 747ed9c5b1d9b2d41638ef94003bda1d996f4353 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:20:00 -0800 Subject: [PATCH 007/280] fix(mobile): show background work at the end of the feed, and even out its spacing (#37767) --- .../features/threads/ThreadDetailScreen.tsx | 66 ++++++++++--------- .../src/features/threads/ThreadFeed.tsx | 20 +++--- .../threads/floating-working-control.tsx | 30 +-------- .../threads/floating-working-status.ts | 8 --- .../threads/thread-context-divider.tsx | 53 ++++++++++----- 5 files changed, 86 insertions(+), 91 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index b711889a0100..e1f38fec47f2 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -190,7 +190,7 @@ import { FloatingWorkingControl, } from "./floating-working-control"; import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status"; -import type { ThreadLifecycleEvent } from "./thread-context-divider"; +import type { ThreadStatusLineModel } from "./thread-context-divider"; import { derivePendingUserInputMaxHeight, ESTIMATED_KEYBOARD_HEIGHT, @@ -341,6 +341,7 @@ function ColumnWidth(props: { readonly width: number | null; readonly children: ); } const USAGE_LIMITS_PANEL_GAP = 12; +const FEED_END_GAP = 12; const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44; const USER_INPUT_TOGGLE_TIMING = { @@ -738,7 +739,31 @@ function ThreadDetailBody( Dialog.alert("Pi", props.extensionStatuses?.map((status) => status.text).join("\n\n")), } : null; - const lifecycleEvent = ((): ThreadLifecycleEvent | null => { + const backgroundLine = ((): ThreadStatusLineModel | null => { + if (pendingBackgroundWork === null || contentPresentationKind !== "ready") return null; + return { + key: "background", + icon: pendingBackgroundWork.waiting ? "person.2" : "terminal", + label: pendingBackgroundWork.title, + accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items + .map((item) => item.label) + .join(", ")}`, + onOpen: () => { + Keyboard.dismiss(); + navigation.navigate("ThreadBackgroundWork", { + environmentId: props.environmentId, + threadId: props.selectedThread.id, + }); + }, + action: { + label: statusPending ? "Stopping..." : "Stop", + accessibilityLabel: "Stop background work", + disabled: !props.canOperateThread || statusPending, + onPress: () => void runStatusAction("stop"), + }, + }; + })(); + const lifecycleLine = ((): ThreadStatusLineModel | null => { if (contentPresentationKind !== "ready" || !(lifecycleSnoozed || settled || woke)) return null; const actionLabel = lifecycleSnoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss"; const wake = @@ -746,7 +771,8 @@ function ThreadDetailBody( ? snoozeWakeLabel(snoozedUntil, { now: lifecycleNow }) : "now"; return { - state: lifecycleSnoozed ? "snoozed" : settled ? "settled" : "woke", + key: "lifecycle", + icon: settled && !lifecycleSnoozed ? "checkmark.circle" : "alarm", label: lifecycleSnoozed ? wake === "now" ? "Snoozed" @@ -769,6 +795,7 @@ function ThreadDetailBody( }, }; })(); + const statusLines = [backgroundLine, lifecycleLine].filter((line) => line !== null); const floatingStatus = ((): FloatingWorkingStatus | null => { const connectionStatus = connectionFloatingStatus({ connectionError: props.connectionError, @@ -828,29 +855,6 @@ function ThreadDetailBody( }, }; } - if (pendingBackgroundWork !== null && contentPresentationKind === "ready") { - return { - kind: "background", - label: pendingBackgroundWork.title, - accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items - .map((item) => item.label) - .join(", ")}`, - waiting: pendingBackgroundWork.waiting, - onPress: () => { - Keyboard.dismiss(); - navigation.navigate("ThreadBackgroundWork", { - environmentId: props.environmentId, - threadId: props.selectedThread.id, - }); - }, - action: { - label: statusPending ? "Stopping..." : "Stop", - accessibilityLabel: "Stop background work", - disabled: !props.canOperateThread || statusPending, - onPress: () => void runStatusAction("stop"), - }, - }; - } if (props.selectedThread.goal !== null && contentPresentationKind === "ready") { const goal = presentProviderGoal(props.selectedThread.goal, false); return { @@ -1119,7 +1123,8 @@ function ThreadDetailBody( questionInFlow ? 0 : contentInsetEndAdjustment.value + - floatingControlCoverage.value + + // The feed's last row keeps a gap above the composer; the status row grows from it. + Math.max(FEED_END_GAP, floatingControlCoverage.value) + (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0), @@ -1448,7 +1453,7 @@ function ThreadDetailBody( workspaceRoot={props.threadCwd} feed={props.selectedThreadFeed} pendingHandoff={props.pendingHandoff} - lifecycleEvent={lifecycleEvent} + statusLines={statusLines} worktreeSetup={props.worktreeSetup} setupWorkingStartedAt={props.setupWorkingStartedAt} preparingWorktree={ @@ -1483,7 +1488,7 @@ function ThreadDetailBody( questionInFlow ? 0 : estimatedOverlayHeight + - (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0) + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : FEED_END_GAP) } contentMaxWidth={contentMaxWidth} historyControls={props.historyControls} @@ -1575,8 +1580,7 @@ function ThreadDetailBody( colorScheme={isDarkMode ? "dark" : "light"} status={floatingStatus} extensionStatus={ - floatingStatus !== null && - (floatingStatus.kind === "background" || floatingStatus.kind === "goal") + floatingStatus !== null && floatingStatus.kind === "goal" ? extensionStatus : null } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index be4e05273a99..e092777ad494 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -23,8 +23,8 @@ import { import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; import { ThreadContextDivider, - ThreadLifecycleLine, - type ThreadLifecycleEvent, + ThreadStatusLine, + type ThreadStatusLineModel, } from "./thread-context-divider"; import { ThreadHandoffDivider, @@ -362,7 +362,8 @@ export interface ThreadFeedProps { readonly workspaceRoot?: string | null; readonly feed: ReadonlyArray; readonly pendingHandoff?: HandoffEndpoints | null; - readonly lifecycleEvent?: ThreadLifecycleEvent | null; + /** Thread states that close the feed: background work, then snooze or settle. */ + readonly statusLines?: ReadonlyArray; readonly contentPresentation: ThreadContentPresentation; readonly latestRun: ThreadFeedLatestRun | null; readonly activeWorkStartedAt: string | null; @@ -1604,7 +1605,7 @@ function ThreadAutomationMessageRow(props: { const summary = taskTitle ?? props.text.trim().split(/\r?\n/, 1)[0] ?? ""; return ( - + 0); return ( {presentation.attribution === "t3code" ? ( @@ -4160,7 +4162,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } ListFooterComponent={ - props.pendingHandoff || props.lifecycleEvent ? ( + props.pendingHandoff || props.statusLines?.length ? ( <> {props.pendingHandoff ? ( ) : null} - {props.lifecycleEvent ? ( - - ) : null} + {props.statusLines?.map((line) => ( + + ))} ) : null } diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index 3624bc6f310e..f1143e9e5040 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -81,10 +81,7 @@ export function FloatingWorkingControl(props: { const extensionStatus = props.extensionStatus ?? null; const extensionOnly = props.status?.kind === "extension"; const useGlass = NATIVE_LIQUID_GLASS_SUPPORTED && !extensionOnly; - const action = - props.status?.kind === "background" || props.status?.kind === "stop" - ? props.status.action - : null; + const action = props.status?.kind === "stop" ? props.status.action : null; const [agentsWidth, setAgentsWidth] = useState(0); const hasQueue = props.queuedCount > 0; const hasPreview = props.devicePreview !== null || props.browserPreview !== null; @@ -164,8 +161,7 @@ export function FloatingWorkingControl(props: { const statusInteractive = props.status?.kind === "connection" || props.status?.kind === "extension" || - props.status?.kind === "child-input" || - props.status?.kind === "background"; + props.status?.kind === "child-input"; const capsuleInteractive = statusInteractive || extensionStatus !== null || @@ -436,28 +432,6 @@ function FloatingStatusLabel(props: { ); } - if (props.status.kind === "background") { - return ( - - - - {props.status.label} - - - ); - } if (props.status.kind === "stop") { return ( void; } - | { - readonly kind: "background"; - readonly label: string; - readonly accessibilityLabel: string; - readonly waiting: boolean; - readonly onPress: () => void; - readonly action: FloatingStatusAction; - } | { readonly kind: "stop"; readonly label: string; diff --git a/apps/mobile/src/features/threads/thread-context-divider.tsx b/apps/mobile/src/features/threads/thread-context-divider.tsx index 2db044d7da6a..ccaa1b1d8aa9 100644 --- a/apps/mobile/src/features/threads/thread-context-divider.tsx +++ b/apps/mobile/src/features/threads/thread-context-divider.tsx @@ -50,9 +50,13 @@ export function ThreadContextDivider(props: { ); } -export interface ThreadLifecycleEvent { - readonly state: "snoozed" | "settled" | "woke"; +export interface ThreadStatusLineModel { + readonly key: string; + readonly icon: AppSymbolName; readonly label: string; + readonly accessibilityLabel?: string; + /** Tapping the label opens the state's detail. */ + readonly onOpen?: () => void; readonly action: { readonly label: string; readonly accessibilityLabel: string; @@ -61,23 +65,42 @@ export interface ThreadLifecycleEvent { }; } -/** Closes the feed while the thread is snoozed, settled, or just woke. Left-aligned, as on web. */ -export function ThreadLifecycleLine(props: { - readonly event: ThreadLifecycleEvent; +/** A thread state that closes the feed with its one action, left-aligned as on web. */ +export function ThreadStatusLine(props: { + readonly line: ThreadStatusLineModel; readonly iconColor: ColorValue; }) { - const { action } = props.event; - return ( - - + const { line } = props; + const { action } = line; + const body = ( + <> + - {props.event.label} + {line.label} + + ); + return ( + + {line.onOpen ? ( + + {body} + + ) : ( + + {body} + + )} · Date: Mon, 16 Nov 2026 15:38:37 -0600 Subject: [PATCH 008/280] feat(web): copy snapshots into another composer (#37771) Co-authored-by: Cursor --- .../src/lib/composerContextClipboard.test.ts | 13 +++- .../src/lib/composerContextClipboard.ts | 7 +- ...rPromptEditorTiptap.input.browser.test.tsx | 67 ++++++++++++++++- .../components/ComposerPromptEditorTiptap.tsx | 13 +++- apps/web/src/components/chat/ChatComposer.tsx | 37 ++++++++- .../chat/ComposerAttachmentStrip.tsx | 9 ++- .../components/chat/ExpandedImageDialog.tsx | 6 ++ .../components/chat/ExpandedImagePreview.tsx | 9 ++- .../chat/SnapShotAttachmentDetails.tsx | 75 ++++++++++++++++++- .../chat/TimelineUserMessageRow.tsx | 29 ++++++- .../src/components/chat/copySnapshot.test.ts | 75 +++++++++++++++++++ apps/web/src/components/chat/copySnapshot.ts | 33 ++++++++ .../useComposerContextImport.browser.test.tsx | 17 ++++- .../chat/useComposerContextImport.ts | 1 + packages/contracts/src/composerContext.ts | 3 + 15 files changed, 374 insertions(+), 20 deletions(-) create mode 100644 apps/web/src/components/chat/copySnapshot.test.ts create mode 100644 apps/web/src/components/chat/copySnapshot.ts diff --git a/apps/mobile/src/lib/composerContextClipboard.test.ts b/apps/mobile/src/lib/composerContextClipboard.test.ts index 77305cce8443..41cdcf3078bc 100644 --- a/apps/mobile/src/lib/composerContextClipboard.test.ts +++ b/apps/mobile/src/lib/composerContextClipboard.test.ts @@ -73,6 +73,13 @@ const image = { mimeType: "image/png", sizeBytes: 7, attachmentId: "source-file", + source: { + kind: "snap-shot" as const, + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, }; const terminal = { version: 1 as const, @@ -146,7 +153,11 @@ describe("mobile context clipboard imports", () => { const signal = { aborted: false } as AbortSignal; const result = await importComposerContextClipboard(clipboard, 0, signal); expect(result?.failures).toEqual([]); - expect(result?.attachments[0]).toMatchObject({ fileUri: "file:///owned.png", sizeBytes: 42 }); + expect(result?.attachments[0]).toMatchObject({ + fileUri: "file:///owned.png", + sizeBytes: 42, + source: image.source, + }); expect(result?.context.records[0]).toMatchObject({ contextId: "import-1", attachmentId: result?.attachments[0]?.id, diff --git a/apps/mobile/src/lib/composerContextClipboard.ts b/apps/mobile/src/lib/composerContextClipboard.ts index 8c5a31cdb7e4..e744a2cbbf96 100644 --- a/apps/mobile/src/lib/composerContextClipboard.ts +++ b/apps/mobile/src/lib/composerContextClipboard.ts @@ -253,6 +253,11 @@ async function persistImportedAttachment( sizeBytes: new File(fileUri).size, }; return record.kind === "image" - ? { ...common, type: "image", previewUri: fileUri } + ? { + ...common, + type: "image", + previewUri: fileUri, + ...(record.source ? { source: record.source } : {}), + } : { ...common, type: "file" }; } diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 692a135ad883..58e9a29b57c1 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -7,7 +7,17 @@ import { useRetainedContextPayloads, } from "./chat/composerContextUndo"; -import type { ServerProviderSkill } from "@t3tools/contracts"; +import { + ComposerContextId, + type ComposerContextRecord, + EnvironmentId, + type ServerProviderSkill, +} from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; import type { Editor } from "@tiptap/core"; import { redoDepth, undoDepth } from "@tiptap/pm/history"; import { NodeSelection } from "@tiptap/pm/state"; @@ -54,12 +64,16 @@ function Composer({ skills, onChange, onCommandKeyDown = () => false, + importContextFragment, + literalText = false, }: { value: string; richTextEnabled: boolean; skills: ReadonlyArray; onChange?: ComposerPromptEditorProps["onChange"] | undefined; onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined; + importContextFragment?: ComposerPromptEditorProps["importContextFragment"]; + literalText?: boolean; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); return ( @@ -78,6 +92,8 @@ function Composer({ }} onPaste={() => {}} onCommandKeyDown={onCommandKeyDown} + importContextFragment={importContextFragment} + literalText={literalText} /> ); } @@ -482,6 +498,55 @@ it.each([ expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted); }); +it.each([ + { literalText: false, imports: 1 }, + { literalText: true, imports: 0 }, +])( + "imports a copied snapshot's context over its image file: %o", + async ({ literalText, imports }) => { + const record = { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "shot.png", + attachmentId: "snapshot", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 3, + } satisfies ComposerContextRecord; + const importContextFragment = vi.fn(() => new Map([[record.contextId, record.contextId]])); + await using screen = await render( + , + ); + const editor = editorIn(screen.container); + await act(async () => { + const clipboardData = new DataTransfer(); + clipboardData.items.add( + new File([new Uint8Array([1, 2, 3])], "shot.png", { type: "image/png" }), + ); + clipboardData.setData("text/plain", formatComposerContextReference(record)); + clipboardData.setData( + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [record], + })!, + ); + editor.view.dom.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, cancelable: true }), + ); + }); + expect(importContextFragment).toHaveBeenCalledTimes(imports); + }, +); + it.each(["x\r\n\r\ny", "x\r\ry"])( "pastes %j with the same blank line as x\\n\\ny", async (text) => { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 20ea35168d21..59d37fbe8c78 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -138,7 +138,11 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView"; import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal"; import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight"; -import { importPastedComposerText, readPastedPlainText } from "./composerInlineTokenPaste"; +import { + importPastedComposerText, + readPastedComposerContext, + readPastedPlainText, +} from "./composerInlineTokenPaste"; import { didComposerSelectionChangeVisibly } from "./composerSelection"; import { captureComposerAttachmentInsertion, @@ -1404,7 +1408,12 @@ function ComposerPromptEditorTiptapInner( }, handlePaste: (view, event) => { const clipboardData = event.clipboardData; - if (!clipboardData || clipboardData.files.length > 0) return false; + if (!clipboardData) return false; + if ( + clipboardData.files.length > 0 && + (literalText || !readPastedComposerContext(clipboardData)?.records.length) + ) + return false; const pastedText = readPastedPlainText(clipboardData); if (!pastedText) return false; event.preventDefault(); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index be3144efb40b..8fb98edc1446 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,3 +1,4 @@ +import { copySnapshot } from "./copySnapshot"; import { VoiceInputSetup } from "./VoiceInputSetup"; import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; @@ -148,6 +149,7 @@ import { type TerminalContextSelection, } from "../../lib/terminalContext"; import { + formatComposerContextReference, threadContextRecord, toKindScopedComposerContextId, } from "@t3tools/shared/composerContextReferences"; @@ -717,7 +719,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview(composerImages, imageId); + const preview = buildExpandedImagePreview( + composerImages, + imageId, + copyComposerSnapshotStable, + ); if (preview) onExpandImage(preview); }, openFile: setPreviewFileId, @@ -1334,7 +1340,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [record]; + return [ + record.kind === "image" && attachment.type === "image" && attachment.source + ? { ...record, source: attachment.source } + : record, + ]; }), ]; if (records.length === 0) return null; @@ -1346,6 +1356,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles); return fragment; }; + const copyComposerSnapshot = async (imageId: string) => { + const image = composerImages.find((candidate) => candidate.id === imageId); + if (!image) throw new Error("Snapshot is no longer available."); + const contextId = toKindScopedComposerContextId("image", image.id); + const fragment = buildContextClipboardFragment([contextId]); + if (!fragment || !image.previewUrl) throw new Error("The snapshot is not ready to copy."); + await copySnapshot( + image.previewUrl, + formatComposerContextReference({ kind: "image", contextId, label: image.name }), + fragment, + ); + }; + const copyComposerSnapshotStable = useStableCallback(copyComposerSnapshot); const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); const { loadThreadTranscript, @@ -2416,6 +2439,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) allImages={composerImages} resolvedTheme={resolvedTheme} onExpandImage={onExpandImage} + onCopySnapshot={copyComposerSnapshotStable} onShowMore={expandMobileComposer} /> ) : null; @@ -2760,9 +2784,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { files, folders } = splitTransferredFiles(event.clipboardData); const plainText = event.clipboardData.getData("text/plain"); const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); + const pastedContext = + !isLiteralPendingAnswer && + (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; if ( folders.length > 0 || - (activeThreadId && + (!pastedContext && + activeThreadId && files.length > 0 && shouldHandleComposerAttachmentPaste({ files, plainText })) ) { @@ -2775,7 +2803,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } - if ((readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0) return; + if (pastedContext) return; if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3315,6 +3343,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId={environmentId} attachmentDraftTarget={attachmentDraftTarget} canOperateThread={canOperateThread} + onCopySnapshot={copyComposerSnapshotStable} onExpandImage={onExpandImage} onFileOpen={onFileOpen} onRemoveImage={removeComposerImage} diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index ca98b4d2f6c7..59115804e497 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -149,6 +149,7 @@ export function ComposerAttachmentMediaRow({ attachmentDraftTarget, canOperateThread, onExpandImage, + onCopySnapshot, onFileOpen, onRemoveImage, onRemoveFile, @@ -167,6 +168,7 @@ export function ComposerAttachmentMediaRow({ readonly environmentId: EnvironmentId; readonly attachmentDraftTarget: ScopedThreadRef | DraftId; readonly canOperateThread: boolean; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onFileOpen: (attachment: ChatFileAttachment) => void; readonly onRemoveImage: (imageId: string) => void; @@ -224,7 +226,7 @@ export function ComposerAttachmentMediaRow({ aria-label={`Preview ${image.name}`} disabled={!ready} onClick={() => { - const preview = buildExpandedImagePreview(images, image.id); + const preview = buildExpandedImagePreview(images, image.id, onCopySnapshot); if (!preview) return; onExpandImage(preview); }} @@ -254,6 +256,7 @@ export function ComposerAttachmentMediaRow({ {source?.kind === "snap-shot" ? ( onCopySnapshot(ready.id) : undefined} className={cn( upload?.status === "uploading" && "bottom-4", upload?.status === "failed" && "bottom-8", @@ -586,11 +589,13 @@ export function ComposerRestingImagePreviews({ allImages, resolvedTheme, onExpandImage, + onCopySnapshot, onShowMore, }: { readonly images: ReadonlyArray; readonly allImages: ReadonlyArray; readonly resolvedTheme: "light" | "dark"; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onShowMore: () => void; }) { @@ -606,7 +611,7 @@ export function ComposerRestingImagePreviews({ aria-label={`Preview ${image.name}`} onPointerDown={(event) => event.preventDefault()} onClick={() => { - const preview = buildExpandedImagePreview(allImages, image.id); + const preview = buildExpandedImagePreview(allImages, image.id, onCopySnapshot); if (preview) onExpandImage(preview); }} > diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 2d70c5f2ef1d..a539994d0186 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -18,6 +18,7 @@ import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; import { isContextMenuOpen } from "../../contextMenuFallback"; import { SnapShotAccessibilityData, + SnapShotCopyButton, SnapShotContentsButton, snapShotAccessibilityDetails, } from "./SnapShotAttachmentDetails"; @@ -277,6 +278,11 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ ) : item.source ? ( ) : null} + {item.onCopySnapshot && ( +
+ +
+ )} diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx index 0eec6753f8e9..ddd299000011 100644 --- a/apps/web/src/components/chat/ExpandedImagePreview.tsx +++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx @@ -27,6 +27,7 @@ export interface ExpandedImageItem { /** Revoke this owned object URL; other blob URLs belong to the timeline. */ ownsSrc?: boolean; source?: SnapShotSource; + onCopySnapshot?: (() => Promise) | undefined; autoPlay?: boolean; originalUrl?: string; srcFragment?: string; @@ -162,6 +163,7 @@ export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => export function buildExpandedImagePreview( images: ReadonlyArray, selectedImageId: string, + onCopySnapshot?: (id: string) => Promise, ): ExpandedImagePreview | null { const selected = images.find((image) => image.id === selectedImageId); if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) { @@ -202,7 +204,12 @@ export function buildExpandedImagePreview( src: image.src, name: image.name, mimeType: image.mimeType, - ...(image.source?.kind === "snap-shot" ? { source: image.source } : {}), + ...(image.source?.kind === "snap-shot" + ? { + source: image.source, + onCopySnapshot: onCopySnapshot ? () => onCopySnapshot(image.id) : undefined, + } + : {}), })), index: selectedIndex, }; diff --git a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx index 07f16c8794e9..826b335469d0 100644 --- a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx +++ b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx @@ -1,6 +1,6 @@ import type { SnapShotSource } from "@t3tools/contracts"; -import { ImageIcon, TextIcon } from "lucide-react"; -import { Suspense } from "react"; +import { CheckIcon, CopyIcon, ImageIcon, TextIcon } from "lucide-react"; +import { Suspense, useRef, useState } from "react"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; @@ -8,6 +8,10 @@ import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { Button } from "../ui/button"; import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + ANCHORED_COPY_TOAST_TIMEOUT_MS, + showAnchoredCopyErrorToast, +} from "../ui/anchoredCopyToast"; import { HighlightedTokens } from "./HighlightedTokens"; export const SNAP_SHOT_ATTACHMENT_FRAME_CLASS = @@ -71,14 +75,64 @@ function snapShotIncludesAccessibility(source: SnapShotSource): boolean { return Boolean(source.accessibility || source.accessibleText?.trim()); } +export function SnapShotCopyButton({ + onCopy, + side = "top", +}: { + onCopy: () => Promise; + side?: "top" | "right" | "bottom" | "left"; +}) { + const ref = useRef(null); + const [copied, setCopied] = useState(false); + + return ( + + { + event.stopPropagation(); + void onCopy().then( + () => { + setCopied(true); + setTimeout(() => setCopied(false), ANCHORED_COPY_TOAST_TIMEOUT_MS); + }, + (error: unknown) => + showAnchoredCopyErrorToast( + ref, + error instanceof Error ? error : new Error(String(error)), + ), + ); + }} + size="xs" + variant="ghost-muted" + /> + } + > + {copied ? ( + + Copy snapshot + + ); +} + export function SnapShotContentsButton({ source, className, side = "top", + onCopySnapshot, }: { source: SnapShotSource; className?: string; side?: "top" | "right" | "bottom" | "left"; + onCopySnapshot?: (() => Promise) | undefined; }) { const includesAccessibility = snapShotIncludesAccessibility(source); const ContentsIcon = includesAccessibility ? TextIcon : ImageIcon; @@ -111,7 +165,14 @@ export function SnapShotContentsButton({
- Accessibility data +
+ Accessibility data + {onCopySnapshot && ( +
+ +
+ )} +
{accessibilityDetails ? ( Promise) | undefined; className?: string; }) { return ( @@ -157,7 +220,11 @@ export function SnapShotAttachmentDetails({
{source.appName} - +
{source.windowTitle || "Captured window"} diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 163635a9b674..7cd57ed18c0c 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,3 +1,4 @@ +import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { @@ -597,6 +598,25 @@ function UserTimelineRow({ row }: { row: Extract { + const image = userImages.find((candidate) => candidate.id === id); + const record = resolvedContext.records + .map(asKnownContextRecord) + .find((candidate) => candidate?.kind === "image" && candidate.attachmentId === id); + if (!image?.previewUrl || record?.kind !== "image") + throw new Error("Snapshot is no longer available."); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ctx.activeThreadEnvironmentId, messageId: row.message.id }, + records: [{ ...record, ...(image.source ? { source: image.source } : {}) }], + }); + if (!fragment) throw new Error("The snapshot is too large to copy."); + await copySnapshotToClipboard( + image.previewUrl, + formatComposerContextReference(record), + fragment, + ); + }; const onBodyCopyCapture = (event: React.ClipboardEvent) => { if (resolvedContext.records.length === 0 || !event.clipboardData) return; const selection = window.getSelection(); @@ -661,7 +681,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(userImages, image.id); + const preview = buildExpandedImagePreview(userImages, image.id, copySnapshot); if (preview) onImageExpand(preview); }} onOpenFile={onFileOpen} @@ -737,7 +757,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(regularImages, image.id); + const preview = buildExpandedImagePreview(regularImages, image.id, copySnapshot); if (!preview) return; ctx.onImageExpand(preview); }} @@ -772,7 +792,10 @@ function UserTimelineRow({ row }: { row: Extract )} {image.previewUrl && image.source?.kind === "snap-shot" ? ( - + copySnapshot(image.id)} + /> ) : null}
))} diff --git a/apps/web/src/components/chat/copySnapshot.test.ts b/apps/web/src/components/chat/copySnapshot.test.ts new file mode 100644 index 000000000000..9ac7080f7b0f --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.test.ts @@ -0,0 +1,75 @@ +import { ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextClipboardHtml, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { expect, it } from "vite-plus/test"; + +import { copySnapshot } from "./copySnapshot"; + +it.each([false, true])( + "preserves image bytes and snapshot metadata, custom format rejected: %s", + async (rejectCustom) => { + class Item { + constructor(readonly data: Record>) {} + } + let clipboard: Item | undefined; + const write = async ([item]: Item[]) => { + if (rejectCustom && item?.data[COMPOSER_CONTEXT_CLIPBOARD_MIME]) + throw new Error("Unsupported format"); + clipboard = item; + await Promise.all(Object.values(item!.data)); + }; + const originals = { + navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"), + ClipboardItem: Object.getOwnPropertyDescriptor(globalThis, "ClipboardItem"), + }; + using _globals = { + [Symbol.dispose]() { + for (const key of ["navigator", "ClipboardItem"] as const) { + const descriptor = originals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { clipboard: { write } }, + }); + Object.defineProperty(globalThis, "ClipboardItem", { configurable: true, value: Item }); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [ + { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "Snapshot", + attachmentId: "snapshot", + name: "snapshot.png", + mimeType: "image/png", + sizeBytes: 3, + source: { + kind: "snap-shot", + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, + }, + ], + })!; + const image = "data:image/png;base64,AQID"; + await copySnapshot(image, "Snapshot", fragment); + const png = await clipboard!.data["image/png"]!; + expect(png.type).toBe("image/png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual([1, 2, 3]); + expect( + decodeComposerContextClipboardHtml(await (await clipboard!.data["text/html"]!).text()), + ).toEqual(JSON.parse(fragment)); + expect(await (await clipboard!.data["text/plain"]!).text()).toBe("Snapshot"); + }, +); diff --git a/apps/web/src/components/chat/copySnapshot.ts b/apps/web/src/components/chat/copySnapshot.ts new file mode 100644 index 000000000000..118121e75364 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.ts @@ -0,0 +1,33 @@ +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextClipboardHtml, +} from "@t3tools/shared/composerContextClipboard"; + +import { readMediaPng } from "../media/mediaContent"; + +export async function copySnapshot(src: string, text: string, fragment: string): Promise { + if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { + throw new Error("Snapshot copying requires a secure browser connection."); + } + const formats = { + "image/png": readMediaPng(src), + "text/plain": new Blob([text], { type: "text/plain" }), + "text/html": new Blob([encodeComposerContextClipboardHtml(text, fragment)], { + type: "text/html", + }), + }; + // Start writing within the click gesture, before the image fetch or decode completes. + try { + await navigator.clipboard.write([ + new ClipboardItem({ + ...formats, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: new Blob([fragment], { + type: COMPOSER_CONTEXT_CLIPBOARD_MIME, + }), + }), + ]); + } catch { + // HTML carries the same snapshot metadata when custom clipboard formats are unsupported. + await navigator.clipboard.write([new ClipboardItem(formats)]); + } +} diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index e2bf9676b8b6..d48e965895dd 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -48,6 +48,7 @@ function deferred() { it.each([ { kind: "file", edit: "delete" }, { kind: "image", edit: "delete" }, + { kind: "image", edit: "retain" }, { kind: "file", edit: "undo" }, { kind: "file", edit: "retain" }, { kind: "file", edit: "switch" }, @@ -124,7 +125,17 @@ it.each([ const attachment = ( kind === "file" ? { ...attachmentFields, kind: "file" as const } - : { ...attachmentFields, kind: "image" as const } + : { + ...attachmentFields, + kind: "image" as const, + source: { + kind: "snap-shot" as const, + appName: "Finder", + windowTitle: "Downloads", + capturedAt: "2026-01-01T00:00:00.000Z", + accessibleText: "Downloads", + }, + } ) satisfies ComposerContextRecord; const annotation = { version: 1, @@ -182,6 +193,10 @@ it.each([ const draft = store.getComposerDraft(target)!; expect(draft.prompt).toBe(promptRef.current); const attachments = kind === "file" ? draft.files : draft.images; + if (kind === "image" && edit === "retain") + expect(draft.images[0]?.source).toEqual( + attachment.kind === "image" ? attachment.source : undefined, + ); expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 0cc66d6a71d1..265278faec74 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -246,6 +246,7 @@ export function useComposerContextImport(input: { sizeBytes: file.size, previewUrl: URL.createObjectURL(file), file, + ...(record.source ? { source: record.source } : {}), }, ], { diff --git a/packages/contracts/src/composerContext.ts b/packages/contracts/src/composerContext.ts index 982202b05bc3..9884284b3f0d 100644 --- a/packages/contracts/src/composerContext.ts +++ b/packages/contracts/src/composerContext.ts @@ -1,5 +1,7 @@ import * as Schema from "effect/Schema"; +import { SnapShotSource } from "./chatAttachment.ts"; + import { AssistantCitation } from "./assistantCitations.ts"; import { EnvironmentId, @@ -99,6 +101,7 @@ export const ImageContextRecord = Schema.Struct({ ...recordBase, kind: Schema.Literal("image"), ...attachmentBinding, + source: Schema.optional(SnapShotSource), }); export type ImageContextRecord = typeof ImageContextRecord.Type; From acddfae5139ac0bda3300af4440b8f9bbea7a7de Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:40:33 -0800 Subject: [PATCH 009/280] fix(desktop): opening the app refreshes the t3 launcher with Local environment off (#31522) --- apps/desktop/src/app/DesktopApp.test.ts | 422 ++++++++++++++---------- apps/desktop/src/app/DesktopApp.ts | 3 + 2 files changed, 258 insertions(+), 167 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index aca3b4fc7fe6..c35dee1ce2a3 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -54,6 +55,7 @@ import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; import * as DesktopIpc from "../ipc/DesktopIpc.ts"; @@ -72,6 +74,178 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; +interface StubbedDesktop { + readonly localEnvironmentEnabled: boolean; + readonly environment: Partial; + readonly fileSystem: Layer.Layer; + readonly record: (event: string) => Effect.Effect; + readonly windowStarted: Deferred.Deferred; + readonly registerLinuxUrlHandler: Effect.Effect; + readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; + readonly flushRendererHistory?: Effect.Effect; + readonly tokenRequested?: Deferred.Deferred; +} + +const runStubbedDesktop = (stub: StubbedDesktop) => + Effect.gen(function* () { + const quitting = yield* Ref.make(false); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: stub.record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: stub.record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + stateDir: "/isolated/userdata", + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + ...stub.environment, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: stub.localEnvironmentEnabled, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: stub.record("menu"), + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: stub.registerLinuxUrlHandler, + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + createMainIfBackendReady: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: stub.record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed(stub.backends ?? []), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: stub.flushRendererHistory ?? Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + return yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: stub + .record("token") + .pipe( + Effect.andThen( + stub.tokenRequested + ? Deferred.succeed(stub.tokenRequested, undefined) + : Effect.void, + ), + Effect.as("token"), + ), + }), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + stub.fileSystem, + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + }); + it.effect.each([false, true])( "stops backends together before flushing history and cancels Linux registration, stop defect=%s", (stopDefect) => @@ -85,178 +259,42 @@ it.effect.each([false, true])( const releaseStops = yield* Deferred.make(); const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); - const quitting = yield* Ref.make(false); const tokenRequested = yield* Deferred.make(); const events: string[] = []; - const record = (event: string) => - Effect.sync(() => { - events.push(event); - }); - const runApp = DesktopApp.program - .pipe( - Effect.provide(NodeCrypto.layer), - Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { - resolveUserDataPath: Effect.succeed("/isolated/userdata"), - configure: record("identity"), - } as DesktopAppIdentity.DesktopAppIdentity["Service"]), - Effect.provideService(ElectronApp.ElectronApp, { - setPath: () => Effect.void, - whenReady: record("ready"), - } as unknown as ElectronApp.ElectronApp["Service"]), - Effect.provideService(ElectronDialog.ElectronDialog, { - showErrorBox: () => Effect.die("unexpected fatal startup error"), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, { - platform: "linux", - isDevelopment: false, - isPackaged: true, - stateDir: "/isolated/userdata", - configuredBackendPort: Option.some(3773), - defaultDesktopSettings: { serverExposureMode: "local-only" }, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { - linux: null, - linuxPasswordStoreCommandLine: "basic", - }), - Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { - installIntoProcess: Effect.succeed(true), - awaitDiscovery: Effect.succeed(true), - awaitUserShellDiscovery: Effect.succeed(true), - updates: Stream.empty, + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: true, + environment: {}, + fileSystem: FileSystem.layerNoop({}), + record: (event) => + Effect.sync(() => { + events.push(event); }), - Effect.provideService(DesktopAppSettings.DesktopAppSettings, { - load: Effect.void, - get: Effect.succeed({ - localEnvironmentEnabled: true, - serverExposureMode: "local-only", - }), - } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), - Effect.provideService(DesktopLifecycle.DesktopLifecycle, { - register: Effect.void, - relaunch: () => Effect.void, - }), - Effect.provideService(DesktopClerk.DesktopClerk, { - configure: Effect.void, - } as DesktopClerk.DesktopClerk["Service"]), - Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { - selectedStorageBackend: Effect.succeedNone, - } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), - Effect.provideService(PreviewPasskeys.PreviewPasskeys, { - configure: Effect.void, - } as PreviewPasskeys.PreviewPasskeys["Service"]), - Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: record("menu"), - }), - Effect.provideService(DesktopUpdates.DesktopUpdates, { - configure: Effect.void, - } as unknown as DesktopUpdates.DesktopUpdates["Service"]), - Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { - register: Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), - ), - }), - ) - .pipe( - Effect.provideService(ElectronProtocol.ElectronProtocol, { - registerDesktopProtocol: () => Effect.void, - } as unknown as ElectronProtocol.ElectronProtocol["Service"]), - Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { - load: () => Effect.void, - } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, { - initialize: Effect.void, - } as DesktopSnapShot.DesktopSnapShot["Service"]), - Effect.provideService(DesktopState.DesktopState, { - quitting, - } as DesktopState.DesktopState["Service"]), - Effect.provideService(DesktopWindow.DesktopWindow, { - ensureMain: record("window").pipe( - Effect.andThen(Deferred.succeed(windowStarted, undefined)), - ), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Effect.provideService(DesktopBackendPool.DesktopBackendPool, { - primary: Effect.succeed({ - start: record("backend"), - currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), - }), - list: Effect.succeed([ - { - stop: () => - Deferred.succeed(firstStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), - ), - }, - { - stop: () => - Deferred.succeed(secondStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - ), - }, - ]), - } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), - Effect.provideService(DesktopServerExposure.DesktopServerExposure, { - configureFromSettings: () => Effect.succeed({ mode: "local-only" }), - backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), - } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), - Effect.provideService(DesktopWslBackend.DesktopWslBackend, { - reconcile: Effect.void, - } as DesktopWslBackend.DesktopWslBackend["Service"]), - Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, - } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), - Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Deferred.succeed(historyStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseHistory)), - Effect.asVoid, - ), - } as DesktopRendererHistory.DesktopRendererHistory["Service"]), - ); - const app = yield* runApp.pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(BrowserImport.BrowserImport, {}), - Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), - Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), - Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), - Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), - Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), - Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { - getBearerToken: record("token").pipe( - Effect.andThen(Deferred.succeed(tokenRequested, undefined)), - Effect.as("token"), + windowStarted, + tokenRequested, + registerLinuxUrlHandler: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + backends: [ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), ), - }), - Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), - Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), - Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), - Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), - Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), - Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), - Layer.mock(ElectronMenu.ElectronMenu, {}), - Layer.mock(ElectronShell.ElectronShell, {}), - Layer.mock(ElectronTheme.ElectronTheme, {}), - Layer.mock(ElectronWindow.ElectronWindow, {}), - Layer.mock(MacPermissions.MacPermissions, {}), - Layer.mock(PreviewManager.PreviewManager, { - isBrowserPartition: () => { - throw new Error("unexpected browser partition lookup"); - }, - }), - FileSystem.layerNoop({}), - Layer.mock(NetService.NetService, {}), - Path.layer, - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ], + flushRendererHistory: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, ), - Effect.forkScoped, - ); + }); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); yield* Deferred.await(tokenRequested); @@ -283,3 +321,53 @@ it.effect.each([false, true])( assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); + +it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ + path, + baseDir, + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index f69bf965d005..56fe979cf8c6 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; @@ -301,6 +302,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ); if (!settings.localEnvironmentEnabled) { + // The backend config refreshes the launcher when the local environment runs; an update may move the app. + yield* DesktopCliShim.install; if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } From a6f7981abba71a51b299bd0ecbf7577d20660541 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:41:38 -0800 Subject: [PATCH 010/280] fix(pi): ask_user_question single-select questions render as a structured card (#32125) --- .../provider-pi/src/server/adapter.test.ts | 289 ++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 147 ++++++++- 2 files changed, 434 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index ff9f9c22ef97..31d0a70cae48 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4895,6 +4895,295 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("renders an ask_user_question select from the tool call's structured question", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ + type: "tool_execution_start", + toolCallId: "ask-call", + toolName: "ask_user_question", + args: { + questions: [ + { + header: "Area", + question: "Which area should we work on?", + options: [ + { + label: "Docker/Compose", + description: "Review or edit Compose projects", + preview: "services:\n web: {}", + }, + { label: "Home Assistant", description: "Automations, dashboards or YAML" }, + ], + }, + ], + }, + }); + const dockerLine = "1. Docker/Compose — Review or edit Compose projects"; + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-ask", + method: "select", + title: + "[Area] Which area should we work on?\n\n--- 1. Docker/Compose preview ---\nservices:\n web: {}", + options: [ + dockerLine, + "2. Home Assistant — Automations, dashboards or YAML", + "3. Type something.", + ], + }); + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + const question = decodeUserInputQuestions(event.turnItem.questions)[0]; + assert.deepEqual( + { + header: question?.header, + question: question?.question, + options: question?.options.map(({ label, description }) => ({ label, description })), + }, + { + header: "Area", + question: + "Which area should we work on?\n\n--- 1. Docker/Compose preview ---\nservices:\n web: {}", + options: [ + { label: "Docker/Compose", description: "Review or edit Compose projects" }, + { label: "Home Assistant", description: "Automations, dashboards or YAML" }, + ], + }, + ); + yield* runtime.respondToRuntimeRequest({ + requestId: event.turnItem.requestId, + answers: { [question!.id]: question!.options[0]!.value }, + }); + const response = yield* fake.takeRequest("extension_ui_response"); + assert.equal(response["id"], "ui-ask"); + assert.equal(response["value"], dockerLine); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("matches an ask_user_question select to the question with the same full title", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + const options = [ + { label: "Yes", description: "Go ahead" }, + { label: "No", description: "Stop here" }, + ]; + yield* fake.emit({ + type: "tool_execution_start", + toolCallId: "ask-call", + toolName: "ask_user_question", + // Some models JSON-encode `questions`; the extension decodes it before asking. + args: { + questions: JSON.stringify([ + { header: "Deploy", question: "Proceed?", options }, + { header: "Deploy", question: "Proceed? Only for staging?", options }, + ]), + }, + }); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-ask", + method: "select", + title: "[Deploy] Proceed? Only for staging?", + options: ["1. Yes — Go ahead", "2. No — Stop here", "3. Type something."], + }); + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + const question = decodeUserInputQuestions(event.turnItem.questions)[0]; + assert.equal(question?.question, "Proceed? Only for staging?"); + // Option lines that differ from the recorded call keep the raw select. + const unmatchedLines = ["1. Yes — Go", "2. No — Stop here", "3. Type something."]; + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-unmatched", + method: "select", + title: "[Deploy] Proceed?", + options: unmatchedLines, + }); + const unmatched = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if ( + unmatched.type !== "turn_item.updated" || + unmatched.turnItem.type !== "user_input_request" + ) { + return assert.fail("expected a user input request"); + } + const unmatchedQuestion = decodeUserInputQuestions(unmatched.turnItem.questions)[0]; + assert.deepEqual( + { + header: unmatchedQuestion?.header, + question: unmatchedQuestion?.question, + options: unmatchedQuestion?.options.map(({ label, value }) => [label, value]), + }, + { + header: "Question", + question: "[Deploy] Proceed?", + options: unmatchedLines.map((line) => [line, line]), + }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("answers each ask_user_question custom text through its follow-up input", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + const args = { + questions: [ + { + question: "How many replicas?", + options: [ + { label: "One", description: "Single instance" }, + { label: "Three", description: "High availability" }, + ], + }, + ], + }; + // Parallel questionnaires can ask the same question. + yield* fake.emit({ + type: "tool_execution_start", + toolCallId: "ask-call", + toolName: "ask_user_question", + args, + }); + yield* fake.emit({ + type: "tool_execution_start", + toolCallId: "ask-call-parallel", + toolName: "ask_user_question", + args, + }); + const lines = ["1. One — Single instance", "2. Three — High availability"]; + const followUpTitle = `How many replicas?\n\n${lines.join("\n")}\n\nType your answer:`; + const takeWaitingRequest = Effect.fnUntraced(function* () { + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "user_input_request" && + event.turnItem.status === "waiting", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + return event.turnItem; + }); + const answerWithCustomText = Effect.fnUntraced(function* (id: string, text: string) { + yield* fake.emit({ + type: "extension_ui_request", + id, + method: "select", + title: "How many replicas?", + options: [...lines, "3. Type something."], + }); + const request = yield* takeWaitingRequest(); + yield* runtime.respondToRuntimeRequest({ + requestId: request.requestId, + answers: { [request.questions[0]!.id]: text }, + }); + const selectResponse = yield* fake.takeRequest("extension_ui_response"); + assert.equal(selectResponse["value"], "3. Type something."); + }); + // The extension reads a bare number sent as the select's value as that option. + yield* answerWithCustomText("ui-ask", "2"); + yield* answerWithCustomText("ui-ask-parallel", "5"); + // Parallel dialogs can arrive before the follow-up input, including a multi-select of the + // same question, which the extension asks as an input with a non-empty placeholder. + const multiSelectTitle = `How many replicas?\n\n${lines.join("\n")}\n\nEnter the numbers of all that apply.`; + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-multi", + method: "input", + title: multiSelectTitle, + placeholder: "1,3; custom answer", + }); + // Another extension's blank-placeholder input that only shares the question is asked. + const unrelatedTitle = "How many replicas?\n\nEnter the release note:"; + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-unrelated", + method: "input", + title: unrelatedTitle, + placeholder: "", + }); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-other", + method: "input", + title: "Anything else?", + }); + assert.equal((yield* takeWaitingRequest()).title, multiSelectTitle); + assert.equal((yield* takeWaitingRequest()).title, unrelatedTitle); + assert.equal((yield* takeWaitingRequest()).title, "Anything else?"); + for (const [id, value] of [ + ["ui-custom", "2"], + ["ui-custom-parallel", "5"], + ]) { + yield* fake.emit({ + type: "extension_ui_request", + id, + method: "input", + title: followUpTitle, + placeholder: "", + }); + const inputResponse = yield* fake.takeRequest("extension_ui_response"); + assert.deepEqual({ id: inputResponse["id"], value: inputResponse["value"] }, { id, value }); + } + // An answer staged when the turn ends is dropped, so a later matching input is asked. + yield* answerWithCustomText("ui-ask-late", "7"); + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "agent_settled" }); + yield* takeEvent((event) => event.type === "turn.terminal"); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-custom-late", + method: "input", + title: followUpTitle, + placeholder: "", + }); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-after", + method: "input", + title: "Anything else?", + }); + assert.equal((yield* takeWaitingRequest()).title, followUpTitle); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["Which database?\n1. Postgres\n2. Type something.\nType your answer:", " "])( "asks an input dialog's title when its placeholder is blank, with title '%s'", (title) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 6694623d9888..418db7219cb9 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -409,6 +409,17 @@ interface PendingPiPrompt { runtimeRequest: OrchestrationV2RuntimeRequest; readonly node: OrchestrationV2ExecutionNode; readonly turnItem: OrchestrationV2TurnItem; + readonly customAnswerRoute: PiCustomAnswerRoute | undefined; +} + +/** + * The ask_user_question extension misreads typed text sent as a select value, so a custom answer + * picks the select's last "Type something." line and answers the input dialog that follows. + */ +interface PiCustomAnswerRoute { + readonly lines: ReadonlyArray; + readonly sentinel: string; + readonly followUpTitlePrefix: string; } function piApprovalRequestKind(title: string): "command" | "file-change" { @@ -601,6 +612,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ProviderAdapter.ProviderAdapterV2Error | Cause.Done >(); const pendingPrompts = new Map(); + // Custom answers waiting for their ask_user_question follow-up input, keyed by title prefix. + // FIFO per prefix: the extension asks each follow-up right after its own select is answered. + const customAnswerFollowUps = new Map(); const sessionApprovals = new Set(); // Async pi-subagents runs launched in this session, by async id, until they settle. const piAsyncRuns = new Map< @@ -1685,6 +1699,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const pending = Array.from(pendingPrompts.values()); pendingPrompts.clear(); + customAnswerFollowUps.clear(); yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), { discard: true, }); @@ -1777,6 +1792,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } if (nativeRequestId === undefined) return; + // The extension's follow-up input has an empty placeholder; its multi-select input does not. + const inputTitle = + method === "input" && event["placeholder"] === "" + ? (recordString(event, "title") ?? "") + : ""; + const followUpPrefix = Array.from(customAnswerFollowUps.keys()) + .filter((prefix) => inputTitle.startsWith(prefix)) + .reduce( + (longest, prefix) => (prefix.length > (longest?.length ?? -1) ? prefix : longest), + undefined, + ); + if (followUpPrefix !== undefined) { + const queued = customAnswerFollowUps.get(followUpPrefix) ?? []; + const value = queued.shift() ?? ""; + if (queued.length === 0) customAnswerFollowUps.delete(followUpPrefix); + yield* connection.send({ type: "extension_ui_response", id: nativeRequestId, value }); + return; + } const approvalTitle = recordString(event, "title") ?? ""; const approvalKey = `${approvalTitle.length}:${approvalTitle}${recordString(event, "message") ?? ""}`; if (method === "confirm" && sessionApprovals.has(approvalKey)) { @@ -1851,6 +1884,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( completedAt: null, updatedAt: createdAt, }; + const askUser = + method === "select" && turn !== null + ? piAskUserSingleSelectQuestion(nativeRequestId, title, event, turn.toolArgs) + : undefined; const turnItem: OrchestrationV2TurnItem = method === "confirm" ? { @@ -1864,7 +1901,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...itemBase, type: "user_input_request", requestId, - questions: [piQuestion(nativeRequestId, method, title, event)], + questions: [askUser?.question ?? piQuestion(nativeRequestId, method, title, event)], }; const pending: PendingPiPrompt = { nativeRequestId, @@ -1876,6 +1913,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( runtimeRequest, node, turnItem, + customAnswerRoute: askUser?.customAnswerRoute, }; pendingPrompts.set(String(requestId), pending); yield* emit({ @@ -3575,7 +3613,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( `Pi extension request ${requestInput.requestId} has expired`, ); } - const response = piUiResponse(pending, requestInput.decision, requestInput.answers); + let response = piUiResponse(pending, requestInput.decision, requestInput.answers); + const route = pending.customAnswerRoute; + if ( + route !== undefined && + typeof response["value"] === "string" && + response["value"].trim().length > 0 && + !route.lines.includes(response["value"]) + ) { + customAnswerFollowUps.set(route.followUpTitlePrefix, [ + ...(customAnswerFollowUps.get(route.followUpTitlePrefix) ?? []), + response["value"], + ]); + response = { value: route.sentinel }; + } yield* connection.send({ type: "extension_ui_response", id: pending.nativeRequestId, @@ -4170,6 +4221,98 @@ function piQuestion( }; } +/** The extension normalizes line terminators in each question field before building the dialog. */ +const rpivField = (input: unknown, key: string) => + recordString(input, key)?.replace(/\r\n/g, "\n").replace(/\r/g, ""); + +const rpivOptionLine = (option: unknown, index: number) => + // oxlint-disable-next-line t3code/no-em-dash-copy -- Matches the extension's option line format. + `${index + 1}. ${rpivField(option, "label")} — ${rpivField(option, "description")}`; + +/** The extension folds option previews into the select title, the only place clients show them. */ +const rpivPreviewBlock = (options: ReadonlyArray) => { + const blocks = options.flatMap((option, index) => { + const preview = rpivField(option, "preview"); + return preview + ? [`--- ${index + 1}. ${rpivField(option, "label")} preview ---\n${preview.slice(0, 600)}`] + : []; + }); + return blocks.length > 0 ? `\n\n${blocks.join("\n\n")}` : ""; +}; + +/** Mirrors the extension's `prepareQuestionArguments`: some models JSON-encode nested args. */ +const rpivDecoded = (value: unknown, isShape: (parsed: unknown) => boolean) => { + if (typeof value !== "string") return value; + try { + const parsed: unknown = JSON.parse(value); + return isShape(parsed) ? parsed : value; + } catch { + return value; + } +}; + +/** + * @juicesharp/rpiv-ask-user-question asks a single-select question over RPC as a select of + * "N. label — description" lines plus a trailing "Type something." entry. Rebuild the question + * from the tool call's arguments; each option answers with its original line, which the extension + * maps back to that option. + */ +function piAskUserSingleSelectQuestion( + questionId: string, + title: string, + event: PiRpcRecord, + toolArgs: ReadonlyMap, +): + | { question: OrchestrationV2UserInputQuestion; customAnswerRoute: PiCustomAnswerRoute } + | undefined { + const lines = event["options"]; + if (!Array.isArray(lines) || lines.length < 2) return undefined; + const sentinel = lines.at(-1); + if (typeof sentinel !== "string") return undefined; + for (const args of toolArgs.values()) { + const questions = rpivDecoded(recordField(args, "questions"), Array.isArray); + if (!Array.isArray(questions)) continue; + for (const entry of questions) { + const question = rpivDecoded(entry, Predicate.isObject); + const text = rpivField(question, "question"); + const header = rpivField(question, "header"); + if (recordField(question, "multiSelect") === true || !text?.trim()) continue; + const prefix = header ? `[${header}] ` : ""; + if (!title.startsWith(`${prefix}${text}`)) continue; + const encodedOptions = rpivDecoded(recordField(question, "options"), Array.isArray); + if (!Array.isArray(encodedOptions) || encodedOptions.length !== lines.length - 1) continue; + const options = encodedOptions.map((option) => rpivDecoded(option, Predicate.isObject)); + const body = `${text}${rpivPreviewBlock(options)}`; + if (title !== `${prefix}${body}`) continue; + if (!options.every((option, index) => lines[index] === rpivOptionLine(option, index))) { + continue; + } + return { + question: { + id: questionId, + header: header?.trim() || "Question", + question: body.trim(), + options: options.map((option, index) => { + const label = rpivField(option, "label")?.trim() || `Option ${index + 1}`; + return { + label, + description: rpivField(option, "description")?.trim() || label, + value: rpivOptionLine(option, index), + }; + }), + }, + // The follow-up repeats the option lines; only its trailing instruction is localized. + customAnswerRoute: { + lines, + sentinel, + followUpTitlePrefix: `${prefix}${text}\n\n${lines.slice(0, -1).join("\n")}\n\n`, + }, + }; + } + } + return undefined; +} + function piUiResponse( pending: PendingPiPrompt, decision: ProviderApprovalDecision | undefined, From a10f9e41d378de696f1bb2f1c69580c5df59af18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:42:44 -0800 Subject: [PATCH 011/280] fix(server): pull request links whose reads keep failing back off instead of re-reading every minute (#31969) --- .../PullRequestSyncReactor.test.ts | 88 +++++++++++++++++++ .../PullRequestSyncReactor.ts | 19 +++- 2 files changed, 106 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts index bb0b3380c38c..4cb350a380a8 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts @@ -325,6 +325,24 @@ const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* ( yield* reactor.drain; }); +const sweepFor = Effect.fn("sweepPullRequestSyncHarnessFor")(function* ( + fixture: Harness, + reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], + minutes: number, +) { + for (let minute = 0; minute < minutes; minute++) yield* sweepAgain(fixture, reactor); +}); + +const failingGitLabLink = makeLink(13, null, { + host: "gitlab.com", + url: "https://gitlab.com/owner/repository/-/merge_requests/13", +}); + +const gitLabCliFailure = new PullRequestOperationError({ + operation: "summary", + detail: "GitLab CLI command failed", +}); + function runUpdated( threadId: ThreadId, status: OrchestrationV2Run["status"], @@ -1839,6 +1857,76 @@ describe("PullRequestSyncReactor", () => { }), ); + it.effect( + "caps the failed-read backoff at the slow cadence and restarts it after a success", + () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const failing = yield* Ref.make(true); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), + summary: (input) => + Ref.get(failing).pipe( + Effect.flatMap((fails) => + fails ? Effect.fail(gitLabCliFailure) : Effect.succeed(makeSummary(input)), + ), + ), + }); + yield* Effect.gen(function* () { + const reactor = yield* startAndSweep(fixture); + const readMinutes = [0]; + const sweepMinutes = Effect.fnUntraced(function* (from: number, to: number) { + for (let minute = from; minute <= to; minute++) { + const before = (yield* Ref.get(fixture.summaryCalls)).length; + yield* sweepAgain(fixture, reactor); + if ((yield* Ref.get(fixture.summaryCalls)).length > before) + readMinutes.push(minute); + } + }); + + yield* sweepMinutes(1, 60); + assert.deepStrictEqual(readMinutes, [0, 1, 3, 7, 15, 30, 45, 60]); + + yield* Ref.set(failing, false); + yield* sweepMinutes(61, 75); + yield* Ref.set(failing, true); + readMinutes.length = 0; + yield* sweepMinutes(76, 80); + assert.deepStrictEqual(readMinutes, [76, 77, 79]); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + + it.effect("reads a backed-off link at once when a refresh asks, then keeps backing off", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), + summary: () => Effect.fail(gitLabCliFailure), + }); + yield* Effect.gen(function* () { + const reactor = yield* startAndSweep(fixture); + yield* sweepFor(fixture, reactor, 4); + const backedOffReads = (yield* Ref.get(fixture.summaryCalls)).length; + + yield* reactor.requestSync(failingGitLabLink); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); + + // The refresh failed at minute 4 with the backoff doubled to 8 minutes. + yield* sweepFor(fixture, reactor, 7); + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); + yield* sweepAgain(fixture, reactor); + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 2); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + it.effect.each([ "gh pr merge 7 --squash 2>&1 | tail -3", "cafe pr merge 7 --squash", diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index 96f0be4e59dc..d962ee8f672d 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -48,6 +48,8 @@ export const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000; // A pull request closed this long ago is rarely reopened, so the sweep stops reading it, as it // does merged ones. A reader that sees it open, or a requested refresh, still reads it at once. const CLOSED_FINAL_AFTER_MS = 24 * 60 * 60 * 1_000; +// A link whose host read failed waits a sweep, then twice as long after each further failure. +const FAILED_READ_BACKOFF_MS = 60 * 1_000; const isChangeRequestCloseCommand = (command: string) => sourceControlDefinitions.definitions.some( @@ -369,6 +371,7 @@ export const make = Effect.gen(function* () { // linking dozens of pull requests) is read together and shares the summary batches. let requestedSweepQueued = false; const retryStacks = new Set(); + const failedReads = new Map(); // Group keys the host answered not-found for, or this server cannot read (no CLI, signed out, // unsupported host); they are read on the slow cadence until a read succeeds. const missing = new Set(); @@ -376,6 +379,7 @@ export const make = Effect.gen(function* () { const pausedUntil = new Map(); const isDue = (key: string, entries: ReadonlyArray, nowMs: number): boolean => { + if ((failedReads.get(key)?.retryAtMs ?? 0) > nowMs) return false; if (requested.has(key)) return true; const active = entries.filter((entry) => isUnsettled(entry.thread)); if (active.length === 0) return false; @@ -425,12 +429,17 @@ export const make = Effect.gen(function* () { // A host-level refresh reaches every project, each retaining its own pending retry. for (const [key, entries] of groups) { - if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key); + if (!pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) continue; + requested.add(key); + // A new request reads at once; a failure after it backs off further, not from the start. + const failed = failedReads.get(key); + if (failed !== undefined) failedReads.set(key, { ...failed, retryAtMs: nowMs }); } pendingRequests.clear(); for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key); for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key); + for (const key of failedReads.keys()) if (!groups.has(key)) failedReads.delete(key); for (const key of missing) if (!groups.has(key)) missing.delete(key); for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key); @@ -599,6 +608,7 @@ export const make = Effect.gen(function* () { } // The host answered, so the cadence clock ticks even if a dispatch below is rejected. lastSyncedAt.set(key, nowMs); + failedReads.delete(key); requested.delete(key); yield* Effect.forEach( entries, @@ -624,6 +634,13 @@ export const make = Effect.gen(function* () { const retryAt = rateLimitRetryAt(cause); if (retryAt !== undefined) { pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0)); + } else { + const previous = failedReads.get(key); + const backoffMs = + previous === undefined + ? FAILED_READ_BACKOFF_MS + : Math.min(previous.backoffMs * 2, SLOW_SYNC_INTERVAL_MS); + failedReads.set(key, { retryAtMs: nowMs + backoffMs, backoffMs }); } const reason = skipReason(cause); const skip = skips.get(reason); From c24255826be5aabb0f32ee18f6ac7dec0b3f1347 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 13:45:07 -0800 Subject: [PATCH 012/280] feat(web): dictation keeps recording into its thread when you switch away (#35761) Co-authored-by: Claude Opus 5.5 --- .../components/AppRouteModal.browser.test.tsx | 2 + apps/web/src/components/AppRouteModal.tsx | 2 + apps/web/src/components/ThreadRouteView.tsx | 6 +- apps/web/src/components/chat/ChatComposer.tsx | 30 +- .../components/chat/ComposerSpeechButton.tsx | 17 +- .../chat/GlobalVoiceInputIndicator.tsx | 52 +++ .../src/components/chat/backgroundThread.ts | 3 + .../VoiceSettingsPanel.browser.test.tsx | 1 + apps/web/src/composerDraftStore.ts | 21 + apps/web/src/routes/_chat.tsx | 2 + ...useEnvironmentSpeechInput.browser.test.tsx | 81 +++- .../src/speech/useEnvironmentSpeechInput.ts | 320 +++++-------- apps/web/src/speech/voiceInputSession.ts | 424 ++++++++++++++++++ 13 files changed, 755 insertions(+), 206 deletions(-) create mode 100644 apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx create mode 100644 apps/web/src/speech/voiceInputSession.ts diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index 004e07744e22..c0864d31c178 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -5,6 +5,8 @@ import { render } from "../../test/render"; import { useCommitOnBlur } from "../hooks/useCommitOnBlur"; import { AppRouteModal } from "./AppRouteModal"; +vi.mock("./chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); + function CommitOnBlurField({ onCommit }: { onCommit: (next: string) => void }) { return ; } diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 0c8a8a670d2f..f4cde43a8ccc 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -4,6 +4,7 @@ import { useRef, useState, type CSSProperties, type ReactNode } from "react"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; import { useCloseAppModal } from "./sidebar/mainAppLocation"; +import { GlobalVoiceInputIndicator } from "./chat/GlobalVoiceInputIndicator"; import { Button } from "./ui/button"; import { DialogBackdrop } from "./ui/dialog"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; @@ -89,6 +90,7 @@ export function AppRouteModal({ label, children }: { label: string; children: Re className="absolute inset-x-0 top-0 hidden h-(--app-modal-titlebar-height) [-webkit-app-region:drag] max-sm:block" /> {children} + diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53..5217b068f9a3 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -8,7 +8,7 @@ import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; -import { BackgroundThreadContext } from "./chat/backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -229,7 +229,9 @@ export function ThreadRouteView({ className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh" inert={background} > - {view} + + {view} + {background ? null : redirect} ); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8fb98edc1446..69250e47b89c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -4,7 +4,7 @@ import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion"; import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; -import { BackgroundThreadContext } from "./backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { resolveCompatibleRuntimeMode, runtimeModeConfig, @@ -107,9 +107,12 @@ import { composerFileNeedsReattach, composerDraftHasUserContent, composerTargetKey, + readComposerDraftPrompt, + resolveLiveComposerDraftTarget, useComposerDraftStore, useComposerThreadDraft, } from "../../composerDraftStore"; +import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../../threadRoutes"; import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; @@ -1052,6 +1055,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const backgroundThread = use(BackgroundThreadContext); + const hiddenThread = use(HiddenThreadContext); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to keydown, window blur and the desktop paste-as-text event to arm plain-text paste useEffect(() => { // A background composer listens on its own form, so it never hears the main composer's keys. @@ -1846,6 +1850,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) projectName, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, + label: activeThread?.title ?? null, + presented: !hiddenThread, + // A question's answer lives only in this composer, so only the thread draft outlives it. + persistentDraft: questionAttachmentTarget + ? undefined + : { + readStoredText: () => readComposerDraftPrompt(composerDraftTarget), + commitStoredText: (text) => { + const live = resolveLiveComposerDraftTarget(composerDraftTarget); + if (live !== null) setComposerDraftPrompt(live, text); + }, + // The route, not the draft target: a queued-message edit has a draft id but no route. + open: () => + void (routeKind === "draft" && typeof composerDraftTarget === "string" + ? navigate({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(composerDraftTarget), + }) + : navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(routeThreadRef), + })), + }, readDraft: () => { const snapshot = readComposerSnapshot(); return { @@ -3828,6 +3855,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) finishShortcutLabel={dictationShortcutLabel} cancelShortcutLabel="Esc" level={speechInput.level} + recordingStartedAt={speechInput.recordingStartedAt} disabled={dictationDisabled} onStart={() => void speechInput.start()} onStop={() => void speechInput.stop()} diff --git a/apps/web/src/components/chat/ComposerSpeechButton.tsx b/apps/web/src/components/chat/ComposerSpeechButton.tsx index ca9ef2a278ad..9f7eb4f37ab7 100644 --- a/apps/web/src/components/chat/ComposerSpeechButton.tsx +++ b/apps/web/src/components/chat/ComposerSpeechButton.tsx @@ -43,18 +43,25 @@ function formatElapsed(seconds: number) { return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; } -function RecordingStatus(props: { level: number; recordingLimitSeconds?: number | undefined }) { - const [elapsedSeconds, setElapsedSeconds] = useState(0); +function RecordingStatus(props: { + level: number; + recordingStartedAt?: number | null | undefined; + recordingLimitSeconds?: number | undefined; +}) { + const { recordingStartedAt } = props; + const [elapsedSeconds, setElapsedSeconds] = useState(() => + recordingStartedAt ? Math.max(0, Math.floor((Date.now() - recordingStartedAt) / 1_000)) : 0, + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the timer displaying the native recording duration useEffect(() => { - const startedAt = Date.now(); + const startedAt = recordingStartedAt ?? Date.now(); const timer = window.setInterval( () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1_000)), 250, ); return () => window.clearInterval(timer); - }, []); + }, [recordingStartedAt]); return ( <> @@ -125,6 +132,7 @@ export function ComposerSpeechRecordingPill(props: { finishShortcutLabel?: string | null; cancelShortcutLabel?: string | null; level: number; + recordingStartedAt?: number | null | undefined; recordingLimitSeconds?: number | undefined; /** Compact matches the `xs` buttons beside text-field editors. */ size?: "default" | "compact"; @@ -181,6 +189,7 @@ export function ComposerSpeechRecordingPill(props: { {recording ? ( ) : ( diff --git a/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx new file mode 100644 index 000000000000..3bc724fe1962 --- /dev/null +++ b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx @@ -0,0 +1,52 @@ +import { useVoiceTranscriptionDestination } from "../../speech/useEnvironmentSpeechInput"; +import { + useRetainedVoiceInputSession, + useVoiceInputSessionActivity, + useVoiceInputSessionSnapshot, + useVoiceOwnerPresented, +} from "../../speech/voiceInputSession"; +import { Button } from "../ui/button"; +import { ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; + +/** + * Keeps the chosen destination's dictation alive across navigation and, while the draft it + * records into is off screen, shows it so it can be finished, cancelled, or returned to. + */ +export function GlobalVoiceInputIndicator({ hidden = false }: { hidden?: boolean }) { + const { prepared, grantId, cloudProvider, cloudModel } = useVoiceTranscriptionDestination(); + const session = useRetainedVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel }); + const { state, target, recordingStartedAt } = useVoiceInputSessionSnapshot(session); + const presented = useVoiceOwnerPresented(target?.ownerKey ?? null); + const { level } = useVoiceInputSessionActivity( + hidden || presented ? null : session, + target?.ownerKey ?? null, + ); + if (hidden || !session || !target || state.phase === "idle" || presented) return null; + + return ( +
+
+ + void session.start(target)} + onStop={() => void session.stop()} + onCancel={() => session.cancel()} + onSkipPostProcessing={() => session.skipPostProcessing()} + /> +
+
+ ); +} diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.ts index b3dfee09a663..e402bc5e6216 100644 --- a/apps/web/src/components/chat/backgroundThread.ts +++ b/apps/web/src/components/chat/backgroundThread.ts @@ -5,3 +5,6 @@ import { createContext } from "react"; * parent's panel; its global shortcuts and listeners stand down. */ export const BackgroundThreadContext = createContext(false); + +/** True only for a thread kept mounted out of sight under Settings or Usage. */ +export const HiddenThreadContext = createContext(false); diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx index 4c8172333ff9..c0107483461c 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx @@ -328,6 +328,7 @@ it("tests the selected model after download and preserves its transcript across state: { phase: "idle", error: null, errorAction: null }, preview: null, level: 0, + recordingStartedAt: null, preparing: false, blocksSubmission: false, freezesEditor: false, diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 4066715c53b2..3c64aa0f6581 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -1660,6 +1660,27 @@ function getComposerDraftState( return state.draftsByThreadKey[threadKey] ?? null; } +/** Where a draft lives now: its thread once promoted, or null once it was discarded. */ +export function resolveLiveComposerDraftTarget( + target: ComposerThreadTarget, +): ComposerThreadTarget | null { + if (typeof target !== "string") return target; + const state = composerDraftStore.getState(); + const promoted = state.promotedDraftRedirects[target]; + if (promoted) return promoted; + return state.draftThreadsByThreadKey[target] || state.draftsByThreadKey[target] ? target : null; +} + +/** The stored prompt for a target, empty when it has no draft, or null when the target is gone. */ +export function readComposerDraftPrompt(target: ComposerThreadTarget): string | null { + const live = resolveLiveComposerDraftTarget(target); + if (live === null) return null; + const state = composerDraftStore.getState(); + const threadKey = resolveComposerDraftKey(state, live); + if (!threadKey) return null; + return state.draftsByThreadKey[threadKey]?.prompt ?? ""; +} + function draftThreadHasOpenPreview(draftThread: DraftThreadState | undefined): boolean { if (draftThread === undefined) return false; const ref = scopeThreadRef(draftThread.environmentId, draftThread.threadId); diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index ad04d04d2949..c65ed390288f 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -1,6 +1,7 @@ import { Outlet, createFileRoute, redirect } from "@tanstack/react-router"; import { ThreadRouteView } from "../components/ThreadRouteView"; +import { GlobalVoiceInputIndicator } from "../components/chat/GlobalVoiceInputIndicator"; import { isAppModalPage } from "../components/sidebar/mainAppLocation"; import { SidebarInset } from "../components/ui/sidebar"; import { resolveThreadRouteTarget } from "../threadRoutes"; @@ -24,6 +25,7 @@ function ChatRouteLayout() { )} {modalOpen ? : null} +