From 61f09a78a7a9e71df6d983c0cda4ab53182806cb Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:15:29 -0300 Subject: [PATCH 01/87] docs(operations): guide migration to an independent fork --- docs/operations/standalone-migration.md | 138 ++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/operations/standalone-migration.md diff --git a/docs/operations/standalone-migration.md b/docs/operations/standalone-migration.md new file mode 100644 index 0000000000000..cf49c526d53aa --- /dev/null +++ b/docs/operations/standalone-migration.md @@ -0,0 +1,138 @@ +# Running a fork without T3-operated services + +This runbook is for moving an existing installation to a fork whose environment server, web app, +desktop app, and mobile app are operated by their owner. It separates what works with direct +pairing today from work still needed for a strict no-T3-network build. It is not a deployment +recipe for the T3 Connect relay. + +## Choose the boundary + +The **environment** is the server on the machine that owns the projects, provider credentials, +files, and database. Clients connect to it over HTTP and WebSocket. The environment can run on a +laptop, desktop, or VPS. Moving only the web UI to a VPS does not move projects from a laptop to +that VPS. See [remote architecture](../internals/remote.md). +On a different machine, the saved absolute project paths and provider credentials must also be +made available there; copying the database alone does not move them. A copied home retains the +environment identity, so never run both copies online at the same time. + +Direct pairing over LAN, a private VPN such as Tailscale, or SSH does not require T3 Connect. A +public browser origin needs a reachable HTTPS address for the environment; hosting the web app +alone does not provide one. See [remote access](../user/remote-access.md#pair-over-a-lan-or-private-network). + +There are two distinct milestones: + +1. **Independent core:** run the fork's environment and use direct routes. Do not sign in to or + link T3 Connect. Projects and agent turns then have no T3 relay in their request path. +2. **Strictly independent clients:** build and distribute the web, desktop, CLI, and mobile clients + with no T3-operated endpoint for telemetry, links, updates, or diagnostics. Official clients do + not meet this milestone merely because they connect to a forked environment. + +Provider subscriptions and their CLIs remain external services chosen by the operator. This +runbook addresses T3-operated services, not those provider services. + +## Inventory before migration + +Record the exact version and release channel of the installed CLI, desktop app, and each mobile +app, plus the fork commit used for the replacement. On the host, `t3 --version`, `t3 status`, and +`t3 service status` identify the CLI and background service. Read the desktop and mobile versions +from their About screens. Check whether desktop and the background service share a T3 home, +whether T3 Connect is linked, which devices use it, and which projects and provider credentials +must survive. Record the routes each client uses; a T3 Connect route must be replaced with a +direct route before cutover. + +Do not run the official server and the fork against the same T3 home. In particular, never start +a development server against a live `~/.t3/userdata`. The database can migrate forward when a +newer server starts, so a version rollback must use a backup made before that start. + +## Prepare an isolated replacement + +1. Pin a fork commit and build with the Node version required by its root `package.json`. Follow + [development setup](./development.md#first-checkout) and the + [source build example](../user/install.md#intel-macs). Keep a local copy of the build and its + commit SHA. A source build can run the server with `node apps/server/dist/bin.mjs`; it does not + use the official `t3` launcher or its update path. +2. Give the replacement its own T3 home and a copy of data. A staging copy made while the + official server is running must use a consistent SQLite snapshot; the dev database migration + tool intentionally drops tasks and links, so it is a test fixture, not a complete migration. + For the final copy, stop the official desktop and service, confirm no server still owns the + database, then copy the entire userdata directory, secrets, settings, and any needed + `service.env` into the new home. Keep the original home and an offline backup unchanged. +3. Run the forked environment with product telemetry disabled: + + ```dotenv + T3CODE_TELEMETRY_ENABLED=false + T3CODE_OTEL_SDK_DISABLED=true + ``` + + Set these in the process environment or the fork's `service.env` before it starts. The server + otherwise defaults product telemetry to `https://ingest.t3.codes`; see + [telemetry](../user/telemetry.md) and [service environment](../user/background-service.md#configure-the-service-environment). + Turn off provider update checks in the server settings until the model manifest is served by + the fork: the current check fetches `model-manifest.json` from `pingdotgg/t3code` on GitHub. + +4. Give the environment a private or HTTPS route that the receiving device can reach. Pair each + client directly with a new one-time code; do not reuse T3 Connect sessions. Test project + listing, a provider turn, reconnect after restart, and the permissions of each paired client. + Keep the first test on isolated data, then repeat after the final offline copy. + +## Replace the client distributions + +The repository's `.env.example` contains the production T3 relay URL. Do not use that value in +fork builds that are meant to run without T3 Connect. + +| Surface | Required for strict independence | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Web | Host the fork's static app at an HTTPS origin you control. Set `VITE_HOSTED_APP_URL` for the web build and `T3CODE_HOSTED_APP_URL` for server-generated links and approval pages. Leave relay and Clerk build values unset if T3 Connect is unused. Configure the browser's own tracing values to your receiver or leave them unset. Do not use `app.t3.codes` for the final acceptance test. | +| Desktop | Build and sign the fork's app under an identity you control. Disable automatic updates with `T3CODE_DISABLE_AUTO_UPDATE=true` until a feed you operate is available, or set the managed policy's `updates.feedUrl` to that feed. The packaged `app-update.yml` otherwise names the upstream release feed. Check fallback download and support links in the UI. | +| CLI and SSH hosts | Distribute the fork's server/CLI archive with its checksums. `T3CODE_RELEASE_BASE_URL` or a managed update mirror can redirect archive downloads, but the ordinary `t3 update` release-index path still refers to the upstream repository. Do not use `t3 update`, `npx t3`, the official install scripts, or desktop-managed SSH installation as a fork delivery mechanism until their full release path is redirected and tested. | +| Mobile | Build and distribute a forked iOS/Android app with your own signing, identifiers, and deep-link configuration. Leave `T3CODE_RELAY_URL`, Clerk, and OTLP tracing values unset for direct-only use. The official mobile binaries can still send crash reports or relay traces to T3-operated services even when they connect directly. Re-pair the new app to each environment; verify what local client state transfers before removing the official app. | + +The [release runbook](./release.md) describes the upstream signing, archive, and update-feed +formats. Reusing its workflow in a fork requires replacing upstream credentials, domains, +distribution destinations, and release ownership; a fork checkout alone does not change them. + +## Remaining network dependencies to close in the fork + +These are implementation tasks, not settings that the current checkout has verified end to end: + +- **Model manifest:** make the refresh URL configurable or bundle-only. Disabling provider update + checks prevents the regular fetch but also stops new compatibility information. +- **Updates and installers:** make the CLI release index, desktop feed, npm launcher, installer + scripts, and SSH runtime downloads use the fork's release source. Until then, keep automatic + updates off and use controlled builds. +- **Links and fallbacks:** audit default `app.t3.codes`, `t3.codes` download/legal links, issue + links, MCP approval redirects, prompt/thread links, and crash recovery. Configure the available + hosted-app origins and replace remaining hard-coded fallbacks where they can be reached. +- **Telemetry and diagnostics:** verify that the server, desktop, web, and mobile builds have no + T3 ingest, relay tracing, or mobile Observe endpoint. Server opt-out alone does not control + separate browser or mobile clients. +- **T3 Connect replacement, if required:** the relay source is in `infra/relay`, but its current + deployment uses Clerk, Cloudflare, PlanetScale, and optional APNs/FCM. Operating it and + rebuilding every client for its URL is a separate project. Direct pairing avoids this entire + control plane if account-based discovery, managed tunnels, and relay notifications are not + required. + +Do not call the fork strictly independent until these reachable paths are either replaced, +disabled, or shown unreachable by an egress test. A source search is an inventory, not proof of +runtime behavior. + +## Cutover and rollback + +1. Back up the official home after stopping every official server that uses it. Preserve the + backup's permissions and protect its tokens and secrets. Do not symlink a live home into the + fork. Start the fork from a copy, not from the original. +2. Confirm the fork opens the copied projects and threads, starts a new turn, and can reconnect + from each own-build client using direct pairing. Verify scheduled tasks and remote links + explicitly: the dev migration tool drops them, while a complete offline copy retains state + whose external effects must be reviewed before enabling it. +3. Disable the old service's startup and stop using the official mobile and hosted web clients. + Only after the fork has passed the acceptance checks should its service be made persistent. +4. To roll back, stop the fork, restore or reopen the untouched pre-migration official home with + the original official version, and re-enable its service. Never point an older official build + at data already migrated by the fork. + +For acceptance, capture the fork commit and client versions, a successful direct reconnect from +web, desktop, and mobile, and outbound DNS/proxy logs while pairing, starting a turn, opening +links, and checking updates. The logs should show no request to T3-operated domains or upstream +release/model-manifest endpoints. Check again after every new build; embedded endpoints differ +across clients and release channels. From 08fbbe95c03bbfa608685501f5af33a0986344b8 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:16:02 -0300 Subject: [PATCH 02/87] fix(server): MCP OAuth grants no more than the client's requested scope An MCP client that asked for `orchestration:read` alone could still be approved for operate or full access, and `scopes_supported` omitted the full-access scopes clients commonly request. The authorization request now reads `scope`, rejects unknown scopes, and caps the approval (and the consent page's choices) at the broadest level the client named in full. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/McpOAuth.test.ts | 103 ++++++++++++++++++ apps/server/src/auth/McpOAuth.ts | 32 +++++- apps/server/src/auth/mcpOAuthHttp.ts | 8 +- .../components/auth/ConnectAgentSurface.tsx | 20 +++- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + docs/internals/environment-auth.md | 5 +- docs/user/outside-agents.md | 5 + packages/contracts/src/auth.ts | 24 ++++ 17 files changed, 196 insertions(+), 11 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..658326f0fee6c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -210,6 +210,12 @@ it.effect("derives discovery metadata from the origin the client reached", () => token_endpoint: `${ORIGIN}/oauth/mcp/token`, registration_endpoint: `${ORIGIN}/oauth/mcp/register`, code_challenge_methods_supported: ["S256"], + scopes_supported: [ + "orchestration:read", + "orchestration:operate", + "settings:write", + "source-control:write", + ], }); }), ), @@ -400,6 +406,103 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", () ), ); +it.live("an explicit scope caps the grant at the access level it names", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const admin = `Bearer ${(yield* auth.issueSession({ scopes: [...AuthStandardClientScopes] })).token}`; + const full = "orchestration:read orchestration:operate settings:write source-control:write"; + const cases = [ + { scope: "orchestration:read", max: "read-only", granted: "orchestration:read" }, + { + scope: "orchestration:operate orchestration:read", + max: "auto", + granted: "orchestration:read orchestration:operate", + }, + // A write scope without its sibling does not reach full access. + { + scope: "orchestration:read orchestration:operate settings:write", + max: "auto", + granted: "orchestration:read orchestration:operate", + }, + { scope: full, max: undefined, granted: full }, + { scope: undefined, max: undefined, granted: full }, + ] as const; + for (const { scope, max, granted } of cases) { + const params = { ...authorizeParams(clientId), ...(scope === undefined ? {} : { scope }) }; + const details = yield* handler(postJson("/oauth/mcp/approval", params, admin)).pipe( + Effect.flatMap( + json<{ + csrfToken: string; + oneClickAccess: ReadonlyArray; + maxAccess?: string; + }>, + ), + ); + expect(details.maxAccess, scope).toBe(max); + expect(details.oneClickAccess.at(-1), scope).toBe(max ?? "full-access"); + + for (const decision of [ + { _tag: "browser-session", access: "full-access", csrfToken: details.csrfToken }, + { + _tag: "pairing-code", + access: "full-access", + code: (yield* auth.issuePairingCredential()).credential, + }, + ]) { + const approved = yield* decide(handler, params, decision, admin); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const token = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>)); + expect(token.scope, `${scope} ${decision._tag}`).toBe(granted); + const client = yield* auth.authenticateMcpClient( + HttpServerRequest.fromWeb( + at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), + ), + ); + expect(client.access, `${scope} ${decision._tag}`).toBe(max ?? "full-access"); + } + } + + // The approval page's token is bound to the scope it was shown for. + const readOnly = { ...authorizeParams(clientId), scope: "orchestration:read" }; + const shown = yield* handler(postJson("/oauth/mcp/approval", readOnly, admin)).pipe( + Effect.flatMap(json<{ csrfToken: string }>), + ); + const widened = yield* decide( + handler, + { ...readOnly, scope: full }, + { _tag: "browser-session", access: "full-access", csrfToken: shown.csrfToken }, + admin, + ); + expect(widened.status).toBe(400); + + for (const scope of ["orchestration:read terminal:operate", "orchestration:operate", ""]) { + const response = yield* handler( + at( + `/oauth/mcp/authorize?${new URLSearchParams({ ...authorizeParams(clientId), scope })}`, + ), + ); + expect(response.status, scope).toBe(302); + const location = new URL(response.headers.get("location")!, ORIGIN); + expect(location.searchParams.get("error"), scope).toBe( + scope === "" ? null : "invalid_scope", + ); + } + }), + ), +); + it.live("signs in a hosted agent with an https callback that asked for a client secret", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 18ad10c2dbd28..58c1754e88f8a 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -11,9 +11,10 @@ import { type AuthMcpTokenResult, type AuthMcpClientAccess, type AuthEnvironmentScope, - AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + clampMcpClientAccess, MCP_PEER_LINK_SOFTWARE_ID, + mcpClientAccessForScopes, mcpClientScopes, parseMcpApprovalCode, type RuntimeMode, @@ -65,7 +66,8 @@ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]); const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/; const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/; -const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; +// Clients that request every supported scope must still be able to reach full access. +const MCP_OAUTH_SCOPES = mcpClientScopes("full-access"); export interface McpOAuthUrls { readonly issuer: string; @@ -172,7 +174,12 @@ export class McpOAuthPageError extends Schema.TaggedError()( export class McpOAuthRedirectError extends Schema.TaggedError()( "McpOAuthRedirectError", { - error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]), + error: Schema.Literals([ + "invalid_request", + "unsupported_response_type", + "invalid_target", + "invalid_scope", + ]), description: Schema.String, redirectUri: Schema.String, state: Schema.optional(Schema.RedactedFromValue(Schema.String)), @@ -186,6 +193,8 @@ export interface AuthorizationRequest { readonly state: Redacted.Redacted | undefined; readonly resource: string; readonly issuer: string; + /** The broadest access the client's `scope` asked for; full access when it sent none. */ + readonly maxAccess: AuthMcpClientAccess; } interface PendingCode { @@ -321,6 +330,7 @@ const make = Effect.gen(function* () { authorization.client.clientId, authorization.redirectUri, authorization.codeChallenge, + authorization.maxAccess, ]), ); @@ -413,6 +423,19 @@ const make = Effect.gen(function* () { if (!sameResource(urls, request.resource)) { return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`); } + const scopes = request.scope?.split(" ").filter((scope) => scope !== "") ?? []; + const unknown = scopes.filter((scope) => !MCP_OAUTH_SCOPES.some((known) => known === scope)); + if (unknown.length > 0) { + return yield* fail("invalid_scope", `Unsupported scope: ${unknown.join(" ")}.`); + } + // An absent or empty scope keeps the approver's choice, as before clients sent one. + const maxAccess = scopes.length === 0 ? "full-access" : mcpClientAccessForScopes(scopes); + if (maxAccess === undefined) { + return yield* fail( + "invalid_scope", + `Every access level needs ${AuthOrchestrationReadScope}.`, + ); + } return { client, redirectUri, @@ -420,6 +443,7 @@ const make = Effect.gen(function* () { state, resource: urls.resource, issuer: urls.issuer, + maxAccess, } satisfies AuthorizationRequest; }); @@ -501,6 +525,8 @@ const make = Effect.gen(function* () { }); } } + // RFC 6749 §3.3: the token response's `scope` reports the narrower grant. + access = clampMcpClientAccess(access, input.authorization.maxAccess); const code = yield* mintCode(input.authorization, access); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 6e10362000adf..beeef33d7dc35 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -4,6 +4,7 @@ import { AuthMcpClientAccess, AuthMcpClientRegistration, AuthMcpRegistrationError, + clampMcpClientAccess, EnvironmentHttpApi, mcpClientScopes, } from "@t3tools/contracts"; @@ -176,12 +177,15 @@ export const layer = HttpApiBuilder.group( ...(oauth.runtimeModeCeiling === undefined ? {} : { runtimeModeCeiling: oauth.runtimeModeCeiling }), + ...(resolved.maxAccess === "full-access" ? {} : { maxAccess: resolved.maxAccess }), ...(session === undefined ? {} : { csrfToken: session.csrfToken, - oneClickAccess: AuthMcpClientAccess.literals.filter((access) => - mcpClientScopes(access).every((scope) => session.scopes.includes(scope)), + oneClickAccess: AuthMcpClientAccess.literals.filter( + (access) => + clampMcpClientAccess(access, resolved.maxAccess) === access && + mcpClientScopes(access).every((scope) => session.scopes.includes(scope)), ), }), }; diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index cc7c1f6e219de..792a7422246ac 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -4,6 +4,7 @@ import { AuthMcpApprovalError, AuthMcpClientAccess, AuthMcpAuthorizationRequest, + clampMcpClientAccess, isRuntimeModeAbove, parseMcpApprovalCode, } from "@t3tools/contracts"; @@ -66,6 +67,7 @@ type Loaded = | { readonly status: "ready"; readonly details: AuthMcpApprovalDetails }; const UNREACHABLE = msg("Could not reach this environment. Try again."); +const NOT_REQUESTED = msg("This app did not ask for this access."); const isApprovalError = Schema.is(AuthMcpApprovalError); export type McpApprovalAnswer = @@ -154,13 +156,17 @@ export function McpConsent({ const [requestedAccess, setAccess] = useState(null); const [pairingCode, setPairingCode] = useState(""); const [armed, setArmed] = useState(false); + const maxAccess = (loaded.status === "ready" && loaded.details.maxAccess) || "full-access"; const access = requireLevelChoice && requestedAccess === null ? null - : resolveMcpAccess( - requestedAccess, - loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined, - pairingCode.trim().length > 0, + : clampMcpClientAccess( + resolveMcpAccess( + requestedAccess, + loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined, + pairingCode.trim().length > 0, + ), + maxAccess, ); const [errorMessage, setErrorMessage] = useState(""); const [pending, setPending] = useState<"approve" | "deny" | null>(null); @@ -261,7 +267,8 @@ export function McpConsent({ access !== null && resolveApprovalDecision({ code: pairingCode, access, details }) !== null; // A code from "Use T3 Code in another app" names its level, so the page does not ask again. - const codeAccess = parseMcpApprovalCode(pairingCode)?.access; + const parsedCodeAccess = parseMcpApprovalCode(pairingCode)?.access; + const codeAccess = parsedCodeAccess && clampMcpClientAccess(parsedCodeAccess, maxAccess); const approveLevel = codeAccess ?? access; return ( @@ -441,6 +448,9 @@ function ceilingReason( access: AuthMcpClientAccess, resolve: MessageResolver, ) { + if (clampMcpClientAccess(access, details.maxAccess ?? access) !== access) { + return resolve(NOT_REQUESTED); + } const ceiling = details.runtimeModeCeiling; return ceiling === undefined || access === "read-only" || diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..85e43e793bd51 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3000,6 +3000,7 @@ "9c5a2e144cefdf2f": "Nur lesen", "12d03e02951725b0": "Projekte und Threads lesen. Kann nichts starten, keine Nachrichten senden und nichts ändern.", "b6c9bd4137eca7b1": "Die Umgebung hat eine Adresse zurückgegeben, die diese Seite nicht öffnet.", + "91aaab8390655d18": "Diese App hat diesen Zugriff nicht angefordert.", "8ec8255ffc9fe8e9": "Die Anmeldung konnte nicht fortgesetzt werden.", "04358a5e0d679d69": "Anmeldeanfrage wird geprüft", "5decc5fd8dc3f6a7": "Einen Moment, diese Umgebung prüft die Anfrage des Agenten.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..294b537269487 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Read only", "12d03e02951725b0": "Read projects and threads. Cannot start, message or change anything.", "b6c9bd4137eca7b1": "The environment returned an address this page will not open.", + "91aaab8390655d18": "This app did not ask for this access.", "8ec8255ffc9fe8e9": "The sign-in could not continue.", "04358a5e0d679d69": "Checking the sign-in request", "5decc5fd8dc3f6a7": "One moment while this environment verifies the agent's request.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..ab24c0f3424fe 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Solo lectura", "12d03e02951725b0": "Leer proyectos e hilos. No puede iniciar, enviar mensajes ni cambiar nada.", "b6c9bd4137eca7b1": "El entorno devolvió una dirección que esta página no abrirá.", + "91aaab8390655d18": "Esta app no pidió este acceso.", "8ec8255ffc9fe8e9": "El inicio de sesión no pudo continuar.", "04358a5e0d679d69": "Comprobando la solicitud de inicio de sesión", "5decc5fd8dc3f6a7": "Un momento mientras este entorno verifica la solicitud del agente.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..fd5b0c68a9415 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Lecture seule", "12d03e02951725b0": "Lire les projets et les fils. Ne peut rien démarrer, envoyer ni modifier.", "b6c9bd4137eca7b1": "L’environnement a renvoyé une adresse que cette page n’ouvrira pas.", + "91aaab8390655d18": "Cette app n'a pas demandé cet accès.", "8ec8255ffc9fe8e9": "La connexion n’a pas pu se poursuivre.", "04358a5e0d679d69": "Vérification de la demande de connexion", "5decc5fd8dc3f6a7": "Un instant, le temps que cet environnement vérifie la demande de l’agent.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..199212edd16d9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2997,6 +2997,7 @@ "9c5a2e144cefdf2f": "読み取り専用", "12d03e02951725b0": "プロジェクトとスレッドを読み取ります。開始、メッセージ送信、変更はできません。", "b6c9bd4137eca7b1": "環境から、このページでは開けないアドレスが返されました。", + "91aaab8390655d18": "このアプリはこのアクセスを要求していません。", "8ec8255ffc9fe8e9": "サインインを続行できませんでした。", "04358a5e0d679d69": "サインインリクエストを確認しています", "5decc5fd8dc3f6a7": "この環境がエージェントのリクエストを検証しています。しばらくお待ちください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..d48daaa493704 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2998,6 +2998,7 @@ "9c5a2e144cefdf2f": "읽기 전용", "12d03e02951725b0": "프로젝트와 스레드를 읽습니다. 시작, 메시지 전송, 변경은 할 수 없습니다.", "b6c9bd4137eca7b1": "환경에서 이 페이지가 열지 않는 주소를 반환했습니다.", + "91aaab8390655d18": "이 앱은 이 권한을 요청하지 않았습니다.", "8ec8255ffc9fe8e9": "로그인을 계속할 수 없습니다.", "04358a5e0d679d69": "로그인 요청을 확인하는 중", "5decc5fd8dc3f6a7": "이 환경에서 에이전트의 요청을 확인하는 동안 잠시 기다려 주세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..162f2d4c11149 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Somente leitura", "12d03e02951725b0": "Lê projetos e threads. Não pode iniciar, enviar mensagens nem alterar nada.", "b6c9bd4137eca7b1": "O ambiente retornou um endereço que esta página não vai abrir.", + "91aaab8390655d18": "Este app não pediu este acesso.", "8ec8255ffc9fe8e9": "Não foi possível continuar o login.", "04358a5e0d679d69": "Verificando a solicitação de login", "5decc5fd8dc3f6a7": "Um momento enquanto este ambiente verifica a solicitação do agente.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..3d28c6dc2aa08 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Только чтение", "12d03e02951725b0": "Чтение проектов и тредов. Нельзя ничего запускать, отправлять или менять.", "b6c9bd4137eca7b1": "Окружение вернуло адрес, который эта страница не откроет.", + "91aaab8390655d18": "Это приложение не запрашивало такой доступ.", "8ec8255ffc9fe8e9": "Не удалось продолжить вход.", "04358a5e0d679d69": "Проверка запроса на вход", "5decc5fd8dc3f6a7": "Подождите, окружение проверяет запрос агента.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..82579625d7b05 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2999,6 +2999,7 @@ "9c5a2e144cefdf2f": "Endast läsning", "12d03e02951725b0": "Läs projekt och trådar. Kan inte starta, skicka meddelanden eller ändra något.", "b6c9bd4137eca7b1": "Miljön returnerade en adress som den här sidan inte öppnar.", + "91aaab8390655d18": "Den här appen bad inte om den här åtkomsten.", "8ec8255ffc9fe8e9": "Inloggningen kunde inte fortsätta.", "04358a5e0d679d69": "Kontrollerar inloggningsbegäran", "5decc5fd8dc3f6a7": "Ett ögonblick medan den här miljön verifierar agentens begäran.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..e41bef3217f9f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3003,6 +3003,7 @@ "9c5a2e144cefdf2f": "只读", "12d03e02951725b0": "读取项目和会话,不能启动会话、发送消息或进行任何更改。", "b6c9bd4137eca7b1": "环境返回了一个此页面不会打开的地址。", + "91aaab8390655d18": "此应用未请求此权限。", "8ec8255ffc9fe8e9": "无法继续登录。", "04358a5e0d679d69": "正在检查登录请求", "5decc5fd8dc3f6a7": "请稍候,此环境正在验证智能体的请求。", diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index ed6be35c0c1ea..1b3e470ba3be7 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -69,7 +69,10 @@ The result is an ordinary session with subject `mcp-client`. A read-only grant holds `orchestration:read` alone. On `/mcp` it passes only tools declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts), where every tool must declare who may call it to compile. Any other grant adds -`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions. Every other HTTP and WebSocket +`orchestration:operate` and a signed ceiling. A client's OAuth `scope`, when sent, lowers +that choice to the broadest level whose scopes it names in full, so a token never carries a +scope the client did not ask for. `scopes_supported` lists every full-access scope because +clients commonly request all of them. Only `/mcp` accepts these sessions. Every other HTTP and WebSocket path rejects that subject, because the RPC surface would let the agent act above its ceiling. Inside MCP the credential sets the limits and tool parameters only pick targets; see diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 97bc0d385a3d7..6bb4851fc7a99 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -80,6 +80,11 @@ policy. Approving without a code starts at **Read only**: threads in every project. A thread it starts or steers cannot run with more permissions than the mode you chose. +An agent can ask for less. One that asks only for `orchestration:read` gets +**Read only**, and one that asks for `orchestration:read` and +`orchestration:operate` gets at most **Auto**, whatever you pick or code you +enter. **Full access** also needs `settings:write` and `source-control:write`. + ## What outside agents can call Some tools only work for an agent running inside a T3 thread, because they act diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 826ffeb6b258e..eb08bcc2e10b3 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -289,6 +289,26 @@ export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray, +): AuthMcpClientAccess | undefined => + AuthMcpClientAccess.literals.findLast((access) => + mcpClientScopes(access).every((scope) => requested.includes(scope)), + ); + +/** `access`, lowered to `max` when it is broader. */ +export const clampMcpClientAccess = ( + access: AuthMcpClientAccess, + max: AuthMcpClientAccess, +): AuthMcpClientAccess => + AuthMcpClientAccess.literals.indexOf(access) > AuthMcpClientAccess.literals.indexOf(max) + ? max + : access; + /** The random part of a one-time pairing code: this many characters from this alphabet. */ export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; export const PAIRING_CODE_LENGTH = 12; @@ -611,6 +631,8 @@ export const AuthMcpAuthorizationRequest = Schema.Struct({ code_challenge_method: Schema.optionalKey(Schema.String), state: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)), resource: Schema.optionalKey(Schema.String), + /** Caps the grant at the broadest access it fully names; absent grants what the approver picks. */ + scope: Schema.optionalKey(Schema.String), }); export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type; @@ -623,6 +645,8 @@ export const AuthMcpApprovalDetails = Schema.Struct({ csrfToken: Schema.optionalKey(Schema.String), /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */ oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)), + /** The broadest access the app's `scope` asked for; any approval is lowered to it. */ + maxAccess: Schema.optionalKey(AuthMcpClientAccess), /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */ runtimeModeCeiling: Schema.optionalKey( Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }), From d2ac6eaf6c6ad0c6a8398bc3a2a5871a8fb54c4c Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:42:39 -0300 Subject: [PATCH 03/87] fix(server): request_secret opens a new card when a later run reuses its id The secret request key was scoped to the provider session, which outlives runs. An agent that reused a clientRequestId in a later run replayed the earlier run's closed card instead of asking again. The key now includes the run id. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 74 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 4 +- 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 0bbb8a65327d0..e53c4bb744dcb 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -1950,6 +1950,80 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect("opens a new secret card when a later run reuses a clientRequestId", () => + Effect.gen(function* () { + const activeRunId = yield* Ref.make(parentRunId); + const cards = yield* Ref.make>(new Map()); + const receipts = yield* Ref.make>(new Set()); + const recorded = yield* Queue.unbounded(); + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => + Effect.gen(function* () { + const runId = yield* Ref.get(activeRunId); + const parent = parentProjection([]); + return { + ...parent, + runs: parent.runs.map((run) => ({ ...run, id: runId })), + turnItems: [...(yield* Ref.get(cards))].map(([id, secretStatus]) => ({ + id, + type: "secret_request", + secretStatus, + })), + } as unknown as OrchestrationV2ThreadProjection; + }), + dispatch: (command) => + command.type !== "secret_request.record" + ? Effect.die("Unexpected command") + : Effect.gen(function* () { + // A repeated command id replays its receipt and records nothing. + if (!(yield* Ref.get(receipts)).has(command.commandId)) { + yield* Ref.update(receipts, (ids) => new Set([...ids, command.commandId])); + yield* Ref.update( + cards, + (items) => new Map([...items, [command.turnItemId, command.secretStatus]]), + ); + } + yield* Queue.offer(recorded, command.secretStatus); + return {} as never; + }), + }), + ServerSettings.layerTest(), + providerRegistryLayer([]), + adapterRegistryLayer([]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const ask = service + .requestSecret(scope, { + label: "Token", + reason: "Connect the account.", + clientRequestId: "router-key", + timeoutMs: 1_000, + }) + .pipe(Effect.forkChild); + const first = yield* ask; + assert.strictEqual(yield* Queue.take(recorded), "pending"); + yield* TestClock.adjust(Duration.millis(1_000)); + assert.include(yield* Fiber.join(first), { status: "timed_out" }); + assert.strictEqual(yield* Queue.take(recorded), "cancelled"); + + yield* Ref.set(activeRunId, RunId.make("run:mcp-providers-later")); + const second = yield* ask; + assert.strictEqual(yield* Queue.take(recorded), "pending"); + yield* TestClock.adjust(Duration.millis(1_000)); + assert.include(yield* Fiber.join(second), { status: "timed_out" }); + assert.strictEqual((yield* Ref.get(cards)).size, 2); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + it.effect( "advertises orchestration capability from registered adapters rather than a driver allowlist", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8dcd025c82481..34c069d6afe91 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2473,7 +2473,9 @@ const make = Effect.gen(function* () { } const runId = run.id; const nodeId = run.rootNodeId; - const key = yield* requestKey(input.clientRequestId); + // Scoped to the run: a provider session's namespace outlives runs, and an id reused in a + // later run must open a new card, not replay the earlier run's closed one. + const key = `${runId}:${yield* requestKey(input.clientRequestId)}`; const turnItemId = TurnItemId.make( `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`, ); From c8d82e61542f16b764b3c1c8ccb5a3f0cac216f2 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:48:26 -0300 Subject: [PATCH 04/87] feat(source-control): Forgejo default server setting With several fj/tea logins, projects without a Forgejo remote (publishing, `owner/repo` clones) picked an arbitrary or default login. A Forgejo "Default server" setting now selects the login for those cases; a project's own remote still always decides. Co-Authored-By: Claude Opus 5.5 --- .../SourceControlProvidersSection.tsx | 77 +++++---- apps/mobile/src/i18n/translations/de.json | 2 + apps/mobile/src/i18n/translations/en.json | 2 + apps/mobile/src/i18n/translations/es.json | 2 + apps/mobile/src/i18n/translations/fr.json | 2 + apps/mobile/src/i18n/translations/ja.json | 2 + apps/mobile/src/i18n/translations/ko.json | 2 + apps/mobile/src/i18n/translations/pt-BR.json | 2 + apps/mobile/src/i18n/translations/ru.json | 2 + apps/mobile/src/i18n/translations/sv.json | 2 + apps/mobile/src/i18n/translations/zh.json | 2 + .../settings/ProviderSettingsForm.tsx | 7 + apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + docs/user/source-control.md | 5 +- .../src/server/ForgejoCli.ts | 55 +++++- .../ForgejoSourceControlProvider.test.ts | 163 +++++++++++++++++- .../server/ForgejoSourceControlProvider.ts | 143 +++++++++------ .../src/shared/definition.ts | 22 ++- 27 files changed, 419 insertions(+), 93 deletions(-) diff --git a/apps/mobile/src/features/settings/components/SourceControlProvidersSection.tsx b/apps/mobile/src/features/settings/components/SourceControlProvidersSection.tsx index 51d474b9477f4..53b7405a18eb5 100644 --- a/apps/mobile/src/features/settings/components/SourceControlProvidersSection.tsx +++ b/apps/mobile/src/features/settings/components/SourceControlProvidersSection.tsx @@ -402,45 +402,56 @@ export function SourceControlHostFieldsForm(props: { }; return ( - {fields.map((field) => ( - - {field.secret ? ( - <> - - {field.label} - - { + const forgejoDefault = definition.kind === "forgejo" && field.key === "defaultServer"; + const label = forgejoDefault + ? gt("Default server", { $context: "settings field, a Forgejo server URL" }) + : field.label; + const description = forgejoDefault + ? gt( + "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", + ) + : field.description; + return ( + + {field.secret ? ( + <> + + {label} + + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={submit} + editable={!locked} + /> + + ) : ( + setDrafts({ ...drafts, [field.key]: value })} onSubmitEditing={submit} - editable={!locked} /> - - ) : ( - setDrafts({ ...drafts, [field.key]: value })} - onSubmitEditing={submit} - /> - )} - {field.description ? ( - {field.description} - ) : null} - - ))} + )} + {description ? ( + {description} + ) : null} + + ); + })} {failure ? ( {failure} diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index cabb9a34dbe9a..b64002a180a48 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5192,6 +5192,8 @@ "8ea7a295f2739627": "Gespeichert für {hosts}.", "526307cb5a8424a7": "Token erstellen", "c65001930bafa424": "Entfernen", + "f5ea5597259324a6": "Standardserver", + "29283141bc890650": "Der fj- oder tea-Login, der verwendet wird, wenn ein Projekt kein Forgejo-Remote hat, etwa beim Veröffentlichen. Das Remote eines Projekts verwendet immer seinen eigenen Login.", "1386dab454716962": "Entfernen", "7e93efc9d1b78549": "Gib diesen Code auf {host} ein und genehmige dann {app}. Er wurde kopiert. Der Server schließt die Anmeldung ab, auch wenn du die App verlässt.", "aafa642d6a47837d": "Die Anmeldung konnte nicht gestartet werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index fa572328fc871..337b91ae2bbf3 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5193,6 +5193,8 @@ "8ea7a295f2739627": "Saved for {hosts}.", "526307cb5a8424a7": "Create a token", "c65001930bafa424": "Remove", + "f5ea5597259324a6": "Default server", + "29283141bc890650": "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", "1386dab454716962": "Remove", "7e93efc9d1b78549": "Enter this code on {host}, then approve {app}. It is copied. The server finishes signing in even if you leave the app.", "aafa642d6a47837d": "Could not start the sign-in", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index aaeb8230bc83e..a84f2af29389a 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5186,6 +5186,8 @@ "8ea7a295f2739627": "Guardado para {hosts}.", "526307cb5a8424a7": "Crear un token", "c65001930bafa424": "Quitar", + "f5ea5597259324a6": "Servidor predeterminado", + "29283141bc890650": "El inicio de sesión de fj o tea que se usa cuando un proyecto no tiene un remoto de Forgejo, como al publicar. El remoto de un proyecto siempre usa su propio inicio de sesión.", "1386dab454716962": "Quitar", "7e93efc9d1b78549": "Introduce este código en {host} y aprueba {app}. Ya está copiado. El servidor termina de iniciar sesión aunque salgas de la app.", "aafa642d6a47837d": "No se pudo iniciar el inicio de sesión", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 371ab3d7532dd..42c931401a55e 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5186,6 +5186,8 @@ "8ea7a295f2739627": "Enregistré pour {hosts}.", "526307cb5a8424a7": "Créer un jeton", "c65001930bafa424": "Supprimer", + "f5ea5597259324a6": "Serveur par défaut", + "29283141bc890650": "La connexion fj ou tea utilisée quand un projet n'a pas de remote Forgejo, par exemple lors de la publication. Le remote d'un projet utilise toujours sa propre connexion.", "1386dab454716962": "Supprimer", "7e93efc9d1b78549": "Saisissez ce code sur {host}, puis approuvez {app}. Il est copié. Le serveur termine la connexion même si vous quittez l’app.", "aafa642d6a47837d": "Impossible de démarrer la connexion", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 32b5c4d8f9748..b7cd4595dbff2 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5168,6 +5168,8 @@ "8ea7a295f2739627": "{hosts} 用に保存済み。", "526307cb5a8424a7": "トークンを作成", "c65001930bafa424": "削除", + "f5ea5597259324a6": "デフォルトサーバー", + "29283141bc890650": "プロジェクトに Forgejo のリモートがないとき(公開時など)に使う fj または tea のログイン。プロジェクトのリモートは常に自身のログインを使います。", "1386dab454716962": "削除", "7e93efc9d1b78549": "{host} でこのコードを入力してから、{app} を承認してください。コードはコピー済みです。アプリを離れても、サーバーがサインインを完了します。", "aafa642d6a47837d": "サインインを開始できませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0cd8713696dc5..fd12918b35ee4 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5172,6 +5172,8 @@ "8ea7a295f2739627": "{hosts}에 저장됨.", "526307cb5a8424a7": "토큰 만들기", "c65001930bafa424": "제거", + "f5ea5597259324a6": "기본 서버", + "29283141bc890650": "프로젝트에 Forgejo 원격이 없을 때(예: 게시할 때) 사용하는 fj 또는 tea 로그인입니다. 프로젝트의 원격은 항상 자체 로그인을 사용합니다.", "1386dab454716962": "제거", "7e93efc9d1b78549": "{host}에서 이 코드를 입력한 뒤 {app}을(를) 승인하세요. 코드가 복사되었습니다. 앱을 나가도 서버가 로그인을 완료합니다.", "aafa642d6a47837d": "로그인을 시작할 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index caac483484c2e..5b312f3f54dd3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5186,6 +5186,8 @@ "8ea7a295f2739627": "Salvo para {hosts}.", "526307cb5a8424a7": "Criar um token", "c65001930bafa424": "Remover", + "f5ea5597259324a6": "Servidor padrão", + "29283141bc890650": "O login do fj ou tea usado quando um projeto não tem remote do Forgejo, como ao publicar. O remote de um projeto sempre usa o próprio login.", "1386dab454716962": "Remover", "7e93efc9d1b78549": "Digite este código em {host} e aprove o {app}. Ele já foi copiado. O servidor conclui o login mesmo se você sair do app.", "aafa642d6a47837d": "Não foi possível iniciar o login", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d5439f9698130..b81ed22fe64e2 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5265,6 +5265,8 @@ "8ea7a295f2739627": "Сохранено для {hosts}.", "526307cb5a8424a7": "Создать токен", "c65001930bafa424": "Удалить", + "f5ea5597259324a6": "Сервер по умолчанию", + "29283141bc890650": "Вход fj или tea, который используется, когда у проекта нет удалённого репозитория Forgejo, например при публикации. Удалённый репозиторий проекта всегда использует свой вход.", "1386dab454716962": "Удалить", "7e93efc9d1b78549": "Введите этот код на {host}, затем подтвердите {app}. Код скопирован. Сервер завершит вход, даже если вы выйдете из приложения.", "aafa642d6a47837d": "Не удалось начать вход", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7a634bcab134f..67c5e5960d88f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5192,6 +5192,8 @@ "8ea7a295f2739627": "Sparad för {hosts}.", "526307cb5a8424a7": "Skapa en token", "c65001930bafa424": "Ta bort", + "f5ea5597259324a6": "Standardserver", + "29283141bc890650": "fj- eller tea-inloggningen som används när ett projekt saknar en Forgejo-fjärr, till exempel vid publicering. Ett projekts fjärr använder alltid sin egen inloggning.", "1386dab454716962": "Ta bort", "7e93efc9d1b78549": "Ange koden på {host} och godkänn sedan {app}. Den är kopierad. Servern slutför inloggningen även om du lämnar appen.", "aafa642d6a47837d": "Kunde inte starta inloggningen", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 98b946c76f028..f485731c52d51 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5176,6 +5176,8 @@ "8ea7a295f2739627": "已为 {hosts} 保存。", "526307cb5a8424a7": "创建 token", "c65001930bafa424": "移除", + "f5ea5597259324a6": "默认服务器", + "29283141bc890650": "项目没有 Forgejo 远程仓库时(例如发布时)使用的 fj 或 tea 登录。项目的远程仓库始终使用自己的登录。", "1386dab454716962": "移除", "7e93efc9d1b78549": "在 {host} 上输入此代码,然后批准 {app}。代码已复制。即使你离开应用,服务器也会完成登录。", "aafa642d6a47837d": "无法开始登录", diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx index 6848be472d816..d6a8fae2ae802 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.tsx +++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx @@ -240,6 +240,13 @@ const PACKAGE_FIELD_TEXT: ReadonlyMap = new Map([ "A git.cafe token, used before CAFE_TOKEN and the cafe login, so GitCafe works without the CLI signed in.", ), ], + ["Default server", msg("Default server", { $context: "settings field, a Forgejo server URL" })], + [ + "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", + msg( + "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", + ), + ], ["e.g. --chrome", msg("e.g. --chrome")], ["e.g. 300000", msg("e.g. 300000")], ["Optional", msg("Optional", { $context: "placeholder of an optional settings field" })], diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..45c89dc484abc 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -9083,6 +9083,8 @@ "70752f3aba4894ff": "Mit einem API-Token statt eines Zugriffstokens.", "417f9edb887598bd": "Erreicht jedes Repository, auf das dein Atlassian-Konto zugreifen kann. Gib ihm Lese- und Schreibzugriff auf Repositorys und Pull Requests sowie read:user:bitbucket und read:workspace:bitbucket.", "3516b19bb6089d21": "Ein git.cafe-Token, das vor CAFE_TOKEN und dem cafe-Login verwendet wird, damit GitCafe ohne angemeldete CLI funktioniert.", + "f5ea5597259324a6": "Standardserver", + "29283141bc890650": "Der fj- oder tea-Login, der verwendet wird, wenn ein Projekt kein Forgejo-Remote hat, etwa beim Veröffentlichen. Das Remote eines Projekts verwendet immer seinen eigenen Login.", "bc63ccd46ca25a3a": "z. B. --chrome", "5cd396217a43a9b3": "z. B. 300000", "9da1db099d0ad2c8": "Optional", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..3d5b01eebb628 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -9091,6 +9091,8 @@ "70752f3aba4894ff": "With an API token instead of an access token.", "417f9edb887598bd": "Reaches every repository your Atlassian account can. Give it read and write access to repositories and pull requests, plus read:user:bitbucket and read:workspace:bitbucket.", "3516b19bb6089d21": "A git.cafe token, used before CAFE_TOKEN and the cafe login, so GitCafe works without the CLI signed in.", + "f5ea5597259324a6": "Default server", + "29283141bc890650": "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", "bc63ccd46ca25a3a": "e.g. --chrome", "5cd396217a43a9b3": "e.g. 300000", "9da1db099d0ad2c8": "Optional", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..546af56a8dd67 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -9081,6 +9081,8 @@ "70752f3aba4894ff": "Con un token de API en lugar de un token de acceso.", "417f9edb887598bd": "Llega a todos los repositorios a los que llega tu cuenta de Atlassian. Dale acceso de lectura y escritura a repositorios y pull requests, además de read:user:bitbucket y read:workspace:bitbucket.", "3516b19bb6089d21": "Un token de git.cafe, que se usa antes que CAFE_TOKEN y el inicio de sesión de cafe, para que GitCafe funcione sin la CLI con sesión iniciada.", + "f5ea5597259324a6": "Servidor predeterminado", + "29283141bc890650": "El inicio de sesión de fj o tea que se usa cuando un proyecto no tiene un remoto de Forgejo, como al publicar. El remoto de un proyecto siempre usa su propio inicio de sesión.", "bc63ccd46ca25a3a": "p. ej., --chrome", "5cd396217a43a9b3": "p. ej., 300000", "9da1db099d0ad2c8": "Opcional", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..47efa53b5591a 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -9083,6 +9083,8 @@ "70752f3aba4894ff": "Avec un jeton d’API au lieu d’un jeton d’accès.", "417f9edb887598bd": "Accède à tous les dépôts accessibles à votre compte Atlassian. Accordez-lui l’accès en lecture et en écriture aux dépôts et aux pull requests, ainsi que read:user:bitbucket et read:workspace:bitbucket.", "3516b19bb6089d21": "Un jeton git.cafe, utilisé avant CAFE_TOKEN et la connexion cafe, pour que GitCafe fonctionne sans connexion à la CLI.", + "f5ea5597259324a6": "Serveur par défaut", + "29283141bc890650": "La connexion fj ou tea utilisée quand un projet n'a pas de remote Forgejo, par exemple lors de la publication. Le remote d'un projet utilise toujours sa propre connexion.", "bc63ccd46ca25a3a": "p. ex. --chrome", "5cd396217a43a9b3": "p. ex. 300000", "9da1db099d0ad2c8": "Facultatif", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..933b9bdff2eec 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -9039,6 +9039,8 @@ "70752f3aba4894ff": "アクセストークンの代わりに API トークンを使用します。", "417f9edb887598bd": "Atlassian アカウントがアクセスできるすべてのリポジトリに到達できます。リポジトリとプルリクエストへの読み取り・書き込みアクセスに加え、read:user:bitbucket と read:workspace:bitbucket を付与してください。", "3516b19bb6089d21": "git.cafe のトークンです。CAFE_TOKEN と cafe login より優先して使用されるため、CLI でサインインしていなくても GitCafe を使えます。", + "f5ea5597259324a6": "デフォルトサーバー", + "29283141bc890650": "プロジェクトに Forgejo のリモートがないとき(公開時など)に使う fj または tea のログイン。プロジェクトのリモートは常に自身のログインを使います。", "bc63ccd46ca25a3a": "例: --chrome", "5cd396217a43a9b3": "例: 300000", "9da1db099d0ad2c8": "省略可能", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..f4905c31c680a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -9041,6 +9041,8 @@ "70752f3aba4894ff": "액세스 토큰 대신 API 토큰을 사용합니다.", "417f9edb887598bd": "Atlassian 계정이 접근할 수 있는 모든 저장소에 접근합니다. 저장소와 풀 리퀘스트에 대한 읽기 및 쓰기 권한과 read:user:bitbucket, read:workspace:bitbucket 권한을 부여하세요.", "3516b19bb6089d21": "CAFE_TOKEN과 cafe 로그인보다 먼저 사용되는 git.cafe 토큰입니다. CLI에 로그인하지 않아도 GitCafe를 사용할 수 있습니다.", + "f5ea5597259324a6": "기본 서버", + "29283141bc890650": "프로젝트에 Forgejo 원격이 없을 때(예: 게시할 때) 사용하는 fj 또는 tea 로그인입니다. 프로젝트의 원격은 항상 자체 로그인을 사용합니다.", "bc63ccd46ca25a3a": "예: --chrome", "5cd396217a43a9b3": "예: 300000", "9da1db099d0ad2c8": "선택 사항", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..0b39ab79cdd20 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -9082,6 +9082,8 @@ "70752f3aba4894ff": "Com um token de API em vez de um token de acesso.", "417f9edb887598bd": "Acessa todos os repositórios que sua conta Atlassian acessa. Dê a ele acesso de leitura e gravação a repositórios e pull requests, além de read:user:bitbucket e read:workspace:bitbucket.", "3516b19bb6089d21": "Um token do git.cafe, usado antes de CAFE_TOKEN e do cafe login, para que o GitCafe funcione sem login na CLI.", + "f5ea5597259324a6": "Servidor padrão", + "29283141bc890650": "O login do fj ou tea usado quando um projeto não tem remote do Forgejo, como ao publicar. O remote de um projeto sempre usa o próprio login.", "bc63ccd46ca25a3a": "ex.: --chrome", "5cd396217a43a9b3": "ex.: 300000", "9da1db099d0ad2c8": "Opcional", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..eadb0dec5eb1a 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -9083,6 +9083,8 @@ "70752f3aba4894ff": "С API-токеном вместо токена доступа.", "417f9edb887598bd": "Даёт доступ ко всем репозиториям, доступным вашему аккаунту Atlassian. Выдайте ему доступ на чтение и запись к репозиториям и пул-реквестам, а также read:user:bitbucket и read:workspace:bitbucket.", "3516b19bb6089d21": "Токен git.cafe, используется раньше CAFE_TOKEN и cafe login, чтобы GitCafe работал без входа в CLI.", + "f5ea5597259324a6": "Сервер по умолчанию", + "29283141bc890650": "Вход fj или tea, который используется, когда у проекта нет удалённого репозитория Forgejo, например при публикации. Удалённый репозиторий проекта всегда использует свой вход.", "bc63ccd46ca25a3a": "например, --chrome", "5cd396217a43a9b3": "например, 300000", "9da1db099d0ad2c8": "Необязательно", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..562fe2588461b 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -9089,6 +9089,8 @@ "70752f3aba4894ff": "Med en API-token i stället för en åtkomsttoken.", "417f9edb887598bd": "Når alla repon som ditt Atlassian-konto kan nå. Ge den läs- och skrivåtkomst till repon och pull requests, plus read:user:bitbucket och read:workspace:bitbucket.", "3516b19bb6089d21": "En git.cafe-token som används före CAFE_TOKEN och cafe-inloggningen, så att GitCafe fungerar utan att CLI:t är inloggat.", + "f5ea5597259324a6": "Standardserver", + "29283141bc890650": "fj- eller tea-inloggningen som används när ett projekt saknar en Forgejo-fjärr, till exempel vid publicering. Ett projekts fjärr använder alltid sin egen inloggning.", "bc63ccd46ca25a3a": "t.ex. --chrome", "5cd396217a43a9b3": "t.ex. 300000", "9da1db099d0ad2c8": "Valfritt", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..66b95459e4749 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -9099,6 +9099,8 @@ "70752f3aba4894ff": "使用 API token 而不是访问 token。", "417f9edb887598bd": "可访问你的 Atlassian 账户能访问的所有仓库。请授予其仓库和 pull request 的读写权限,以及 read:user:bitbucket 和 read:workspace:bitbucket。", "3516b19bb6089d21": "git.cafe token,优先于 CAFE_TOKEN 和 cafe 登录使用,因此无需登录 CLI 即可使用 GitCafe。", + "f5ea5597259324a6": "默认服务器", + "29283141bc890650": "项目没有 Forgejo 远程仓库时(例如发布时)使用的 fj 或 tea 登录。项目的远程仓库始终使用自己的登录。", "bc63ccd46ca25a3a": "例如:--chrome", "5cd396217a43a9b3": "例如:300000", "9da1db099d0ad2c8": "可选", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..b80139afc6580 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -59,7 +59,10 @@ fj does not preserve the subpath when checking its account. When cloning or publishing, use a full repository URL to select a specific server. You can use `owner/repo` when only one fj server is configured, or with your default `tea` -login when fj is unavailable or unconfigured. With multiple fj servers, use the full URL. +login when fj is unavailable or unconfigured. With multiple servers, set **Default server** +in **Settings → Source control & issues → Forgejo / Gitea** on that environment. `owner/repo` and +projects without a Forgejo remote then use that server's login. A project whose remote names +a server always uses that server's login. If you have multiple `tea` accounts on one server, select one with `tea login default `. Git push and clone also need Git credentials or an SSH key for that server. diff --git a/packages/source-control-forgejo/src/server/ForgejoCli.ts b/packages/source-control-forgejo/src/server/ForgejoCli.ts index c94d96dd39eb4..a85a8869bf06e 100644 --- a/packages/source-control-forgejo/src/server/ForgejoCli.ts +++ b/packages/source-control-forgejo/src/server/ForgejoCli.ts @@ -17,6 +17,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider"; +import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as ForgejoDefinition from "../shared/definition.ts"; // A Gitea list page can hold 50 pull request bodies; tea's output is otherwise capped at 1 MB. const API_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; @@ -221,6 +223,30 @@ export function matchForgejoLogin( : undefined; } +/** + * The server Settings names for a project without a Forgejo remote, as a remote to match logins + * against, or undefined when unset. One that does not parse matches no login rather than any. + */ +export const defaultServer = ( + settings: SourceControlHost.SourceControlHost["Service"]["settings"], +) => + settings.get.pipe( + Effect.map((current) => { + const { defaultServer: value } = readSourceControlHostSettings( + ForgejoDefinition.settings, + current.sourceControlHosts[ForgejoDefinition.definition.kind], + ); + if (!value) return undefined; + const url = /^https?:\/\//i.test(value) ? value : `https://${value}`; + const remote = parseForgejoRemote(url); + return { + url, + remote: remote ?? { host: url, hostname: url, ssh: false, path: "" }, + }; + }), + Effect.orElseSucceed(() => undefined), + ); + const ForgejoKeysConfig = Config.all({ dataHome: Config.String("XDG_DATA_HOME").pipe(Config.option), appData: Config.String("APPDATA").pipe(Config.option), @@ -229,7 +255,7 @@ const ForgejoKeysConfig = Config.all({ export const make = Effect.gen(function* () { // Optional strings cannot fail to decode. const { dataHome, appData } = yield* Effect.suspend(() => ForgejoKeysConfig).pipe(Effect.orDie); - const { process } = yield* SourceControlHost.SourceControlHost; + const { process, settings } = yield* SourceControlHost.SourceControlHost; const fileSystem = yield* FileSystem.FileSystem; const httpClient = yield* HttpClient.HttpClient; const authLock = yield* Semaphore.make(1); @@ -592,17 +618,27 @@ export const make = Effect.gen(function* () { ssh: false, path: remote?.path ?? "", }; - const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl; + // Without a remote or a named host, the server Settings names decides which login serves. + const fallback = remote ? undefined : yield* defaultServer(settings); + const loginRemote = remote ?? fallback?.remote ?? null; + const schemeRemoteUrl = remote?.ssh + ? input.context?.provider.baseUrl + : (remoteUrl ?? fallback?.url); const fjLogins = yield* listLogins({ cwd: input.cwd, command: "fj", ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}), }); const requestedHost = input.host ?? input.context?.requestedHost; - const matchHostOnly = hostOnly || (!!input.host && !remote?.path); + const matchHostOnly = hostOnly || (!!input.host && !remote?.path) || fallback !== undefined; const selectLogin = (logins: ReturnType) => - remote - ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly) + loginRemote + ? matchForgejoLogin( + logins, + loginRemote, + loginRemote.ssh ? requestedHost : undefined, + matchHostOnly, + ) : (logins.find((item) => item.default === "true") ?? (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined)); let login = selectLogin(fjLogins); @@ -611,8 +647,13 @@ export const make = Effect.gen(function* () { !login && fjLogins.some( (item) => - !remote || - matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly), + !loginRemote || + matchForgejoLogin( + [item], + loginRemote, + loginRemote.ssh ? requestedHost : undefined, + matchHostOnly, + ), ) ) { const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe( diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts index cd65a8ab62050..4e06beb3afe64 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts @@ -1,4 +1,4 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { DEFAULT_SERVER_SETTINGS, SourceControlProviderKind } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -2432,6 +2432,167 @@ it.effect("explains a slow fj instead of advising an install when tea is absent" ), ); +const withForgejoDefault = (defaultServer: string) => ({ + ...DEFAULT_SERVER_SETTINGS, + sourceControlHosts: { forgejo: { defaultServer } }, +}); + +it.effect( + "picks the fj login without a project remote by Settings, else the first that works", + () => + Effect.forEach( + [ + { + defaultServer: "", + remoteUrl: undefined, + checked: ["https://elsewhere.test", "https://forgejo.test"], + }, + // Settings names one server, so another login that works is never tried. + { + defaultServer: "https://forgejo.test", + remoteUrl: undefined, + checked: ["https://forgejo.test"], + }, + { defaultServer: "missing.test", remoteUrl: undefined, checked: [] }, + { + defaultServer: "https://forgejo.test", + remoteUrl: "https://other.test/maria/project.git", + checked: [], + }, + ], + ({ defaultServer, checked: expected, remoteUrl }) => { + const checked: string[] = []; + return Effect.gen(function* () { + const spec = yield* ForgejoSourceControlProvider.makeDiscovery; + assert.strictEqual(spec.type, "managed-cli"); + if (spec.type !== "managed-cli") return; + const result = yield* spec.probe("/repo"); + assert.deepStrictEqual(checked, expected, defaultServer); + if (expected.length === 0) { + assert.strictEqual(result.auth.status, "unauthenticated"); + return; + } + assert.strictEqual(result.executable, "fj"); + assert.strictEqual(result.auth.status, "authenticated"); + assert.deepStrictEqual(result.auth.host, Option.some("forgejo.test")); + assert.deepStrictEqual(result.auth.account, Option.some("maria")); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(ForgejoCli.ForgejoCli)({ + getAccount: (input) => { + assert.strictEqual(input.baseUrl, "https://forgejo.test"); + return Effect.succeed("maria"); + }, + listLogins: (input) => + Effect.succeed( + input.command === "tea" + ? [] + : [ + { + name: "elsewhere.test", + url: "https://elsewhere.test", + user: "", + default: "false", + }, + { + name: "forgejo.test", + url: "https://forgejo.test", + user: "", + default: "false", + }, + ], + ), + }), + TestSourceControlHost.layer({ + settings: withForgejoDefault(defaultServer), + process: { + run: (input) => { + // Settings has no project in scope, so there is no origin remote. + if (input.command === "git") + return Effect.succeed( + remoteUrl + ? processOutput(remoteUrl) + : processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }), + ); + if (input.command === "tea") return Effect.succeed(processOutput("[]")); + assert.strictEqual(input.command, "fj"); + if (input.args[0] === "version") + return Effect.succeed(processOutput("fj 0.10.0")); + if (input.args[0] === "auth") return Effect.succeed(processOutput("")); + const host = input.args[1]!; + checked.push(host); + return Effect.succeed( + processOutput("", { + exitCode: ChildProcessSpawner.ExitCode( + host === "https://forgejo.test" ? 0 : 1, + ), + }), + ); + }, + }, + }), + ), + ), + Effect.provideService(HostProcess.HomeDirectory, "/home/maria"), + ); + }, + { discard: true }, + ), +); + +it.effect("resolves a repository without a remote on the Settings default server", () => + Effect.gen(function* () { + const cli = yield* ForgejoCli.make; + const published = yield* cli.resolveRepository({ cwd: "/new", repository: "maria/project" }); + assert.strictEqual(published.baseUrl, "https://code.test"); + assert.strictEqual(published.login, "code"); + // The project's remote picks its own login over the default. + const remote = yield* cli.resolveRepository({ + cwd: "/repo", + context: { + provider: { + kind: SourceControlProviderKind.make("forgejo"), + name: "Forgejo", + baseUrl: "https://forgejo.local", + }, + remoteName: "origin", + remoteUrl: "https://forgejo.local/maria/project.git", + }, + }); + assert.strictEqual(remote.baseUrl, "https://forgejo.local"); + }).pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ exists: () => Effect.succeed(false) }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => { + throw new Error("tea must handle its own HTTP request"); + }), + ), + Effect.provide( + TestSourceControlHost.layer({ + settings: withForgejoDefault("code.test"), + process: { + run: (input) => { + assert.deepStrictEqual(input.args, ["login", "list", "--output", "json"]); + return Effect.succeed( + processOutput( + encodeJson([ + { name: "work", url: "https://forgejo.local", user: "maria", default: "true" }, + { name: "code", url: "https://code.test", user: "maria", default: "false" }, + ]), + ), + ); + }, + }, + }), + ), + ), +); + it.effect("does not call a valid fj login on an HTTP-only server unauthenticated", () => Effect.gen(function* () { const spec = yield* ForgejoSourceControlProvider.makeDiscovery.pipe( diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 8a1b8d49b876f..5283d153e291c 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -23,6 +23,27 @@ import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullR const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); +/** tea's login for `server` when Settings names one, else its default login. */ +const teaAuth = ( + stdout: string, + server?: NonNullable>, +) => { + const logins = ForgejoCli.parseForgejoLogins(stdout); + const login = server + ? ForgejoCli.matchForgejoLogin(logins, server, undefined, true) + : (logins.find((entry) => entry.default === "true") ?? logins[0]); + return login + ? providerAuth({ + status: login.valid === "true" ? "authenticated" : "unauthenticated", + account: login.user, + host: ForgejoCli.parseForgejoRemote(login.url)?.host, + }) + : providerAuth({ + status: "unauthenticated", + detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.", + }); +}; + export const discovery = { type: "cli", kind: SourceControlProviderKind.make("forgejo"), @@ -31,20 +52,7 @@ export const discovery = { versionArgs: ["--version"], authArgs: ["login", "status", "--output", "json"], remoteRefinementArgs: () => ["login", "list", "--output", "json"], - parseAuth: (input) => { - const logins = ForgejoCli.parseForgejoLogins(input.stdout); - const login = logins.find((entry) => entry.default === "true") ?? logins[0]; - return login - ? providerAuth({ - status: login.valid === "true" ? "authenticated" : "unauthenticated", - account: login.user, - host: ForgejoCli.parseForgejoRemote(login.url)?.host, - }) - : providerAuth({ - status: "unauthenticated", - detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.", - }); - }, + parseAuth: (input) => teaAuth(input.stdout), refineUnknownRemote: (input) => { const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl); const login = @@ -68,7 +76,7 @@ export const discovery = { export const makeDiscovery = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; - const { process } = yield* SourceControlHost.SourceControlHost; + const { process, settings } = yield* SourceControlHost.SourceControlHost; const listLogins = cli.listLogins; if (!listLogins) return discovery; return { @@ -94,45 +102,70 @@ export const makeDiscovery = Effect.gen(function* () { const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl })); const logins = Result.isSuccess(credentials) ? credentials.success : []; const remote = ForgejoCli.parseForgejoRemote(remoteUrl); - const login = - (remote && ForgejoCli.matchForgejoLogin(logins, remote)) || - logins.find((entry) => entry.default === "true") || - logins[0]; - const fj = yield* probeSourceControlProvider({ - // fj reads the cwd repository even with --host and fails on an unborn branch. - cwd: yield* HostProcess.HomeDirectory, - process, - spec: { - ...discovery, - executable: "fj", - versionArgs: ["version"], - authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"], - parseAuth: (result) => - Result.isFailure(credentials) - ? providerAuth({ - status: "unknown", - detail: "Could not read fj authentication storage. Authenticate again with fj.", - }) - : login && result.exitCode === 0 + const remoteLogin = remote && ForgejoCli.matchForgejoLogin(logins, remote); + const fallback = remote ? undefined : yield* ForgejoCli.defaultServer(settings); + const fallbackLogin = + fallback && ForgejoCli.matchForgejoLogin(logins, fallback.remote, undefined, true); + // A remote's own login decides alone, then the Settings default; else any login that works. + const candidates = remote + ? remoteLogin + ? [remoteLogin] + : [] + : fallback + ? fallbackLogin + ? [fallbackLogin] + : [] + : [ + ...logins.filter((entry) => entry.default === "true"), + ...logins.filter((entry) => entry.default !== "true"), + ]; + // fj reads the cwd repository even with --host and fails on an unborn branch. + const home = yield* HostProcess.HomeDirectory; + const probeFj = (login: (typeof logins)[number] | undefined) => + probeSourceControlProvider({ + cwd: home, + process, + spec: { + ...discovery, + executable: "fj", + versionArgs: ["version"], + authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"], + parseAuth: (result) => + Result.isFailure(credentials) ? providerAuth({ - status: "authenticated", - account: login.user, - host: ForgejoCli.parseForgejoRemote(login.url)?.host, + status: "unknown", + detail: "Could not read fj authentication storage. Authenticate again with fj.", }) - : // fj prints this for transport failures (TLS, connect, DNS), never for a rejected token. - login && result.stderr.includes("error sending request for url") + : login && result.exitCode === 0 ? providerAuth({ - status: "unknown", - detail: `Could not reach ${login.url} to verify the fj login.`, + status: "authenticated", + account: login.user, host: ForgejoCli.parseForgejoRemote(login.url)?.host, }) - : providerAuth({ - status: "unauthenticated", - detail: - "Authenticate this server with `fj --host auth add-token`. For a server under a URL subpath, such as `https://example.com/forgejo`, use `tea login add` instead.", - }), - }, - }); + : // fj prints this for transport failures (TLS, connect, DNS), never for a rejected token. + login && result.stderr.includes("error sending request for url") + ? providerAuth({ + status: "unknown", + detail: `Could not reach ${login.url} to verify the fj login.`, + host: ForgejoCli.parseForgejoRemote(login.url)?.host, + }) + : providerAuth({ + status: "unauthenticated", + detail: + "Authenticate this server with `fj --host auth add-token`. For a server under a URL subpath, such as `https://example.com/forgejo`, use `tea login add` instead.", + }), + }, + }); + let login = candidates[0]; + let fj = yield* probeFj(login); + for (const candidate of candidates.slice(1)) { + if (fj.status !== "available" || fj.auth.status === "authenticated") break; + const next = yield* probeFj(candidate); + if (next.auth.status === "authenticated") { + login = candidate; + fj = next; + } + } if (fj.status === "available" && (login || Result.isFailure(credentials))) { if (login && fj.auth.status === "authenticated" && cli.getAccount) { const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result); @@ -153,7 +186,17 @@ export const makeDiscovery = Effect.gen(function* () { } return fj; } - const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery }); + const tea = yield* probeSourceControlProvider({ + cwd, + process, + spec: + remote || fallback + ? { + ...discovery, + parseAuth: (input) => teaAuth(input.stdout, remote ?? fallback?.remote), + } + : discovery, + }); // Discovery keeps the install hint only for an absent executable; a slow or broken fj // explains itself better than tea's install advice. const fjAbsent = fj.status === "missing" && fj.installHint === discovery.installHint; diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index 73bd2caa8ae8f..83d25a91cf643 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -1,4 +1,10 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { + makeProviderSettingsSchema, + SourceControlProviderKind, + TrimmedString, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { canonicalRepositoryPath } from "@t3tools/shared/git"; import { buildCommitUrl, @@ -29,6 +35,19 @@ const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/src\/(?:branch|tag|commit const KIND = SourceControlProviderKind.make("forgejo"); +export const settings = makeProviderSettingsSchema({ + defaultServer: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "Default server", + description: + "The fj or tea login used when a project has no Forgejo remote, such as when publishing. A project's remote always uses its own login.", + providerSettingsForm: { placeholder: "https://codeberg.org" }, + }), + ), +}); +export type ForgejoSettings = typeof settings.Type; + function isForgejoHost(hostname: string): boolean { const host = hostname.toLowerCase(); return ( @@ -88,6 +107,7 @@ export const definition = defineSourceControl({ publishHost: (signedInHost) => signedInHost ?? "your server", newRepositoryOwner: (account) => (account ? { owner: account } : null), defaultCloneTransport: "https", + settings, // The server's resolved web URL wins; otherwise an HTTP remote on the same host names the // origin, which may carry a port. SSH remotes say nothing about the web origin. changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => From 3be8ec4a697d6af78fd845e8610585ac52718602 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:49:25 -0300 Subject: [PATCH 05/87] fix(desktop): a refused macOS update install no longer leaves the app stuck On macOS, Squirrel reports a refused install after quitAndInstall returns, through the update state. The update pill treated the accepted call as success and showed nothing, and the lifecycle kept its quit marked "allowed", so the next quit skipped backend shutdown. The pill now waits for that install error and reports it, and the lifecycle resets a quit that the updater recovered from. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopLifecycle.test.ts | 53 +++++++++++++++++++ apps/desktop/src/app/DesktopLifecycle.ts | 7 +++ .../SidebarUpdatePill.browser.test.tsx | 37 ++++++++++++- .../components/sidebar/SidebarUpdatePill.tsx | 14 ++++- 4 files changed, 107 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..7016cdda3ff2e 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -141,6 +141,8 @@ describe("DesktopLifecycle", () => { Effect.gen(function* () { const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; yield* lifecycle.register; + // DesktopUpdates sets this before calling quitAndInstall. + yield* Ref.set((yield* DesktopState.DesktopState).quitting, true); appListeners.get("before-quit-for-update")?.(); yield* Effect.yieldNow; @@ -166,6 +168,57 @@ describe("DesktopLifecycle", () => { }, ); + it.effect("shuts down in order on a quit after the updater refused to install", () => + Effect.gen(function* () { + const appListeners = new Map void>(); + const quitRequested = yield* Deferred.make(); + const layerEnvironment = Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + platform: "darwin", + isDevelopment: false, + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const layer = DesktopLifecycle.layer.pipe( + Layer.provideMerge( + layerElectronApp( + appListeners, + Deferred.succeed(quitRequested, undefined).pipe(Effect.asVoid), + ), + ), + Layer.provideMerge(layerElectronTheme), + Layer.provideMerge(layerElectronWindow()), + Layer.provideMerge(layerDesktopWindow()), + Layer.provideMerge(layerEnvironment), + Layer.provideMerge(DesktopShutdown.layer), + Layer.provideMerge(DesktopState.layer), + ); + + yield* Effect.scoped( + Effect.gen(function* () { + const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; + const state = yield* DesktopState.DesktopState; + const shutdown = yield* DesktopShutdown.DesktopShutdown; + yield* lifecycle.register; + + yield* Ref.set(state.quitting, true); + appListeners.get("before-quit-for-update")?.(); + // DesktopUpdates.recoverFailedInstall after Squirrel reports an install error. + yield* Ref.set(state.quitting, false); + + let prevented = false; + appListeners.get("before-quit")?.({ + preventDefault: () => { + prevented = true; + }, + } as Electron.Event); + + assert.isTrue(prevented, "the recovered backends must stop before the app quits"); + yield* shutdown.awaitRequest; + yield* shutdown.markComplete; + yield* Deferred.await(quitRequested); + }), + ).pipe(Effect.provide(layer)); + }), + ); + it.effect("destroys windows before waiting for backend shutdown", () => Effect.gen(function* () { const appListeners = new Map void>(); diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 9568e72dde310..252c23876fae0 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -254,9 +254,14 @@ export const make = DesktopLifecycle.of({ const electronApp = yield* ElectronApp.ElectronApp; const electronTheme = yield* ElectronTheme.ElectronTheme; const environment = yield* DesktopEnvironment.DesktopEnvironment; + const desktopState = yield* DesktopState.DesktopState; const context = yield* Effect.context(); const runEffect = Effect.runPromiseWith(context); const quit: QuitState = { phase: "running", waitingSinceNanos: 0n }; + // Every allowed quit keeps `quitting` set; a refused update install clears it on recovery. + const dropRecoveredUpdaterQuit = () => { + if (quit.phase === "allowed" && !Ref.getUnsafe(desktopState.quitting)) quit.phase = "running"; + }; yield* electronTheme.onUpdated(() => { void runEffect( desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")), @@ -282,6 +287,7 @@ export const make = DesktopLifecycle.of({ ); }); yield* electronApp.on("before-quit", (event: Electron.Event) => { + dropRecoveredUpdaterQuit(); handleBeforeQuit(event, runEffect, quit); }); yield* electronApp.on("activate", () => { @@ -312,6 +318,7 @@ export const make = DesktopLifecycle.of({ process, "exit", (exitCode: number) => { + dropRecoveredUpdaterQuit(); Effect.runSyncWith(context)( Effect.gen(function* () { const shutdown = yield* DesktopShutdown.DesktopShutdown; diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx index 0f751bc52aef6..f0f761319c1e4 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx @@ -1,10 +1,10 @@ -import type { DesktopUpdateState } from "@t3tools/contracts"; +import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { act, render } from "../../../test/render"; -import { SidebarUpdatePill } from "./SidebarUpdatePill"; +import { installLocalUpdate, SidebarUpdatePill } from "./SidebarUpdatePill"; import type { UpdateEverythingRow } from "./updateEverything.logic"; const mocks = vi.hoisted(() => { @@ -168,3 +168,36 @@ describe("SidebarUpdatePill update everything", () => { await expect.element(row.getByRole("cell", { name: "Claude", exact: true })).toBeVisible(); }); }); + +describe("installLocalUpdate", () => { + it("reports an install the updater refuses after accepting it", async () => { + const downloaded = { ...nightlyUpdate([]), status: "downloaded" as const }; + const subscribed = Promise.withResolvers<(state: DesktopUpdateState) => void>(); + let listener: ((state: DesktopUpdateState) => void) | undefined; + const bridge = { + installUpdate: async () => { + expect(listener).toBeTypeOf("function"); + return { accepted: true, completed: false, state: downloaded }; + }, + onUpdateState: (callback: (state: DesktopUpdateState) => void) => { + listener = callback; + subscribed.resolve(callback); + return () => {}; + }, + } as unknown as DesktopBridge; + const reportError = vi.fn(); + + const installed = installLocalUpdate(bridge, reportError); + const pushState = await Promise.race([subscribed.promise, installed]); + expect(pushState).toBeTypeOf("function"); + // macOS reports a declined install prompt through the updater's error event, after the IPC. + (pushState as (state: DesktopUpdateState) => void)({ + ...downloaded, + message: "Install was cancelled.", + errorContext: "install", + }); + + await expect(installed).resolves.toBe(false); + expect(reportError).toHaveBeenCalledWith("Could not install update", "Install was cancelled."); + }); +}); diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index ce45fe8bf73a4..432eeecbffb62 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -175,6 +175,10 @@ export async function installLocalUpdate( reportError: ReportLocalUpdateError = toastUpdateError, expectedVersion?: string, ): Promise { + const failure = Promise.withResolvers(); + const unsubscribe = bridge.onUpdateState((state) => { + if (state.errorContext === "install" && state.message) failure.resolve(state.message); + }); try { const result = await bridge.installUpdate(expectedVersion); if (!result.accepted) { @@ -184,8 +188,12 @@ export async function installLocalUpdate( const actionError = shouldToastDesktopUpdateActionResult(result) ? getDesktopUpdateActionError(result) : null; - if (!actionError) return true; - reportError(m(msg("Could not install update")), actionError); + if (actionError) { + reportError(m(msg("Could not install update")), actionError); + return false; + } + // A success quits this app. macOS reports a refused install later, through the update state. + reportError(m(msg("Could not install update")), await failure.promise); return false; } catch (error) { reportError( @@ -193,6 +201,8 @@ export async function installLocalUpdate( thrownErrorMessage(error, m) ?? m(msg("An unexpected error occurred.")), ); return false; + } finally { + unsubscribe(); } } From 5b3e5083dbc53bf03e582d2ae64727c581411c0d Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:56:11 -0300 Subject: [PATCH 06/87] fix(mobile): pasting the app link that `t3 pair` prints now pairs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `t3 pair` prints a `t3code://pair?pairingUrl=…` app link. The QR scanner unwrapped it, but the manual pairing field passed it to parsePairingUrl as is and could not read a host or code. Both paths now use the shared readPairingAppLink. Co-Authored-By: Claude Opus 5.5 --- .../src/features/connection/pairing.test.ts | 11 +++++++++++ apps/mobile/src/features/connection/pairing.ts | 18 +++--------------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/connection/pairing.test.ts b/apps/mobile/src/features/connection/pairing.test.ts index 466fbfa7a282d..543106a8956a2 100644 --- a/apps/mobile/src/features/connection/pairing.test.ts +++ b/apps/mobile/src/features/connection/pairing.test.ts @@ -43,4 +43,15 @@ describe("parsePairingUrl", () => { code: "pairing-token", }); }); + + it("unwraps the app link that `t3 pair` prints", () => { + expect( + parsePairingUrl( + "t3code://pair?pairingUrl=http%3A%2F%2F192.168.1.100%3A3773%2Fpair%23token%3Dpairing-token", + ), + ).toEqual({ + host: "http://192.168.1.100:3773", + code: "pairing-token", + }); + }); }); diff --git a/apps/mobile/src/features/connection/pairing.ts b/apps/mobile/src/features/connection/pairing.ts index d596343d3f90e..e68dbfc78b730 100644 --- a/apps/mobile/src/features/connection/pairing.ts +++ b/apps/mobile/src/features/connection/pairing.ts @@ -1,11 +1,9 @@ -import { readHostedPairingRequest } from "@t3tools/shared/remote"; +import { readHostedPairingRequest, readPairingAppLink } from "@t3tools/shared/remote"; import * as Schema from "effect/Schema"; import { msg } from "gt-react-native"; import { m } from "../../i18n/messages"; -const MOBILE_PAIRING_URL_PARAM = "pairingUrl"; - function isIpLiteral(host: string): boolean { try { const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, ""); @@ -46,7 +44,7 @@ export function buildPairingUrl(host: string, code: string): string { } export function parsePairingUrl(url: string): { host: string; code: string } { - const trimmed = url.trim(); + const trimmed = readPairingAppLink(url.trim()) ?? url.trim(); if (!trimmed) return { host: "", code: "" }; try { @@ -79,15 +77,5 @@ export function extractPairingUrlFromQrPayload(payload: string): string { throw new PairingQrPayloadEmptyError({}); } - try { - const url = new URL(trimmed); - if (url.protocol === "t3code:") { - const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? ""; - if (pairingUrl.length > 0) { - return pairingUrl; - } - } - } catch {} - - return trimmed; + return readPairingAppLink(trimmed) ?? trimmed; } From 617617a543b615187946d4732a2c3394baa0bb09 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 12:57:44 -0300 Subject: [PATCH 07/87] test(shared): link printenv instead of copying it so the shell test runs on macOS macOS kills a copied system binary because its code signature no longer matches the path, so readEnvironmentFromLoginShell's fixture failed on macOS. A symlink keeps the original signed binary. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/shell.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4174dcc364972..d4679c3a7c2a1 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -130,7 +130,8 @@ describe("readEnvironmentFromLoginShell", () => { encoding: "utf8", env: { PATH: process.env.PATH }, }).trim(); - NodeFS.copyFileSync(printenv, NodePath.join(tools, "printenv")); + // macOS kills a copied system binary (its signature no longer matches the path). + NodeFS.symlinkSync(printenv, NodePath.join(tools, "printenv")); vi.stubEnv("PATH", tools); const shellPath = NodePath.join(home, "bin"); const bashEnv = NodePath.join(home, "env.bash"); From 2ba4867532741dae0148f157688d59c4cc36d2c0 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 13:01:24 -0300 Subject: [PATCH 08/87] feat(web): filter the sidebar to one environment With several environments connected, the sidebar mixed every machine's projects and threads. A device menu next to the project filter now narrows it to one environment. Repository groups list only that environment's copies, the button shows a dot when a hidden environment needs the user, and the menu counts needs-you and working threads per environment. The choice persists per device. Opening a hidden thread or removing the chosen environment shows all environments again. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/Sidebar.logic.test.ts | 39 ++ apps/web/src/components/Sidebar.logic.ts | 37 ++ apps/web/src/components/Sidebar.tsx | 470 ++++++++++-------- .../sidebar/SidebarEnvironmentScopeMenu.tsx | 124 +++++ apps/web/src/hooks/useSidebarProjectGroups.ts | 11 +- apps/web/src/i18n/translations/de.json | 5 + apps/web/src/i18n/translations/en.json | 5 + apps/web/src/i18n/translations/es.json | 5 + apps/web/src/i18n/translations/fr.json | 5 + apps/web/src/i18n/translations/ja.json | 5 + apps/web/src/i18n/translations/ko.json | 5 + apps/web/src/i18n/translations/pt-BR.json | 5 + apps/web/src/i18n/translations/ru.json | 5 + apps/web/src/i18n/translations/sv.json | 5 + apps/web/src/i18n/translations/zh.json | 5 + apps/web/src/uiStateStore.test.ts | 14 + apps/web/src/uiStateStore.ts | 13 + docs/user/thread-sidebar.md | 10 + 18 files changed, 553 insertions(+), 215 deletions(-) create mode 100644 apps/web/src/components/sidebar/SidebarEnvironmentScopeMenu.tsx diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 76f8c8c30c2d5..8601efac1bb00 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -16,6 +16,8 @@ import { resolveSidebarSweepKeys, resolveSidebarRowStatus, resolveSidebarThreadStatus, + resolveSidebarEnvironmentScope, + summarizeSidebarEnvironmentWork, resolveThreadStatusPill, resolveWindowTitleThreadStatus, resolveWorkingStartedAt, @@ -174,6 +176,43 @@ describe("orderItemsByPreferredIds", () => { }); }); +describe("sidebar environment filter", () => { + const laptop = EnvironmentId.make("env-laptop"); + const server = EnvironmentId.make("env-server"); + + it("reads a removed environment as every environment", () => { + const environments = [{ environmentId: laptop }]; + expect(resolveSidebarEnvironmentScope(laptop, environments)).toBe(laptop); + expect(resolveSidebarEnvironmentScope(server, environments)).toBeNull(); + expect(resolveSidebarEnvironmentScope(null, environments)).toBeNull(); + }); + + it("counts approvals and running work per environment, skipping archived and idle threads", () => { + const base = { + hasPendingApprovals: false, + hasPendingUserInput: false, + runtime: null, + archivedAt: null, + }; + const running = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: "2026-03-09T10:00:00.000Z", + }; + const work = summarizeSidebarEnvironmentWork([ + { ...base, environmentId: server, hasPendingApprovals: true }, + { ...base, environmentId: server, runtime: running }, + { ...base, environmentId: server, hasPendingUserInput: true, archivedAt: "2026-03-09" }, + { ...base, environmentId: laptop }, + ]); + expect(work.get(server)).toEqual({ needsYou: 1, working: 1 }); + expect(work.has(laptop)).toBe(false); + }); +}); + describe("resolveSidebarThreadStatus", () => { const runtime = { status: "running" as const, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index f97a6e33fb864..d595e47da02df 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -957,6 +957,43 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si return "ready"; } +/** The stored environment filter, or every environment once that environment is gone. */ +export function resolveSidebarEnvironmentScope( + stored: string | null, + environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>, +): EnvironmentId | null { + return ( + environments.find((environment) => environment.environmentId === stored)?.environmentId ?? null + ); +} + +export interface SidebarEnvironmentWork { + readonly needsYou: number; + readonly working: number; +} + +/** Per environment, the threads waiting on the user and the ones running, so a filter that hides them can say so. */ +export function summarizeSidebarEnvironmentWork( + threads: ReadonlyArray< + SidebarThreadStatusInput & Pick + >, +): ReadonlyMap { + const work = new Map(); + for (const thread of threads) { + if (thread.archivedAt !== null) continue; + const status = resolveSidebarThreadStatus(thread); + const needsYou = status === "approval" || status === "input" || status === "request"; + const working = status === "working" || status === "preparing"; + if (!needsYou && !working) continue; + const current = work.get(thread.environmentId) ?? { needsYou: 0, working: 0 }; + work.set(thread.environmentId, { + needsYou: current.needsYou + (needsYou ? 1 : 0), + working: current.working + (working ? 1 : 0), + }); + } + return work; +} + /** Sidebar row status: a failure the user has already opened settles to ready, like Done. */ export function resolveSidebarRowStatus( thread: ThreadStatusInput & SidebarThreadStatusInput, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 7157e7aaa75b9..deebe3d9af424 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -141,6 +141,7 @@ import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; import { + useEnvironments, useEnvironmentIdentities, useConnectedEnvironmentIds, useEnvironmentMachines, @@ -200,6 +201,8 @@ import { resolveSidebarDropTarget, resolveSidebarDropVerb, resolveSidebarThreadSection, + resolveSidebarEnvironmentScope, + summarizeSidebarEnvironmentWork, resolveSidebarReorderableThreadKeys, searchSidebarThreads, shouldCreateNewThreadInCurrentProject, @@ -257,6 +260,7 @@ import { import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; +import { SidebarEnvironmentScopeMenu } from "./sidebar/SidebarEnvironmentScopeMenu"; import { TooltipProvider } from "./ui/tooltip"; import { composerDraftHasUserContent, @@ -810,13 +814,13 @@ function isOptimisticDropReleased(input: { } // Build maps in a hook so the compiler can prove they are frozen and cache them. -function useSidebarLookups() { +function useSidebarLookups(environmentScope: EnvironmentId | null) { const gt = useGT(); const projects = useProjects(); const environments = useEnvironmentIdentities(); const serverConfigs = useServerConfigs(); const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom); - const projectGroups = useSidebarProjectGroups(); + const projectGroups = useSidebarProjectGroups(environmentScope); const environmentLabelById = new Map( environments.map((environment) => [environment.environmentId, environment.label] as const), ); @@ -909,6 +913,19 @@ function readRouteThreadKey(router: AnyRouter): string | null { export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) { const gt = useGT(); const messages = useMessages(); + const { environments: availableEnvironments } = useEnvironments(); + const environmentIdentities = useEnvironmentIdentities().filter(({ environmentId }) => + availableEnvironments.some( + (environment) => environment.environmentId === environmentId && environment.entry.enabled, + ), + ); + const storedEnvironmentScope = useUiStateStore((store) => store.sidebarEnvironmentScope); + const setPersistedEnvironmentScope = useUiStateStore((store) => store.setSidebarEnvironmentScope); + // A removed environment reads as all; the stored id stays, like a missing project scope. + const environmentScope = resolveSidebarEnvironmentScope( + storedEnvironmentScope, + environmentIdentities, + ); const { projects, serverConfigs, @@ -919,7 +936,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectDisplayNameByKey, projectGroupByScopeKey, projectScopeItems: lookupProjectScopeItems, - } = useSidebarLookups(); + } = useSidebarLookups(environmentScope); const delegatedUnderParent = useDelegatedUnderParent(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); @@ -1082,6 +1099,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys(keys); scrollSidebarToTop(sidebarContentRef.current); }; + const setEnvironmentScope = (environmentId: EnvironmentId | null) => { + clearSelection(); + setPersistedEnvironmentScope(environmentId); + scrollSidebarToTop(sidebarContentRef.current); + }; // A scope whose project is gone reads as all projects once every snapshot has // loaded. The stored keys are left alone, so the scope returns with its project. // An archived project's scope reads as all projects, matching the menu. @@ -1098,14 +1120,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const chosenProjectGroups = scopeGroups.filter((project) => chosenProjectScopeKeys.includes(project.projectKey), ); + // Groups already hold only the filtered environment's members, so an environment filter + // without a project scope is every project left in them. const chosenScopeProjectKeys = - chosenProjectGroups.length === 0 + chosenProjectGroups.length === 0 && environmentScope === null ? null : new Set( - chosenProjectGroups.flatMap((project) => - project.memberProjectRefs.map( - (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, - ), + (chosenProjectGroups.length === 0 ? projectGroups : chosenProjectGroups).flatMap( + (project) => + project.memberProjectRefs.map( + (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, + ), ), ); const threads = useQuietThreadShells(); @@ -1157,7 +1182,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (!revealWidensScope) return; clearSelection(); setPersistedProjectScopeKeys([]); - }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); + setPersistedEnvironmentScope(null); + }, [ + clearSelection, + revealWidensScope, + setPersistedProjectScopeKeys, + setPersistedEnvironmentScope, + ]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); const scratchMachineLabelFor = ( @@ -1194,7 +1225,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs); const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys; const threadSearch = useThreadSearch( - connectedEnvironmentIds, + environmentScope === null + ? connectedEnvironmentIds + : connectedEnvironmentIds.filter((environmentId) => environmentId === environmentScope), threadSearchQuery, scopedProjectGroups.length === 0 ? {} @@ -2984,215 +3017,226 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve fixedHeader={ 0} + hasProjects={projects.length > 0} projectScope={ - item.label} - isItemEqualToValue={(a, b) => a.value === b.value} - open={projectScopeMenuState.open} - onOpenChange={(open, eventDetails) => { - if (eventDetails.isCanceled) return; - if (open) suppressNextScopeChangeRef.current = false; - dispatchProjectScopeMenu({ type: "open-changed", open }); - }} - onItemHighlighted={(item) => { - highlightedProjectScopeKeyRef.current = item?.value ?? null; - }} - value={selectedProjectScopeItem} - onValueChange={(item, eventDetails) => { - if (suppressNextScopeChangeRef.current) { - suppressNextScopeChangeRef.current = false; - return; - } - if (!item) return; - if (item.value === "all") { - setProjectScopeKeys([]); - } else if ( - eventDetails.event instanceof MouseEvent && - eventDetails.event.shiftKey - ) { - // Canceling skips Base UI's commit, which would freeze the search query, and its close. - eventDetails.cancel(); - toggleProjectScopeKey(item.value); - } else { - setProjectScopeKeys([item.value]); - } - }} - > - 0 - ? gt("Filter threads by project: {projects}", { - projects: scopedProjectGroups - .map((project) => project.displayName) - .join(", "), - }) - : gt("Filter threads by project") - } - /> - } - > - {scopedProjectGroups.length > 1 ? ( - - {scopedProjectGroups.slice(0, 2).map((project, index) => ( - - - - ))} - - ) : scopedProjectGroups[0] ? ( - - - - ) : ( - - )} - - {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} - closeType === "keyboard"} + <> + {environmentIdentities.length > 1 ? ( + + ) : null} + item.label} + isItemEqualToValue={(a, b) => a.value === b.value} + open={projectScopeMenuState.open} + onOpenChange={(open, eventDetails) => { + if (eventDetails.isCanceled) return; + if (open) suppressNextScopeChangeRef.current = false; + dispatchProjectScopeMenu({ type: "open-changed", open }); + }} + onItemHighlighted={(item) => { + highlightedProjectScopeKeyRef.current = item?.value ?? null; + }} + value={selectedProjectScopeItem} + onValueChange={(item, eventDetails) => { + if (suppressNextScopeChangeRef.current) { + suppressNextScopeChangeRef.current = false; + return; + } + if (!item) return; + if (item.value === "all") { + setProjectScopeKeys([]); + } else if ( + eventDetails.event instanceof MouseEvent && + eventDetails.event.shiftKey + ) { + // Canceling skips Base UI's commit, which would freeze the search query, and its close. + eventDetails.cancel(); + toggleProjectScopeKey(item.value); + } else { + setProjectScopeKeys([item.value]); + } + }} > - { - if ( - event.defaultPrevented || - event.nativeEvent.isComposing || - event.keyCode === 229 - ) { - return; - } - const scopeKey = highlightedProjectScopeKeyRef.current; - const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null; - // The thread pin shortcut pins the highlighted project here. - if ( - project && - canPinProject(project) && - isProjectPinShortcut(event, keybindings) - ) { - event.preventDefault(); - event.stopPropagation(); - toggleProjectGroupPin(project); - return; - } - if (event.ctrlKey || event.altKey || event.metaKey) return; - if (event.shiftKey && event.key === "Enter") { - if (!project) return; - event.preventDefault(); - toggleProjectScopeKey(project.projectKey); - return; - } - if ( - event.key !== "ContextMenu" && - !(event.shiftKey && event.key === "F10") - ) { - return; - } - if (project) handleProjectSettings(event, project); - }} - onChange={(event) => - dispatchProjectScopeMenu({ - type: "query-changed", - query: event.target.value, - }) + 0 + ? gt("Filter threads by project: {projects}", { + projects: scopedProjectGroups + .map((project) => project.displayName) + .join(", "), + }) + : gt("Filter threads by project") + } + /> } - /> - - No matching projects. - - - {(item: (typeof projectScopeItems)[number]) => { - const project = projectGroupByScopeKey.get(item.value) ?? null; - const isSelected = project - ? projectScopeKeys.includes(item.value) - : projectScopeKeys.length === 0; - return ( - { - if (project) handleProjectSettings(event, project); - }} - > - + > + {scopedProjectGroups.length > 1 ? ( + + {scopedProjectGroups.slice(0, 2).map((project, index) => ( + + + + ))} + + ) : scopedProjectGroups[0] ? ( + + + + ) : ( + + )} + + {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} + closeType === "keyboard"} + > + { + if ( + event.defaultPrevented || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) { + return; + } + const scopeKey = highlightedProjectScopeKeyRef.current; + const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null; + // The thread pin shortcut pins the highlighted project here. + if ( + project && + canPinProject(project) && + isProjectPinShortcut(event, keybindings) + ) { + event.preventDefault(); + event.stopPropagation(); + toggleProjectGroupPin(project); + return; + } + if (event.ctrlKey || event.altKey || event.metaKey) return; + if (event.shiftKey && event.key === "Enter") { + if (!project) return; + event.preventDefault(); + toggleProjectScopeKey(project.projectKey); + return; + } + if ( + event.key !== "ContextMenu" && + !(event.shiftKey && event.key === "F10") + ) { + return; + } + if (project) handleProjectSettings(event, project); + }} + onChange={(event) => + dispatchProjectScopeMenu({ + type: "query-changed", + query: event.target.value, + }) + } + /> + + No matching projects. + + + {(item: (typeof projectScopeItems)[number]) => { + const project = projectGroupByScopeKey.get(item.value) ?? null; + const isSelected = project + ? projectScopeKeys.includes(item.value) + : projectScopeKeys.length === 0; + return ( + { + if (project) handleProjectSettings(event, project); + }} + > + + {project ? ( + + ) : ( + + )} + + {item.label} + {project && showProjectEnvironments ? ( + + ) : null} {project ? ( - + toggleProjectGroupPin(project)} + /> + ) : null + } + settings={ + + } + /> ) : ( - + // Keeps "All projects" as tall as the project rows. + )} - - {item.label} - {project && showProjectEnvironments ? ( - - ) : null} - {project ? ( - toggleProjectGroupPin(project)} - /> - ) : null - } - settings={ - - } - /> - ) : ( - // Keeps "All projects" as tall as the project rows. - - )} - - ); - }} - - - + + ); + }} + + + + } onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} diff --git a/apps/web/src/components/sidebar/SidebarEnvironmentScopeMenu.tsx b/apps/web/src/components/sidebar/SidebarEnvironmentScopeMenu.tsx new file mode 100644 index 0000000000000..fd3ee8001e46e --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarEnvironmentScopeMenu.tsx @@ -0,0 +1,124 @@ +import type { EnvironmentId, EnvironmentMachineKind } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { MonitorSmartphoneIcon } from "lucide-react"; + +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; +import type { SidebarEnvironmentWork } from "../Sidebar.logic"; +import { + Menu, + MenuGroupLabel, + MenuItemDetail, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuTrigger, +} from "../ui/menu"; +import { SidebarHeaderIconButton } from "./SidebarThreadHeader"; + +const ALL_ENVIRONMENTS = "all"; + +/** + * Narrows the sidebar to one environment. It only hides rows: connections stay as they are, and + * the trigger keeps a dot while a hidden environment has a thread waiting on the user. + */ +export function SidebarEnvironmentScopeMenu({ + environments, + machineByEnvironmentId, + value, + work, + onValueChange, +}: { + readonly environments: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly label: string; + }>; + readonly machineByEnvironmentId: ReadonlyMap; + readonly value: EnvironmentId | null; + readonly work: ReadonlyMap; + readonly onValueChange: (environmentId: EnvironmentId | null) => void; +}) { + const gt = useGT(); + const selected = environments.find((environment) => environment.environmentId === value); + const hiddenNeedsYou = + value === null + ? 0 + : [...work].reduce( + (total, [environmentId, entry]) => + environmentId === value ? total : total + entry.needsYou, + 0, + ); + const label = selected + ? hiddenNeedsYou > 0 + ? gt( + "{count, plural, one {Showing {environment}. {count} thread elsewhere needs you} other {Showing {environment}. {count} threads elsewhere need you}}", + { environment: selected.label, count: hiddenNeedsYou }, + ) + : gt("Showing {environment}", { environment: selected.label }) + : gt("Filter threads by environment"); + const detail = (entry: SidebarEnvironmentWork | undefined) => { + if (entry === undefined) return null; + const parts = [ + entry.needsYou > 0 + ? gt("{count, plural, one {{count} needs you} other {{count} need you}}", { + count: entry.needsYou, + }) + : null, + entry.working > 0 ? gt("{count} working", { count: entry.working }) : null, + ].filter((part) => part !== null); + return parts.length === 0 ? null : {parts.join(" · ")}; + }; + + return ( + + }> + {selected ? ( + + ) : ( + + )} + {hiddenNeedsYou > 0 ? ( + + ) : null} + + + {gt("Show threads from")} + + onValueChange(next === ALL_ENVIRONMENTS ? null : (next as EnvironmentId)) + } + > + + + + {gt("All environments")} + + + {environments.map((environment) => ( + + + + {environment.label} + {detail(work.get(environment.environmentId))} + + + ))} + + + + ); +} diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index 7a0036d35786d..f110bc380fe1a 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -1,3 +1,4 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import { useMessages } from "gt-react"; import { orderItemsByPreferredIds, sortSidebarV2ProjectGroups } from "../components/Sidebar.logic"; @@ -11,8 +12,14 @@ import { useDelegatedUnderParent, useProjects, useQuietThreadShells } from "../s import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useClientSettings } from "./useSettings"; -export function useSidebarProjectGroups() { - const projects = useProjects(); +// With an environment, groups hold only that environment's members, so a repository group keeps +// its key but lists, targets and counts just the copies there. +export function useSidebarProjectGroups(environmentId: EnvironmentId | null = null) { + const allProjects = useProjects(); + const projects = + environmentId === null + ? allProjects + : allProjects.filter((project) => project.environmentId === environmentId); // Activity order lags a running thread's streaming ticks until its next // real change; reading every tick re-rendered the whole sidebar with it. const threads = useQuietThreadShells(); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..2d462f99eda0b 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -11645,6 +11645,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} Anhang} other {{count} Anhänge}}", "ffedb03b620f97a9": "Nicht gesendeter Entwurf", "90a349d827d1dcf5": "Entwurf verwerfen", + "524e4bb76976942f": "{count, plural, one {Zeigt {environment}. {count} Thread woanders braucht dich} other {Zeigt {environment}. {count} Threads woanders brauchen dich}}", + "b082c0602780fbab": "Zeigt {environment}", + "f6dd36e7cc2f9725": "Threads nach Umgebung filtern", + "97884c869683f97f": "{count, plural, one {{count} braucht dich} other {{count} brauchen dich}}", + "1a021ea597900720": "Threads anzeigen von", "ace9f34925fb6905": "Ordner ablegen erfordert die Desktop-App", "327623037d69218f": "Browser geben keine Ordnerpfade weiter. Verwende „Projekt hinzufügen“, um einen Ordner zu wählen.", "effe26aaf2941c69": "Der Server dieses Computers ist noch nicht verbunden", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..aa6130c487890 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -11653,6 +11653,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} attachment} other {{count} attachments}}", "ffedb03b620f97a9": "Unsent draft", "90a349d827d1dcf5": "Discard draft", + "524e4bb76976942f": "{count, plural, one {Showing {environment}. {count} thread elsewhere needs you} other {Showing {environment}. {count} threads elsewhere need you}}", + "b082c0602780fbab": "Showing {environment}", + "f6dd36e7cc2f9725": "Filter threads by environment", + "97884c869683f97f": "{count, plural, one {{count} needs you} other {{count} need you}}", + "1a021ea597900720": "Show threads from", "ace9f34925fb6905": "Dropping folders needs the desktop app", "327623037d69218f": "Browsers do not share folder paths. Use Add project to choose a folder.", "effe26aaf2941c69": "This computer's server is not connected yet", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..c1b91843c07e6 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -11638,6 +11638,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} adjunto} other {{count} adjuntos}}", "ffedb03b620f97a9": "Borrador sin enviar", "90a349d827d1dcf5": "Descartar borrador", + "524e4bb76976942f": "{count, plural, one {Mostrando {environment}. {count} hilo en otro lugar te necesita} other {Mostrando {environment}. {count} hilos en otros lugares te necesitan}}", + "b082c0602780fbab": "Mostrando {environment}", + "f6dd36e7cc2f9725": "Filtrar hilos por entorno", + "97884c869683f97f": "{count, plural, one {{count} te necesita} other {{count} te necesitan}}", + "1a021ea597900720": "Mostrar hilos de", "ace9f34925fb6905": "Para soltar carpetas se necesita la app de escritorio", "327623037d69218f": "Los navegadores no comparten las rutas de las carpetas. Usa Añadir proyecto para elegir una carpeta.", "effe26aaf2941c69": "El servidor de este equipo aún no está conectado", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..4cecec15d281b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -11643,6 +11643,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} pièce jointe} other {{count} pièces jointes}}", "ffedb03b620f97a9": "Brouillon non envoyé", "90a349d827d1dcf5": "Abandonner le brouillon", + "524e4bb76976942f": "{count, plural, one {Affichage de {environment}. {count} fil ailleurs a besoin de vous} other {Affichage de {environment}. {count} fils ailleurs ont besoin de vous}}", + "b082c0602780fbab": "Affichage de {environment}", + "f6dd36e7cc2f9725": "Filtrer les fils par environnement", + "97884c869683f97f": "{count, plural, one {{count} a besoin de vous} other {{count} ont besoin de vous}}", + "1a021ea597900720": "Afficher les fils de", "ace9f34925fb6905": "Déposer des dossiers nécessite l’app de bureau", "327623037d69218f": "Les navigateurs ne partagent pas les chemins des dossiers. Utilisez Ajouter un projet pour choisir un dossier.", "effe26aaf2941c69": "Le serveur de cet ordinateur n’est pas encore connecté", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..341635190faf8 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -11593,6 +11593,11 @@ "20283eb1dd6119f9": "{count, plural, other {{count} 個の添付ファイル}}", "ffedb03b620f97a9": "未送信の下書き", "90a349d827d1dcf5": "下書きを破棄", + "524e4bb76976942f": "{count, plural, other {{environment} を表示中。ほかの {count} 件のスレッドが対応を待っています}}", + "b082c0602780fbab": "{environment} を表示中", + "f6dd36e7cc2f9725": "スレッドを環境で絞り込む", + "97884c869683f97f": "{count, plural, other {{count} 件が対応待ち}}", + "1a021ea597900720": "表示するスレッドの環境", "ace9f34925fb6905": "フォルダーのドロップにはデスクトップアプリが必要です", "327623037d69218f": "ブラウザーはフォルダーのパスを共有しません。「プロジェクトを追加」でフォルダーを選択してください。", "effe26aaf2941c69": "このコンピューターのサーバーはまだ接続されていません", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..a63e4adcf144b 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -11590,6 +11590,11 @@ "20283eb1dd6119f9": "{count, plural, other {첨부 파일 {count}개}}", "ffedb03b620f97a9": "보내지 않은 초안", "90a349d827d1dcf5": "초안 삭제", + "524e4bb76976942f": "{count, plural, other {{environment} 표시 중. 다른 곳의 스레드 {count}개가 응답을 기다립니다}}", + "b082c0602780fbab": "{environment} 표시 중", + "f6dd36e7cc2f9725": "환경별로 스레드 필터링", + "97884c869683f97f": "{count, plural, other {{count}개 응답 대기}}", + "1a021ea597900720": "스레드 표시 위치", "ace9f34925fb6905": "폴더를 끌어다 놓으려면 데스크톱 앱이 필요합니다", "327623037d69218f": "브라우저는 폴더 경로를 공유하지 않습니다. 프로젝트 추가를 사용해 폴더를 선택하세요.", "effe26aaf2941c69": "이 컴퓨터의 서버가 아직 연결되지 않았습니다", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..2671a2d0e03a3 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -11642,6 +11642,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} anexo} other {{count} anexos}}", "ffedb03b620f97a9": "Rascunho não enviado", "90a349d827d1dcf5": "Descartar rascunho", + "524e4bb76976942f": "{count, plural, one {Mostrando {environment}. {count} thread em outro lugar precisa de você} other {Mostrando {environment}. {count} threads em outros lugares precisam de você}}", + "b082c0602780fbab": "Mostrando {environment}", + "f6dd36e7cc2f9725": "Filtrar threads por ambiente", + "97884c869683f97f": "{count, plural, one {{count} precisa de você} other {{count} precisam de você}}", + "1a021ea597900720": "Mostrar threads de", "ace9f34925fb6905": "Soltar pastas exige o app desktop", "327623037d69218f": "Os navegadores não compartilham caminhos de pastas. Use Adicionar projeto para escolher uma pasta.", "effe26aaf2941c69": "O servidor deste computador ainda não está conectado", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..e28ea439fbb7f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -11643,6 +11643,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} вложение} few {{count} вложения} many {{count} вложений} other {{count} вложения}}", "ffedb03b620f97a9": "Неотправленный черновик", "90a349d827d1dcf5": "Удалить черновик", + "524e4bb76976942f": "{count, plural, one {Показано: {environment}. {count} тред в другом месте ждёт вас} few {Показано: {environment}. {count} треда в других местах ждут вас} many {Показано: {environment}. {count} тредов в других местах ждут вас} other {Показано: {environment}. {count} треда в других местах ждут вас}}", + "b082c0602780fbab": "Показано: {environment}", + "f6dd36e7cc2f9725": "Фильтровать треды по окружению", + "97884c869683f97f": "{count, plural, one {{count} ждёт вас} few {{count} ждут вас} many {{count} ждут вас} other {{count} ждут вас}}", + "1a021ea597900720": "Показывать треды из", "ace9f34925fb6905": "Для перетаскивания папок нужно десктопное приложение", "327623037d69218f": "Браузеры не передают пути к папкам. Выберите папку через «Добавить проект».", "effe26aaf2941c69": "Сервер этого компьютера ещё не подключён", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..62e7c4049b3e2 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -11651,6 +11651,11 @@ "20283eb1dd6119f9": "{count, plural, one {{count} bilaga} other {{count} bilagor}}", "ffedb03b620f97a9": "Ej skickat utkast", "90a349d827d1dcf5": "Kasta utkast", + "524e4bb76976942f": "{count, plural, one {Visar {environment}. {count} tråd på annat håll behöver dig} other {Visar {environment}. {count} trådar på annat håll behöver dig}}", + "b082c0602780fbab": "Visar {environment}", + "f6dd36e7cc2f9725": "Filtrera trådar efter miljö", + "97884c869683f97f": "{count, plural, one {{count} behöver dig} other {{count} behöver dig}}", + "1a021ea597900720": "Visa trådar från", "ace9f34925fb6905": "Att släppa mappar kräver skrivbordsappen", "327623037d69218f": "Webbläsare delar inte mappsökvägar. Använd Lägg till projekt för att välja en mapp.", "effe26aaf2941c69": "Datorns server är inte ansluten än", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..86e540cdb0cc1 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -11667,6 +11667,11 @@ "20283eb1dd6119f9": "{count, plural, other {{count} 个附件}}", "ffedb03b620f97a9": "未发送的草稿", "90a349d827d1dcf5": "丢弃草稿", + "524e4bb76976942f": "{count, plural, other {正在显示 {environment}。其他位置有 {count} 个会话需要你处理}}", + "b082c0602780fbab": "正在显示 {environment}", + "f6dd36e7cc2f9725": "按环境筛选会话", + "97884c869683f97f": "{count, plural, other {{count} 个需要你处理}}", + "1a021ea597900720": "显示来自以下环境的会话", "ace9f34925fb6905": "拖入文件夹需要使用桌面应用", "327623037d69218f": "浏览器不提供文件夹路径,请使用“添加项目”选择文件夹。", "effe26aaf2941c69": "尚未连接本机的服务器", diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 804757e78307a..d31a067187927 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -20,6 +20,7 @@ function makeUiState(overrides: Partial = {}): UiState { projectExpandedById: {}, projectOrder: [], sidebarProjectScopeKeys: [], + sidebarEnvironmentScope: null, threadLastVisitedAtById: {}, threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, @@ -126,6 +127,7 @@ describe("parsePersistedState", () => { }, defaultAdvertisedEndpointKey: "desktop-core:lan:http", sidebarProjectScopeKeys: [], + sidebarEnvironmentScope: null, pullRequestMergeMethod: "merge", threadChangedFilesExpandedById: { "environment:thread-1": { @@ -238,6 +240,7 @@ describe("uiStateStore persistence", () => { defaultAdvertisedEndpointKey: "desktop-core:lan:http", sidebarProjectScopeKeys: [], sidebarProjectScopeKey: null, + sidebarEnvironmentScope: null, threadChangedFilesExpansionVersion: 2, threadChangedFilesExpandedById: { "environment:thread-1": { @@ -263,6 +266,17 @@ describe("uiStateStore persistence", () => { expect(parsePersistedState(persisted).sidebarProjectScopeKeys).toEqual(keys); }); + it("restores the sidebar environment scope across reloads", () => { + persistState(makeUiState({ sidebarEnvironmentScope: "environment-laptop" })); + + const persisted = JSON.parse( + localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", + ) as PersistedUiState; + + expect(parsePersistedState(persisted).sidebarEnvironmentScope).toBe("environment-laptop"); + expect(parsePersistedState({}).sidebarEnvironmentScope).toBeNull(); + }); + it("keeps a single-project scope readable by older clients", () => { persistState(makeUiState({ sidebarProjectScopeKeys: ["github.com/pingdotgg/t3code"] })); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index b2ac1a508c7a6..70a7b15df3080 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -29,6 +29,7 @@ export interface PersistedUiState { defaultAdvertisedEndpointKey?: string | null; sidebarProjectScopeKey?: string | null; sidebarProjectScopeKeys?: string[]; + sidebarEnvironmentScope?: string | null; threadChangedFilesExpansionVersion?: number; threadChangedFilesExpandedById?: Record>; pullRequestMergeMethod?: string; @@ -38,6 +39,8 @@ export interface UiProjectState { projectExpandedById: Record; projectOrder: string[]; sidebarProjectScopeKeys: string[]; + // An environment id; null shows every environment. + sidebarEnvironmentScope: string | null; } export interface UiThreadState { @@ -60,6 +63,7 @@ const initialState: UiState = { projectExpandedById: {}, projectOrder: [], sidebarProjectScopeKeys: [], + sidebarEnvironmentScope: null, threadLastVisitedAtById: {}, threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, @@ -153,6 +157,7 @@ export function parsePersistedState(parsed: PersistedUiState): UiState { sidebarProjectScopeKeys: sanitizeStringArray( parsed.sidebarProjectScopeKeys ?? [parsed.sidebarProjectScopeKey], ), + sidebarEnvironmentScope: sanitizeOptionalKey(parsed.sidebarEnvironmentScope), pullRequestMergeMethod: isPullRequestMergeMethod(parsed.pullRequestMergeMethod) ? parsed.pullRequestMergeMethod : initialState.pullRequestMergeMethod, @@ -227,6 +232,7 @@ export function persistState(state: UiState): void { state.sidebarProjectScopeKeys.length === 1 ? (state.sidebarProjectScopeKeys[0] ?? null) : null, + sidebarEnvironmentScope: state.sidebarEnvironmentScope, threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION, threadChangedFilesExpandedById: state.threadChangedFilesExpandedById, pullRequestMergeMethod: state.pullRequestMergeMethod, @@ -428,6 +434,7 @@ interface UiStateStore extends UiState { setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void; setDefaultAdvertisedEndpointKey: (key: string | null) => void; setSidebarProjectScopeKeys: (projectKeys: readonly string[]) => void; + setSidebarEnvironmentScope: (environmentId: string | null) => void; setPullRequestMergeMethod: (method: PullRequestMergeMethod) => void; setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void; reorderProjects: ( @@ -449,6 +456,12 @@ export const useUiStateStore = create((set) => ({ set((state) => setDefaultAdvertisedEndpointKey(state, key)), setSidebarProjectScopeKeys: (projectKeys) => set((state) => setSidebarProjectScopeKeys(state, projectKeys)), + setSidebarEnvironmentScope: (environmentId) => + set((state) => + state.sidebarEnvironmentScope === environmentId + ? state + : { ...state, sidebarEnvironmentScope: environmentId }, + ), setPullRequestMergeMethod: (method) => set((state) => setPullRequestMergeMethod(state, method)), setProjectExpanded: (projectIds, expanded) => set((state) => setProjectExpanded(state, projectIds, expanded)), diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 38dd4684723f9..1be0e3d059222 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -160,6 +160,16 @@ Pinned threads stay above the folders, and Snoozed and Settled stay below them. can drag a thread onto the composer to mention it, but not within the sidebar, and the Working section is off. Each device keeps its own choice. +### Show one environment + +When more than one environment is connected, the device button next to the project filter on web +and desktop narrows the sidebar to one of them. Projects grouped by repository then list only +their copies on that environment. It only hides rows: every environment stays connected and +keeps working, and the button shows a dot while a thread on a hidden environment needs you. Its +menu counts what needs you and what is working on each environment. Opening a hidden thread +from a link or the command palette shows all environments again. If you remove the environment, +the sidebar shows all of them. Each device keeps its own choice. + ## Settle finished work Choose **Settle thread** from its menu to move finished work out of the active list From 9415abacfc80af41e91e18aa91c86b9905986885 Mon Sep 17 00:00:00 2001 From: Diogo Coutinho Date: Thu, 19 Nov 2026 13:02:06 -0300 Subject: [PATCH 09/87] feat: add several projects at once from agent history or a Git repository search Adding projects one folder at a time was slow, and agent history import only lived on the Welcome page. A new Add projects dialog, reachable from Add project in the command palette, offers two sources for an environment: the folders Claude Code, Codex and Pi sessions ran in (shared with the Welcome page, now extracted to onboarding/ProjectImport), and a new filesystem.discoverRepositories RPC that walks user-named folders on the host for Git repositories (4 levels, skipping hidden, dependency and protected macOS folders, no symlinks, guarded by filesystem:read). Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.test.ts | 6 + .../src/observability/RpcInstrumentation.ts | 1 + .../src/project/AgentSessionScanner.test.ts | 107 +++- .../server/src/project/AgentSessionScanner.ts | 221 +++++-- apps/server/src/ws.ts | 2 + apps/web/src/components/AddProjectsDialog.tsx | 362 +++++++++++ apps/web/src/components/CommandPalette.tsx | 27 + .../components/onboarding/ProjectImport.tsx | 588 ++++++++++++++++++ .../src/components/onboarding/WelcomePage.tsx | 570 +---------------- apps/web/src/i18n/translations/de.json | 42 ++ apps/web/src/i18n/translations/en.json | 42 ++ apps/web/src/i18n/translations/es.json | 42 ++ apps/web/src/i18n/translations/fr.json | 42 ++ apps/web/src/i18n/translations/ja.json | 40 ++ apps/web/src/i18n/translations/ko.json | 40 ++ apps/web/src/i18n/translations/pt-BR.json | 42 ++ apps/web/src/i18n/translations/ru.json | 42 ++ apps/web/src/i18n/translations/sv.json | 42 ++ apps/web/src/i18n/translations/zh.json | 41 ++ apps/web/src/routes/__root.tsx | 2 + apps/web/src/state/agentSessions.ts | 5 + docs/user/install.md | 17 + packages/contracts/src/agentSessions.ts | 11 + .../contracts/src/clientRpcPermissions.ts | 3 + packages/contracts/src/rpc.ts | 10 + 25 files changed, 1743 insertions(+), 604 deletions(-) create mode 100644 apps/web/src/components/AddProjectsDialog.tsx create mode 100644 apps/web/src/components/onboarding/ProjectImport.tsx diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 8afe47e715a9f..0a0059b4171af 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -71,6 +71,12 @@ describe("RPC authorization scopes", () => { } }); + it("keeps repository discovery, which walks host folders, behind filesystem read", () => { + expect(requiredScopeForRpcMethod(WS_METHODS.filesystemDiscoverRepositories)).toBe( + AuthFilesystemReadScope, + ); + }); + it("lets thread readers observe and refresh checkout branches", () => { for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) { expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a2b698657afcb..719f4bdc822a0 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -184,6 +184,7 @@ const RPC_AGGREGATES = { [WS_METHODS.filesystemBrowse]: "workspace", [WS_METHODS.filesystemGetMetadata]: "workspace", [WS_METHODS.agentSessionsScan]: "workspace", + [WS_METHODS.filesystemDiscoverRepositories]: "workspace", [WS_METHODS.agentSessionsImport]: "workspace", [WS_METHODS.assetsCreateUrl]: "workspace", [WS_METHODS.assetsPersistChatAttachments]: "orchestration", diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 6d9d3438ef380..6db01091c3225 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -141,6 +141,12 @@ const runScan = (input: ScannerTestInput) => return yield* scanner.scan; }).pipe(Effect.provide(layerScannerTest(input))); +const runDiscovery = (input: ScannerTestInput & { readonly roots: ReadonlyArray }) => + Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + return yield* scanner.discoverRepositories(input.roots); + }).pipe(Effect.provide(layerScannerTest(input))); + const runRecentThreadOutcomes = (input: ScannerTestInput & { readonly workspaceRoot: string }) => Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; @@ -1323,11 +1329,13 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { it.effect("excludes sandboxes reached through a symlink into the worktrees dir", () => Effect.gen(function* () { const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + const configBaseDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-base-"), + ); const linkParent = yield* makeTempDir("t3code-scanner-links-"); - const fileSystem = yield* FileSystem.FileSystem; const worktreeCwd = path.join(configBaseDir, "worktrees", "t3code", "wt-3"); yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true }); @@ -1487,6 +1495,101 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { ); }); + describe("discoverRepositories", () => { + it.effect( + "finds repositories under a picked folder without entering skipped or linked ones", + () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const root = yield* fileSystem.realPath(yield* makeTempDir("t3code-discovery-root-")); + const makeRepo = Effect.fn("AgentSessionScanner.test.makeRepo")(function* ( + directory: string, + origin?: string, + ) { + yield* fileSystem.makeDirectory(path.join(directory, ".git"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(directory, ".git", "config"), + origin === undefined ? "[core]\n" : `[remote "origin"]\n\turl = ${origin}\n`, + ); + }); + + const app = path.join(root, "app"); + yield* makeRepo(app, "git@github.com:pingdotgg/t3code.git"); + // Nested checkouts belong to the repository around them. + yield* makeRepo(path.join(app, "packages", "nested")); + const imported = path.join(root, "clients", "imported"); + yield* makeRepo(imported); + yield* makeRepo(path.join(root, "clients", "node_modules", "dependency")); + yield* makeRepo(path.join(root, ".hidden", "repo")); + yield* makeRepo(path.join(root, "a", "b", "c", "d", "too-deep")); + yield* fileSystem.makeDirectory(path.join(root, "plain")); + // A link back to the root would loop if it were followed. + yield* fileSystem.symlink(root, path.join(root, "plain", "loop")); + + const result = yield* runDiscovery({ + claudeHomePath, + codexHomePath, + roots: [root], + importedWorkspaceRoots: [imported], + }); + + expect( + result.candidates.map((candidate) => ({ + path: candidate.path, + alreadyImported: candidate.alreadyImported, + threadCount: candidate.threadCount, + git: candidate.git, + })), + ).toEqual([ + { + path: app, + alreadyImported: false, + threadCount: 0, + git: { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" }, + }, + { + path: imported, + alreadyImported: true, + threadCount: 0, + git: { remoteKey: null, repository: null }, + }, + ]); + expect(result.truncated).toBeUndefined(); + }), + ); + + it.effect( + "finds repositories New project made under T3's folder, but not its other state", + () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const configBaseDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-base-"), + ); + const made = path.join(configBaseDir, "projects", "made"); + const state = path.join(configBaseDir, "userdata", "repo"); + for (const directory of [made, state]) { + yield* fileSystem.makeDirectory(path.join(directory, ".git"), { recursive: true }); + } + + const result = yield* runDiscovery({ + claudeHomePath, + codexHomePath, + configBaseDir, + roots: [path.join(configBaseDir, "projects"), configBaseDir], + }); + + expect(result.candidates.map((candidate) => candidate.path)).toEqual([made]); + }), + ); + }); + describe("recentThreads", () => { it.effect("imports Codex conversations stored only as zstd-compressed rollouts", () => Effect.gen(function* () { diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b6e1780bd039e..2c7ab96b350f2 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; import * as NodeZlib from "node:zlib"; @@ -105,6 +107,36 @@ const GIT_FILE_READ_CONCURRENCY = 16; const BLOCKED_GIT_FILE_RETRY_MS = 5 * 60 * 1000; const MAX_BLOCKED_GIT_FILE_PATHS = 1024; +// Repository discovery reads only folders the user picks, within these bounds. +const MAX_DISCOVERY_DEPTH = 4; +const MAX_DISCOVERY_DIRECTORIES = 5_000; +const MAX_DISCOVERED_REPOSITORIES = 200; +// ponytail: one deadline for the whole walk; a readdir stuck on a network mount still holds a pool thread. +const DISCOVERY_DEADLINE = "15 seconds"; +// Dependencies and build output hold vendored checkouts, not the user's projects. +const DISCOVERY_SKIPPED_NAMES = new Set([ + "node_modules", + "bower_components", + "vendor", + "Pods", + "dist", + "build", + "out", + "target", + "venv", + "__pycache__", +]); +// macOS guards these with consent prompts a server cannot answer; read them only when picked. +const DISCOVERY_PROTECTED_HOME_FOLDERS = [ + "Desktop", + "Documents", + "Downloads", + "Library", + "Movies", + "Music", + "Pictures", +]; + const TranscriptContentBlock = Schema.Struct({ type: Schema.optional(Schema.String), text: Schema.optional(Schema.String), @@ -234,6 +266,10 @@ export class AgentSessionScanner extends Context.Service< AgentSessionScanner, { readonly scan: Effect.Effect; + /** Git repositories under folders the user picked, as candidates without history. */ + readonly discoverRepositories: ( + roots: ReadonlyArray, + ) => Effect.Effect; readonly recentThreads: ( workspaceRoot: string, completedSources?: ReadonlyArray, @@ -902,6 +938,8 @@ export const make = Effect.gen(function* () { const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const baseDir = path.resolve(serverConfig.baseDir); const worktreesDir = path.resolve(serverConfig.worktreesDir); + // Matches ManagedProjectFolders' named projects root. + const namedProjectsRoot = path.join(baseDir, "projects"); const platform = yield* HostProcess.Platform; const isWindows = platform === "win32"; const foldWorktreeCase = isWindows; @@ -925,9 +963,13 @@ export const make = Effect.gen(function* () { normalizeForWorktreeMatch(ancestor, foldWorktreeCase), ), ) || - normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( + (normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( normalizeForWorktreeMatch(baseDir, foldWorktreeCase), - ) || + ) && + // New project creates the user's projects here; the rest of T3's folder is its own state. + !normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( + normalizeForWorktreeMatch(namedProjectsRoot, foldWorktreeCase), + )) || isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase); const listDirectory = (directory: string) => @@ -1932,6 +1974,143 @@ export const make = Effect.gen(function* () { let cachedCandidates: Effect.Success> | null = null; + /** Candidates for directory projects, matched to the projects already here. */ + const toProjectCandidates = Effect.fn("AgentSessionScanner.toProjectCandidates")(function* ( + entries: ReadonlyMap< + string, + { + readonly path: string; + readonly sources: ReadonlyArray; + readonly threadCount: number; + readonly lastActiveAtMs: number | null; + readonly git: AgentSessionProjectGit | null; + } + >, + ) { + // Resolve persisted roots too; transcripts may use different symlinks to the same directory. + const importedProjects = yield* projectStore + .listShells() + .pipe( + Effect.mapError( + (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), + ), + ); + const importedProjectsByRoot = new Map(); + for (const project of importedProjects) { + const projectRoot = path.resolve(expandHomePath(project.workspaceRoot, homeDir)); + importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project); + importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project); + } + + const candidates: Array = []; + for (const [key, entry] of entries) { + const importedProject = + importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ?? + importedProjectsByRoot.get(key); + const candidatePath = importedProject?.workspaceRoot ?? entry.path; + candidates.push({ + path: candidatePath, + title: path.basename(candidatePath) || candidatePath, + ...(importedProject === undefined ? {} : { projectId: importedProject.id }), + sources: [...entry.sources], + threadCount: entry.threadCount, + lastActiveAt: + entry.lastActiveAtMs === null + ? null + : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)), + alreadyImported: importedProject !== undefined, + git: entry.git, + }); + } + return candidates; + }); + + const discoverRepositories: AgentSessionScanner["Service"]["discoverRepositories"] = Effect.fn( + "AgentSessionScanner.discoverRepositories", + )(function* (roots) { + const protectedFolders = new Set( + DISCOVERY_PROTECTED_HOME_FOLDERS.map((name) => + normalizeProjectPathForComparison(path.join(homeDir, name)), + ), + ); + const queue = roots.flatMap((root) => { + const expanded = expandHomePath(root.trim(), homeDir); + return path.isAbsolute(expanded) ? [{ directory: path.resolve(expanded), depth: 0 }] : []; + }); + const repositories: Array = []; + const seen = new Set(); + let truncated = false; + // Breadth first, so the bounds cut the deepest folders and shallow repositories come first. + const walk = Effect.gen(function* () { + for (let next = queue.shift(); next !== undefined; next = queue.shift()) { + const { directory, depth } = next; + const key = normalizeProjectPathForComparison(directory); + if (seen.has(key)) continue; + if (seen.size === MAX_DISCOVERY_DIRECTORIES) { + truncated = true; + return; + } + seen.add(key); + // An unreadable folder is skipped like an empty one. + const entries = yield* Effect.promise(() => + NodeFSP.readdir(directory, { withFileTypes: true }).catch(() => []), + ); + // A repository's own folders are its business: nested checkouts and submodules stay out. + if (entries.some((entry) => entry.name === ".git")) { + repositories.push(directory); + if (repositories.length === MAX_DISCOVERED_REPOSITORIES) { + truncated = queue.length > 0; + return; + } + continue; + } + if (depth === MAX_DISCOVERY_DEPTH) continue; + for (const entry of entries) { + // Dirents report symlinks as links, so links (and the loops they make) are not followed. + if (!entry.isDirectory() || entry.name.startsWith(".")) continue; + if (DISCOVERY_SKIPPED_NAMES.has(entry.name)) continue; + const child = path.join(directory, entry.name); + if (protectedFolders.has(normalizeProjectPathForComparison(child))) continue; + if (isExcludedProjectPath(child)) continue; + queue.push({ directory: child, depth: depth + 1 }); + } + } + }); + if (Option.isNone(yield* walk.pipe(Effect.timeoutOption(DISCOVERY_DEADLINE)))) { + truncated = true; + } + + // A linked worktree counts toward its main checkout, as in the history scan. + const directoryProjects = yield* resolveDirectoryProjects(repositories); + const entries = new Map< + string, + { + path: string; + sources: ReadonlyArray; + threadCount: number; + lastActiveAtMs: number | null; + git: AgentSessionProjectGit | null; + } + >(); + for (const directory of repositories) { + const project = directoryProjects.get(directory); + if (project === undefined || project === null || entries.has(project.key)) continue; + entries.set(project.key, { + path: project.path, + sources: [], + threadCount: 0, + lastActiveAtMs: null, + git: project.git, + }); + } + const candidates = yield* toProjectCandidates(entries); + return { + candidates: candidates.toSorted((left, right) => left.path.localeCompare(right.path)), + scannedAt: DateTime.formatIso(yield* DateTime.now), + ...(truncated ? { truncated: true } : {}), + }; + }); + const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () { cachedCandidates = yield* collectCandidates(); const { candidates: raw, truncated } = cachedCandidates; @@ -1980,41 +2159,7 @@ export const make = Effect.gen(function* () { : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs); } - // Resolve persisted roots too; transcripts may use different symlinks to the same directory. - const importedProjects = yield* projectStore - .listShells() - .pipe( - Effect.mapError( - (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), - ), - ); - const importedProjectsByRoot = new Map(); - for (const project of importedProjects) { - const projectRoot = path.resolve(expandHomePath(project.workspaceRoot, homeDir)); - importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project); - importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project); - } - - const candidates: Array = []; - for (const [key, entry] of merged.entries()) { - const importedProject = - importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ?? - importedProjectsByRoot.get(key); - const candidatePath = importedProject?.workspaceRoot ?? entry.path; - candidates.push({ - path: candidatePath, - title: path.basename(candidatePath) || candidatePath, - ...(importedProject === undefined ? {} : { projectId: importedProject.id }), - sources: entry.sources, - threadCount: entry.threadCount, - lastActiveAt: - entry.lastActiveAtMs === null - ? null - : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)), - alreadyImported: importedProject !== undefined, - git: entry.git, - }); - } + const candidates = yield* toProjectCandidates(merged); candidates.sort((left, right) => { if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path); @@ -2307,7 +2452,7 @@ export const make = Effect.gen(function* () { completedSources = [], ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources)); - return AgentSessionScanner.of({ scan, recentThreads }); + return AgentSessionScanner.of({ scan, discoverRepositories, recentThreads }); }); export const layer = Layer.effect(AgentSessionScanner, make).pipe( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63d45c48816e4..ffa154140e402 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3056,6 +3056,8 @@ export const layerWsRpc = ( [WS_METHODS.attachmentsCreateUploadUrl]: (input) => issueAttachmentUploadUrl(input), [WS_METHODS.attachmentsDelete]: (input) => deletePendingAttachment(input.attachmentId), [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, + [WS_METHODS.filesystemDiscoverRepositories]: (input) => + agentSessionScanner.discoverRepositories(input.roots), [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), [WS_METHODS.assetsCreateUrl]: diff --git a/apps/web/src/components/AddProjectsDialog.tsx b/apps/web/src/components/AddProjectsDialog.tsx new file mode 100644 index 0000000000000..66f1e2008c569 --- /dev/null +++ b/apps/web/src/components/AddProjectsDialog.tsx @@ -0,0 +1,362 @@ +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { getAddProjectInitialQuery } from "@t3tools/client-runtime/operations/projects"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + PROJECT_DISCOVERY_ROOTS_LIMIT, + type AgentSessionScanResult, + type EnvironmentId, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { T, useGT, useMessages, Var } from "gt-react"; +import { useRef, useState, type ReactNode } from "react"; +import { create } from "zustand"; + +import { m } from "../i18n/messages"; +import { useProjectScans } from "../onboarding/useProjectScans"; +import type { WelcomeImportSelection } from "../onboarding/welcomeState"; +import { repositoryDiscovery } from "../state/agentSessions"; +import { useEnvironments } from "../state/environments"; +import { useAtomCommand } from "../state/use-atom-command"; +import { + ImportCandidateList, + useImportSourcesLabel, + useProjectImport, + type ProjectImportScan, +} from "./onboarding/ProjectImport"; +import { Button } from "./ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "./ui/dialog"; +import { ScrollArea } from "./ui/scroll-area"; +import { Textarea } from "./ui/textarea"; +import { toastManager } from "./ui/toast"; + +type AddProjectsSource = "history" | "disk"; + +interface AddProjectsRequest { + readonly environmentId: EnvironmentId; + readonly source: AddProjectsSource; +} + +const useRequest = create<{ request: AddProjectsRequest | null; session: number }>(() => ({ + request: null, + session: 0, +})); + +/** Opens the list that adds several projects at once, from agent history or folders on disk. */ +export function openAddProjectsDialog(request: AddProjectsRequest) { + useRequest.setState((state) => ({ request, session: state.session + 1 })); +} + +function close() { + useRequest.setState({ request: null }); +} + +export function AddProjectsDialogHost() { + const request = useRequest((state) => state.request); + const session = useRequest((state) => state.session); + if (request === null) return null; + return request.source === "history" ? ( + + ) : ( + + ); +} + +function useEnvironmentLabel(environmentId: EnvironmentId) { + const gt = useGT(); + const { environments } = useEnvironments(); + return ( + environments.find((environment) => environment.environmentId === environmentId)?.label ?? + gt("this computer") + ); +} + +function HistoryProjectsDialog({ environmentId }: { readonly environmentId: EnvironmentId }) { + const gt = useGT(); + const label = useEnvironmentLabel(environmentId); + const sources = useImportSourcesLabel(); + const scan = useProjectScans([environmentId])[0]!; + return ( + + Projects your {sources} sessions ran in on {label}, with their + recent threads. + + } + status={ + scan.isPending && scan.data === null + ? gt("Looking for projects…") + : scan.error !== null + ? gt("Could not check projects. {error}", { error: scan.error }) + : null + } + truncated={scan.data?.truncated === true} + /> + ); +} + +function DiskProjectsDialog({ environmentId }: { readonly environmentId: EnvironmentId }) { + const gt = useGT(); + const label = useEnvironmentLabel(environmentId); + const { environments } = useEnvironments(); + const serverConfig = environments.find( + (environment) => environment.environmentId === environmentId, + )?.serverConfig; + const baseDirectory = serverConfig?.settings.addProjectBaseDirectory.trim() ?? ""; + // The folder Add project browses from, then where New project creates projects. + const suggestedFolders = [ + ...new Set([ + ...(baseDirectory.length > 0 ? [getAddProjectInitialQuery(baseDirectory)] : []), + ...(serverConfig?.newProjectsRoot === undefined ? [] : [serverConfig.newProjectsRoot]), + ]), + ].join("\n"); + const canDiscover = useAtomValue(repositoryDiscovery.permissionAtom(environmentId)); + const discover = useAtomCommand(repositoryDiscovery, { reportFailure: false }); + const [folders, setFolders] = useState(suggestedFolders); + const [searching, setSearching] = useState(false); + const [error, setError] = useState(null); + const [result, setResult] = useState(null); + const roots = [ + ...new Set( + folders + .split("\n") + .map((line) => line.trim()) + .filter(Boolean), + ), + ]; + const search = async () => { + setSearching(true); + setError(null); + const outcome = await discover({ environmentId, input: { roots } }); + setSearching(false); + if (outcome._tag === "Success") { + setResult(outcome.value); + return; + } + setError( + thrownErrorMessage(squashAtomCommandFailure(outcome), m) ?? + gt("Could not look for repositories."), + ); + }; + const scan: ProjectImportScan = { + environmentId, + // Projects already here have nothing left to add. + data: + result === null + ? null + : { candidates: result.candidates.filter((candidate) => !candidate.alreadyImported) }, + refresh: () => void search(), + }; + const tooMany = roots.length > PROJECT_DISCOVERY_ROOTS_LIMIT; + return ( + + Looks for Git repositories in folders on {label}. To add a folder without Git, + use Local folder. + + } + header={ +
+ '; + const drawer = (key: string) => ( + + ); + await using screen = await render(drawer("a")); + const input = host.element.querySelector("textarea")!; + input.focus(); + await screen.rerender(drawer("b")); + expect(document.activeElement).toBe(input); + }); + + it("maximize covers the tool and restore brings it back", async () => { + const onToggleMaximized = vi.fn(); + const tabs = (maximized: boolean) => ( + + ); + await using screen = await render(tabs(false)); + const content = screen.getByTestId("surface-content"); + await expect.element(content).toBeVisible(); + + await screen.rerender(tabs(true)); + await expect.element(content).not.toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Restore terminal" })); + expect(onToggleMaximized).toHaveBeenCalledOnce(); + + await screen.rerender(tabs(false)); + await expect.element(content).toBeVisible(); + }); +}); + +describe("panel parity", () => { + it("in the narrow sheet the rail is present and the terminal icon opens the drawer", async () => { + const onToggleTerminal = vi.fn(); + const props = railPanel(DIFF_SURFACE); + await using screen = await render( + , + { container: sizedContainer(600) }, + ); + const rail = screen.container.querySelector("[data-right-panel-rail]"); + expect(rail).not.toBeNull(); + await userEvent.click(rail!.querySelector('[data-rail-group="terminal"]')!); + expect(onToggleTerminal).toHaveBeenCalledOnce(); + }); + + it("drawer height never exceeds the sheet's height", async () => { + await using screen = await render( + , + { container: sizedContainer(400) }, + ); + const drawer = screen.container.querySelector( + "[data-right-panel-terminal-drawer]", + )!; + const column = drawer.parentElement!; + expect(drawer.getBoundingClientRect().height).toBeLessThanOrEqual( + column.getBoundingClientRect().height - 120, + ); + expect(drawer.getBoundingClientRect().height).toBeGreaterThan(0); + }); + + it("maximized panel keeps the rail and the drawer", async () => { + await using screen = await render( + , + { container: sizedContainer(600) }, + ); + expect(screen.container.querySelector("[data-right-panel-rail]")).not.toBeNull(); + expect( + screen.container.querySelector('[data-right-panel-terminal-drawer="open"]'), + ).not.toBeNull(); + }); +}); diff --git a/apps/web/src/components/RightPanelTabs.logic.test.ts b/apps/web/src/components/RightPanelTabs.logic.test.ts index b1ac278ab5bd4..70211b21340c5 100644 --- a/apps/web/src/components/RightPanelTabs.logic.test.ts +++ b/apps/web/src/components/RightPanelTabs.logic.test.ts @@ -1,13 +1,23 @@ import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { TerminalSummary } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { RightPanelSurface } from "~/rightPanelStore"; import { - latestTurnChangedFileCount, - rightPanelDynamicTabSurfaces, - rightPanelSectionOf, - rightPanelSectionTarget, + changesNovel, + clampTerminalDrawerHeight, + currentTerminalClaims, + latestTurnChangeTotals, + nextUnseenRightPanelGroups, + reconcileMountedTerminalThreads, + reconcileTerminalSurfaceIds, + rightPanelGroupOf, + rightPanelGroupTarget, + terminalDrawerStatus, + terminalSurfaceMount, + TERMINAL_DRAWER_MIN_HEIGHT, + visibleRightPanelToolGroups, } from "./RightPanelTabs.logic"; const diff: RightPanelSurface = { id: "diff", kind: "diff" }; @@ -17,50 +27,9 @@ const firstTerminal = { terminalIds: ["a"], activeTerminalId: "a", } as unknown as RightPanelSurface; -const secondTerminal = { - id: "terminal:b", - kind: "terminal", - terminalIds: ["b"], - activeTerminalId: "b", -} as unknown as RightPanelSurface; const browser: RightPanelSurface = { id: "browser:tab", kind: "preview", resourceId: "tab" }; const files = { id: "files", kind: "files" } as unknown as RightPanelSurface; -describe("right panel sections", () => { - const surfaces = [diff, firstTerminal, files, secondTerminal, browser]; - - it("maps diff, terminal and browser surfaces to their section", () => { - expect(rightPanelSectionOf(diff)).toBe("changes"); - expect(rightPanelSectionOf(secondTerminal)).toBe("terminal"); - expect(rightPanelSectionOf(browser)).toBe("browser"); - expect(rightPanelSectionOf(files)).toBeNull(); - expect(rightPanelSectionOf(undefined)).toBeNull(); - }); - - it("keeps the active surface when it already belongs to the section", () => { - expect(rightPanelSectionTarget(surfaces, "terminal:a", "terminal")).toBe(firstTerminal); - }); - - it("falls back to the newest surface of the section's kind", () => { - expect(rightPanelSectionTarget(surfaces, "files", "terminal")).toBe(secondTerminal); - expect(rightPanelSectionTarget(surfaces, null, "changes")).toBe(diff); - }); - - it("asks for a new surface when the section has none, so a click never adds a second one", () => { - expect(rightPanelSectionTarget([diff, files], "diff", "browser")).toBeNull(); - expect(rightPanelSectionTarget([files], "files", "terminal")).toBeNull(); - }); - - it("drops only the diff from the dynamic tabs", () => { - expect(rightPanelDynamicTabSurfaces(surfaces)).toEqual([ - firstTerminal, - files, - secondTerminal, - browser, - ]); - }); -}); - function summary( checkpointTurnCount: number, fileCount: number, @@ -80,17 +49,369 @@ function summary( } as unknown as ThreadCheckpointSummary; } -describe("latestTurnChangedFileCount", () => { - it("counts the files of the highest turn, whatever the order", () => { - expect(latestTurnChangedFileCount([summary(2, 3), summary(1, 7)])).toBe(3); - expect(latestTurnChangedFileCount([summary(1, 7), summary(2, 3)])).toBe(3); +describe("latestTurnChangeTotals", () => { + it("totals the files of the highest turn, whatever the order", () => { + expect(latestTurnChangeTotals([summary(2, 3), summary(1, 7)])).toEqual({ + turnCount: 2, + count: 3, + additions: 3, + deletions: 0, + }); + expect(latestTurnChangeTotals([summary(1, 7), summary(2, 3)])?.turnCount).toBe(2); }); it("uses the server total when the file list is only a prefix", () => { - expect(latestTurnChangedFileCount([summary(1, 2, 40)])).toBe(40); + expect(latestTurnChangeTotals([summary(1, 2, 40)])).toEqual({ + turnCount: 1, + count: 40, + additions: 0, + deletions: 0, + }); + }); + + it("has no totals before the first turn", () => { + expect(latestTurnChangeTotals([])).toBeNull(); + }); +}); + +const file = { + id: "file:src/a.ts", + kind: "file", + relativePath: "src/a.ts", + revealLine: null, + revealRequestId: 1, +} as unknown as RightPanelSurface; +const secondBrowser: RightPanelSurface = { + id: "browser:tab2", + kind: "preview", + resourceId: "tab2", +}; +const device = { id: "device", kind: "device" } as unknown as RightPanelSurface; +const pullRequest = { + id: "pull-request:p:r:1", + kind: "pull-request", +} as unknown as RightPanelSurface; + +describe("right panel groups", () => { + it("maps every surface kind to its rail group", () => { + const table: Array<[RightPanelSurface, string]> = [ + [diff, "changes"], + [browser, "browser"], + [files, "files"], + [file, "files"], + [{ id: "pull-requests", kind: "pull-requests" }, "reviews"], + [pullRequest, "reviews"], + [{ id: "issue:x", kind: "issue" } as unknown as RightPanelSurface, "reviews"], + [device, "devices"], + [{ id: "thread:t", kind: "thread" } as unknown as RightPanelSurface, "threads"], + [{ id: "linked-thread:x", kind: "linked-thread" } as unknown as RightPanelSurface, "threads"], + [firstTerminal, "terminal"], + ]; + for (const [surface, group] of table) expect(rightPanelGroupOf(surface)).toBe(group); + }); + + it("keeps the active surface when it belongs to the group, else the newest of the group", () => { + const surfaces = [diff, browser, files, secondBrowser, file]; + expect(rightPanelGroupTarget(surfaces, "browser:tab", "browser")).toBe(browser); + expect(rightPanelGroupTarget(surfaces, "diff", "browser")).toBe(secondBrowser); + expect(rightPanelGroupTarget(surfaces, null, "changes")).toBe(diff); + expect(rightPanelGroupTarget(surfaces, "diff", "files")).toBe(file); + }); + + it("asks for a new surface when the group has none", () => { + expect(rightPanelGroupTarget([diff, files], "diff", "browser")).toBeNull(); + expect(rightPanelGroupTarget([diff, firstTerminal], "diff", "devices")).toBeNull(); + }); + + it("always shows changes, browser and files; others need availability or an open surface", () => { + const none = { reviews: false, devices: false, threads: false }; + expect(visibleRightPanelToolGroups({ surfaces: [], available: none })).toEqual([ + "changes", + "browser", + "files", + ]); + expect( + visibleRightPanelToolGroups({ + surfaces: [device], + available: { reviews: true, devices: false, threads: false }, + }), + ).toEqual(["changes", "browser", "files", "reviews", "devices"]); + expect( + visibleRightPanelToolGroups({ + surfaces: [], + available: { reviews: false, devices: false, threads: true }, + }), + ).toEqual(["changes", "browser", "files", "threads"]); + }); +}); + +describe("unseen groups", () => { + it("marks the group of a surface added while another group is active", () => { + expect( + nextUnseenRightPanelGroups({ + before: [diff], + after: { isOpen: true, activeSurfaceId: "diff", surfaces: [diff, pullRequest] }, + drawerOpen: false, + unseen: [], + }), + ).toEqual(["reviews"]); + }); + + it("does not mark the active group, and clears a group once it is visible", () => { + expect( + nextUnseenRightPanelGroups({ + before: [diff], + after: { isOpen: true, activeSurfaceId: "browser:tab", surfaces: [diff, browser] }, + drawerOpen: false, + unseen: [], + }), + ).toEqual([]); + expect( + nextUnseenRightPanelGroups({ + before: [diff, pullRequest], + after: { isOpen: true, activeSurfaceId: pullRequest.id, surfaces: [diff, pullRequest] }, + drawerOpen: false, + unseen: ["reviews", "browser"], + }), + ).toEqual(["browser"]); + }); + + it("marks terminal while the drawer or the panel is closed, clears it when the drawer shows", () => { + expect( + nextUnseenRightPanelGroups({ + before: [diff], + after: { isOpen: true, activeSurfaceId: "diff", surfaces: [diff, firstTerminal] }, + drawerOpen: false, + unseen: [], + }), + ).toEqual(["terminal"]); + expect( + nextUnseenRightPanelGroups({ + before: [diff], + after: { isOpen: false, activeSurfaceId: "diff", surfaces: [diff, firstTerminal] }, + drawerOpen: true, + unseen: [], + }), + ).toEqual(["terminal"]); + expect( + nextUnseenRightPanelGroups({ + before: [diff, firstTerminal], + after: { isOpen: true, activeSurfaceId: "diff", surfaces: [diff, firstTerminal] }, + drawerOpen: true, + unseen: ["terminal"], + }), + ).toEqual([]); + }); + + it("returns the same array when nothing changes", () => { + const unseen = ["reviews"] as const; + expect( + nextUnseenRightPanelGroups({ + before: [diff], + after: { isOpen: true, activeSurfaceId: "diff", surfaces: [diff] }, + drawerOpen: false, + unseen, + }), + ).toBe(unseen); + }); +}); + +describe("changes novelty", () => { + const latest = { turnCount: 3, count: 2 }; + + it("has no dot before the open panel seeds a seen turn", () => { + expect(changesNovel({ latest, seenTurnCount: undefined, changesVisible: false })).toBe(false); + }); + + it("lights for a newer turn that changed files while Changes is hidden", () => { + expect(changesNovel({ latest, seenTurnCount: 2, changesVisible: false })).toBe(true); }); - it("has no count before the first turn", () => { - expect(latestTurnChangedFileCount([])).toBeNull(); + it("stays off for a newer turn that changed no files", () => { + expect( + changesNovel({ latest: { turnCount: 3, count: 0 }, seenTurnCount: 2, changesVisible: false }), + ).toBe(false); }); + + it("stays off while Changes is visible", () => { + expect(changesNovel({ latest, seenTurnCount: 2, changesVisible: true })).toBe(false); + }); +}); + +describe("terminal adoption", () => { + const snapshot = "manager-1"; + + it("adopts every server terminal no surface owns, in server order", () => { + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(["b"]), + serverIds: ["c", "b", "a"], + previous: undefined, + snapshotId: snapshot, + closingIds: [], + }), + ).toEqual({ adopt: ["c", "a"], drop: [] }); + }); + + it("skips terminals that are closing", () => { + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(), + serverIds: ["a", "b"], + previous: undefined, + snapshotId: snapshot, + closingIds: ["a"], + }).adopt, + ).toEqual(["b"]); + }); + + it("drops only ids the server listed before and no longer lists", () => { + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(["a", "b", "local"]), + serverIds: ["a"], + previous: { ids: ["a", "b"], snapshotId: snapshot }, + snapshotId: snapshot, + closingIds: [], + }), + ).toEqual({ adopt: [], drop: ["b"] }); + }); + + it("never drops on the first observation or when the snapshot changes", () => { + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(["a"]), + serverIds: [], + previous: undefined, + snapshotId: snapshot, + closingIds: [], + }).drop, + ).toEqual([]); + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(["a"]), + serverIds: [], + previous: { ids: ["a"], snapshotId: snapshot }, + snapshotId: "manager-2", + closingIds: [], + }).drop, + ).toEqual([]); + }); + + it("adopts a session created later within the same snapshot", () => { + expect( + reconcileTerminalSurfaceIds({ + ownedIds: new Set(["a"]), + serverIds: ["a", "setup"], + previous: { ids: ["a"], snapshotId: snapshot }, + snapshotId: snapshot, + closingIds: [], + }), + ).toEqual({ adopt: ["setup"], drop: [] }); + }); +}); + +describe("terminal mounting", () => { + it("mounts only ids the server lists or this client opened, and waits while the list is unknown", () => { + expect( + terminalSurfaceMount({ terminalIds: ["a", "b"], serverIds: ["b"], claimedIds: [] }), + ).toEqual({ kind: "mount", terminalIds: ["b"] }); + expect( + terminalSurfaceMount({ terminalIds: ["a"], serverIds: null, claimedIds: ["a"] }), + ).toEqual({ kind: "mount", terminalIds: ["a"] }); + expect(terminalSurfaceMount({ terminalIds: ["a"], serverIds: null, claimedIds: [] })).toEqual({ + kind: "pending", + }); + // A saved sub-tab the server no longer lists, after a restart: attaching would start a shell. + expect(terminalSurfaceMount({ terminalIds: ["a"], serverIds: [], claimedIds: [] })).toEqual({ + kind: "ended", + }); + }); + + it("ignores claims made before the server restarted, until reconcile clears them", () => { + const claimedIds = ["a"]; + expect( + currentTerminalClaims({ claimedIds, observedSnapshotId: "m1", serverSnapshotId: "m2" }), + ).toEqual([]); + expect( + currentTerminalClaims({ claimedIds, observedSnapshotId: "m1", serverSnapshotId: "m1" }), + ).toEqual(["a"]); + expect( + currentTerminalClaims({ claimedIds, observedSnapshotId: undefined, serverSnapshotId: "m2" }), + ).toEqual(["a"]); + }); +}); + +describe("mounted terminal threads", () => { + const open = new Set(["a", "b", "c", "d"]); + + it("mounts the active thread once its drawer shows and keeps it through a collapse", () => { + const reconcile = (current: string[], activeShowing: boolean) => + reconcileMountedTerminalThreads({ current, panelOpen: open, active: "a", activeShowing }); + expect(reconcile([], false)).toEqual([]); + expect(reconcile([], true)).toEqual(["a"]); + expect(reconcile(["a"], false)).toEqual(["a"]); + }); + + it("keeps recently shown threads whose panel is open, most recent last, up to the cap", () => { + expect( + reconcileMountedTerminalThreads({ + current: ["a", "b", "c"], + panelOpen: open, + active: "a", + activeShowing: true, + }), + ).toEqual(["b", "c", "a"]); + expect( + reconcileMountedTerminalThreads({ + current: ["a", "b", "c"], + panelOpen: new Set(["a", "c", "d"]), + active: "d", + activeShowing: true, + maxHidden: 1, + }), + ).toEqual(["c", "d"]); + }); +}); + +function terminalSummary( + overrides: Partial>, +): TerminalSummary { + return { + threadId: "t", + terminalId: "a", + cwd: "/", + worktreePath: null, + status: "running", + pid: 1, + exitCode: null, + exitSignal: null, + hasRunningSubprocess: false, + label: "", + updatedAt: "", + ...overrides, + }; +} + +describe("terminal drawer status", () => { + it.each([ + ["running with a subprocess", { status: "running", hasRunningSubprocess: true }, "running"], + ["exited 0", { status: "exited", exitCode: 0 }, "ok"], + ["exited 1", { status: "exited", exitCode: 1 }, "failed"], + ["error", { status: "error" }, "failed"], + ["starting without a subprocess", { status: "starting" }, null], + ] as const)("%s", (_name, overrides, expected) => { + expect(terminalDrawerStatus(terminalSummary(overrides))).toBe(expected); + }); + + it("has no status without a summary", () => { + expect(terminalDrawerStatus(null)).toBeNull(); + }); +}); + +it("clamps drawer height to the container and falls back to the default", () => { + expect(clampTerminalDrawerHeight(2000, 600)).toBe(480); + expect(clampTerminalDrawerHeight(10, 600)).toBe(TERMINAL_DRAWER_MIN_HEIGHT); + expect(clampTerminalDrawerHeight(300, 600)).toBe(300); + expect(clampTerminalDrawerHeight(Number.NaN, 600)).toBe(280); }); diff --git a/apps/web/src/components/RightPanelTabs.logic.ts b/apps/web/src/components/RightPanelTabs.logic.ts index 9b0d4139f630c..a1e612b0cf4b9 100644 --- a/apps/web/src/components/RightPanelTabs.logic.ts +++ b/apps/web/src/components/RightPanelTabs.logic.ts @@ -2,53 +2,243 @@ import { checkpointFileTotals, type ThreadCheckpointSummary, } from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { TerminalSummary } from "@t3tools/contracts"; -import type { RightPanelSurface } from "~/rightPanelStore"; +import type { RightPanelSurface, ThreadRightPanelState } from "~/rightPanelStore"; +import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "~/types"; -export type RightPanelSection = "changes" | "terminal" | "browser"; +export type RightPanelToolGroup = + | "changes" + | "browser" + | "files" + | "reviews" + | "devices" + | "threads"; +export type RightPanelRailGroup = RightPanelToolGroup | "terminal"; -const SECTION_SURFACE_KIND = { - changes: "diff", +const RIGHT_PANEL_TOOL_GROUPS: readonly RightPanelToolGroup[] = [ + "changes", + "browser", + "files", + "reviews", + "devices", + "threads", +]; + +const GROUP_OF_KIND = { + diff: "changes", + preview: "browser", + files: "files", + file: "files", + "pull-requests": "reviews", + "pull-request": "reviews", + issue: "reviews", + device: "devices", + thread: "threads", + "linked-thread": "threads", terminal: "terminal", - browser: "preview", -} as const satisfies Record; +} as const satisfies Record; -export function rightPanelSectionOf(surface: RightPanelSurface | undefined) { - if (!surface) return null; - for (const [section, kind] of Object.entries(SECTION_SURFACE_KIND)) { - if (surface.kind === kind) return section as RightPanelSection; - } - return null; +export function rightPanelGroupOf(surface: RightPanelSurface): RightPanelRailGroup { + return GROUP_OF_KIND[surface.kind]; } /** - * The surface a section tab shows: the active one when it already belongs to the section, - * else the newest of its kind. Null means the section has none yet and must create one. + * The surface a group's icon shows: the active one when it already belongs to the group, else + * the newest of the group. Null means the group has none yet and must create one. */ -export function rightPanelSectionTarget( +export function rightPanelGroupTarget( surfaces: readonly RightPanelSurface[], activeSurfaceId: string | null, - section: RightPanelSection, + group: RightPanelToolGroup, ): RightPanelSurface | null { - const kind = SECTION_SURFACE_KIND[section]; const active = surfaces.find((surface) => surface.id === activeSurfaceId); - if (active?.kind === kind) return active; - return surfaces.findLast((surface) => surface.kind === kind) ?? null; + if (active && rightPanelGroupOf(active) === group) return active; + return surfaces.findLast((surface) => rightPanelGroupOf(surface) === group) ?? null; } -/** The Changes tab stands for the diff surface, so the diff gets no tab of its own. */ -export function rightPanelDynamicTabSurfaces( - surfaces: readonly RightPanelSurface[], -): readonly RightPanelSurface[] { - return surfaces.filter((surface) => surface.kind !== "diff"); +const ALWAYS_SHOWN_GROUPS = new Set(["changes", "browser", "files"]); + +/** An open surface keeps its group on the rail, so nothing open becomes unreachable. */ +export function visibleRightPanelToolGroups(input: { + surfaces: readonly RightPanelSurface[]; + available: Readonly>; +}): readonly RightPanelToolGroup[] { + const present = new Set(input.surfaces.map(rightPanelGroupOf)); + return RIGHT_PANEL_TOOL_GROUPS.filter( + (group) => + ALWAYS_SHOWN_GROUPS.has(group) || + present.has(group) || + input.available[group as "reviews" | "devices" | "threads"], + ); } -export function latestTurnChangedFileCount( +type PanelVisibilityState = Pick; + +export function visibleRightPanelGroups( + state: PanelVisibilityState, + drawerOpen: boolean, +): ReadonlySet { + const visible = new Set(); + if (!state.isOpen) return visible; + const active = state.surfaces.find((surface) => surface.id === state.activeSurfaceId); + if (active && active.kind !== "terminal") visible.add(rightPanelGroupOf(active)); + if (drawerOpen) visible.add("terminal"); + return visible; +} + +export function nextUnseenRightPanelGroups(input: { + before: readonly RightPanelSurface[]; + after: PanelVisibilityState; + drawerOpen: boolean; + unseen: readonly RightPanelRailGroup[]; +}): readonly RightPanelRailGroup[] { + const visible = visibleRightPanelGroups(input.after, input.drawerOpen); + const beforeIds = new Set(input.before.map((surface) => surface.id)); + const next = new Set(input.unseen.filter((group) => !visible.has(group))); + for (const surface of input.after.surfaces) { + if (beforeIds.has(surface.id)) continue; + const group = rightPanelGroupOf(surface); + if (!visible.has(group)) next.add(group); + } + if (next.size === input.unseen.length && input.unseen.every((group) => next.has(group))) { + return input.unseen; + } + return [...next]; +} + +export function changesNovel(input: { + latest: { turnCount: number; count: number } | null; + seenTurnCount: number | undefined; + changesVisible: boolean; +}): boolean { + if (input.seenTurnCount === undefined || input.changesVisible) return false; + return ( + input.latest !== null && input.latest.count > 0 && input.latest.turnCount > input.seenTurnCount + ); +} + +export function latestTurnChangeTotals( summaries: ReadonlyArray, -): number | null { +): { turnCount: number; count: number; additions: number; deletions: number } | null { let latest: ThreadCheckpointSummary | undefined; for (const summary of summaries) { if (!latest || summary.checkpointTurnCount > latest.checkpointTurnCount) latest = summary; } - return latest ? checkpointFileTotals(latest).count : null; + if (!latest) return null; + const totals = checkpointFileTotals(latest); + return { + turnCount: latest.checkpointTurnCount, + count: totals.count, + additions: totals.additions, + deletions: totals.deletions, + }; +} + +/** + * Drops only follow a listing of the same snapshot, so a reconnect that briefly lists nothing + * counts as a first observation and never takes a sub-tab away. + */ +export function reconcileTerminalSurfaceIds(input: { + ownedIds: ReadonlySet; + serverIds: readonly string[]; + previous: { ids: readonly string[]; snapshotId: string | symbol | undefined } | undefined; + snapshotId: string | symbol | undefined; + closingIds: readonly string[]; +}): { adopt: readonly string[]; drop: readonly string[] } { + const closing = new Set(input.closingIds); + const server = new Set(input.serverIds); + const adopt = input.serverIds.filter((id) => !input.ownedIds.has(id) && !closing.has(id)); + const drop = + input.previous === undefined || input.previous.snapshotId !== input.snapshotId + ? [] + : input.previous.ids.filter((id) => !server.has(id) && input.ownedIds.has(id)); + return { adopt, drop }; +} + +export type TerminalSurfaceMount = + | { readonly kind: "mount"; readonly terminalIds: string[] } + | { readonly kind: "pending" } + | { readonly kind: "ended" }; + +/** + * Attaching to an id the server does not know starts a new shell, so a sub-tab mounts only ids + * the server lists or that this client opened since the server last restarted. + */ +export function terminalSurfaceMount(input: { + terminalIds: readonly string[]; + serverIds: readonly string[] | null; + claimedIds: readonly string[]; +}): TerminalSurfaceMount { + const mountable = input.terminalIds.filter( + (id) => input.serverIds?.includes(id) === true || input.claimedIds.includes(id), + ); + if (mountable.length > 0) return { kind: "mount", terminalIds: mountable }; + return input.serverIds === null ? { kind: "pending" } : { kind: "ended" }; +} + +/** + * Claims are cleared when the thread's reconcile sees a new server snapshot, which runs only + * after a render; until then a list from a restarted server voids them. + */ +export function currentTerminalClaims(input: { + claimedIds: readonly string[]; + observedSnapshotId: string | symbol | undefined; + serverSnapshotId: string | symbol | undefined; +}): readonly string[] { + return input.observedSnapshotId === undefined || + input.serverSnapshotId === undefined || + input.observedSnapshotId === input.serverSnapshotId + ? input.claimedIds + : []; +} + +const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; + +/** + * Threads whose drawer terminals stay mounted, least recently shown first: the active thread + * once its drawer has shown, and other threads whose panel is still open, so switching back + * does not re-attach and replay history. + */ +export function reconcileMountedTerminalThreads(input: { + current: readonly string[]; + panelOpen: ReadonlySet; + active: string | null; + activeShowing: boolean; + maxHidden?: number; +}): string[] { + const kept = input.current.filter( + (key) => input.panelOpen.has(key) && !(key === input.active && input.activeShowing), + ); + if (input.active !== null && input.activeShowing) kept.push(input.active); + const maxHidden = input.maxHidden ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS; + let excess = kept.filter((key) => key !== input.active).length - maxHidden; + return kept.filter((key) => key === input.active || excess-- <= 0); +} + +export type TerminalDrawerStatus = "running" | "ok" | "failed"; + +export function terminalDrawerStatus(summary: TerminalSummary | null): TerminalDrawerStatus | null { + if (!summary) return null; + if (summary.status === "error" || (summary.exitCode !== null && summary.exitCode !== 0)) { + return "failed"; + } + if (summary.status === "exited" && summary.exitCode === 0) return "ok"; + if ( + (summary.status === "starting" || summary.status === "running") && + summary.hasRunningSubprocess + ) { + return "running"; + } + return null; +} + +export const TERMINAL_DRAWER_MIN_HEIGHT = 120; +export const TERMINAL_DRAWER_COLLAPSED_HEIGHT = 30; +const TERMINAL_DRAWER_TOOL_RESERVE = 120; + +export function clampTerminalDrawerHeight(height: number, containerHeight: number): number { + if (!Number.isFinite(height)) return DEFAULT_THREAD_TERMINAL_HEIGHT; + const max = Math.max(TERMINAL_DRAWER_MIN_HEIGHT, containerHeight - TERMINAL_DRAWER_TOOL_RESERVE); + return Math.min(Math.max(height, TERMINAL_DRAWER_MIN_HEIGHT), max); } diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 0807ef99a4613..ceeb127a6e2a0 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1,7 +1,7 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { m, type MessageResolver } from "../i18n/messages"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadRuntimeIsActive, type EnvironmentThreadShell, @@ -44,8 +44,7 @@ import { CircleDotIcon, Smartphone, ChevronDown, - ChevronLeft, - ChevronRight, + Ellipsis, FileDiff, Files, Globe2, @@ -56,7 +55,6 @@ import { VolumeOffIcon, } from "lucide-react"; import { - type ComponentType, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type ReactElement, @@ -73,11 +71,17 @@ import { linkedThreadTitle } from "~/linkedThreadSurface"; import type { RightPanelSurface } from "~/rightPanelStore"; import { cn } from "~/lib/utils"; import { - rightPanelDynamicTabSurfaces, - rightPanelSectionOf, - rightPanelSectionTarget, - type RightPanelSection, + rightPanelGroupOf, + rightPanelGroupTarget, + type RightPanelRailGroup, + type RightPanelToolGroup, } from "./RightPanelTabs.logic"; +import { + RIGHT_PANEL_GROUP_LABELS, + RightPanelRail, + type RightPanelRailProps, +} from "./RightPanelRail"; +import { DiffStatLabel } from "./chat/DiffStatLabel"; import { issueStatePresentation } from "~/components/issue/issuePresentation"; import { issueEnvironment } from "~/state/issues"; import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings"; @@ -122,6 +126,10 @@ import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; +import { + RightPanelTerminalDrawer, + type RightPanelTerminalDrawerProps, +} from "./RightPanelTerminalDrawer"; export interface RightPanelTabsProps { mode: PreviewPanelMode; @@ -151,7 +159,8 @@ export interface RightPanelTabsProps { ) => void; onCloseOtherSurfaces: (surface: RightPanelSurface) => void; onCloseSurfacesToRight: (surface: RightPanelSurface) => void; - onCloseAllSurfaces: () => void; + /** Closes the surfaces of `surface`'s group. */ + onCloseAllSurfaces: (surface: RightPanelSurface) => void; onMoveSurface?: (surfaceId: string, toIndex: number) => void; onCopyFilePath: (relativePath: string) => void; onAddBrowser: () => void; @@ -176,11 +185,21 @@ export interface RightPanelTabsProps { /** Overrides the default reason while side chats are available but cannot start. */ sideChatDisabledReason?: string | null; pullRequestStatusSeeds?: Readonly>; - /** Files the latest turn changed, shown on the Changes tab. */ - changesCount?: number | null; + /** The latest turn's changes, shown in the Changes header. */ + changeTotals?: { count: number; additions: number; deletions: number } | null; + /** Null on the pull-request and issue pages, which show every surface as a sub-tab instead. */ + rail: RightPanelRailInput | null; + /** Absent on pages without a thread, such as the pull-request and issue lists. */ + terminalDrawer?: RightPanelTerminalDrawerProps | null; children: ReactNode; } +/** What the thread knows about its rail; the panel adds the active group, creation and the launcher. */ +export type RightPanelRailInput = Pick< + RightPanelRailProps, + "groups" | "dots" | "terminalOpen" | "shortcutLabels" | "onToggleTerminal" +>; + export interface PullRequestTabStatus { projectId: string; repository: string; @@ -906,44 +925,6 @@ function PullRequestSurfaceIcon({ return ; } -function RightPanelSectionTab(props: { - label: string; - icon: ComponentType<{ className?: string }>; - count: number | null; - active: boolean; - available: boolean; - disabledReason: string; - ownsDesktopTitleBar: boolean; - onSelect: () => void; -}) { - const Icon = props.icon; - const button = ( - - ); - if (props.available) return button; - return ; -} - function SortableTabList(props: { surfaces: readonly RightPanelSurface[]; /** The full surface list, since drops move by index into it, not into the shown tabs. */ @@ -1168,6 +1149,14 @@ function RightPanelTab( ); } +const MULTI_INSTANCE_GROUPS = new Set([ + "browser", + "files", + "reviews", + "devices", + "threads", +]); + export function RightPanelTabs(props: RightPanelTabsProps) { const gt = useGT(); const messages = useMessages(); @@ -1179,11 +1168,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const addSurfaceTriggerRef = useRef(null); const [renamingDevice, setRenamingDevice] = useState(null); const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false); - const [tabScrollState, setTabScrollState] = useState({ - hasOverflow: false, - canScrollLeft: false, - canScrollRight: false, - }); + const [tabStripOverflows, setTabStripOverflows] = useState(false); if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); @@ -1221,34 +1206,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }; }, [props.open]); - const updateTabScrollState = (viewport: HTMLDivElement) => { - const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; - const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; - const canScrollRight = - hasOverflow && - viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE; - setTabScrollState((current) => { - if ( - current.hasOverflow === hasOverflow && - current.canScrollLeft === canScrollLeft && - current.canScrollRight === canScrollRight - ) { - return current; - } - return { hasOverflow, canScrollLeft, canScrollRight }; - }); - }; - - const scrollTabs = (direction: -1 | 1) => { - const viewport = tabScrollViewport(tabListRef.current); - if (!viewport) return; - const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; - viewport.scrollBy({ - left: direction * Math.max(120, viewport.clientWidth * 0.75), - behavior: reduceMotion ? "auto" : "smooth", - }); - }; - const addSurfaceActions = [ { label: msg("Browser"), @@ -1321,45 +1278,81 @@ export function RightPanelTabs(props: RightPanelTabsProps) { : []), ] as const; - const dynamicSurfaces = rightPanelDynamicTabSurfaces(props.surfaces); - const activeSection = rightPanelSectionOf(focusedSurface); - const sectionTabs = [ - { - section: "changes", - label: msg("Changes"), - icon: FileDiff, - count: props.changesCount ?? null, + const rail = props.rail ?? null; + const activeGroup = + focusedSurface && focusedSurface.kind !== "terminal" + ? (rightPanelGroupOf(focusedSurface) as RightPanelToolGroup) + : null; + const showTabStrip = + rail === null || (activeGroup !== null && MULTI_INSTANCE_GROUPS.has(activeGroup)); + const headerSurfaces = + rail === null + ? props.surfaces.filter((surface) => surface.kind !== "terminal") + : showTabStrip + ? props.surfaces.filter((surface) => rightPanelGroupOf(surface) === activeGroup) + : []; + + const sideChatCanStart = + props.onAddSideChat !== undefined && + props.sideChatAvailable === true && + !props.sideChatDisabledReason; + const groupCreation = { + changes: { available: props.diffAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.diff), + reason: messages(SURFACE_UNAVAILABLE_HINTS.diff), create: props.onAddDiff, }, - { - section: "terminal", - label: msg("Terminal"), - icon: TerminalSquare, - count: null, - available: props.terminalAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.terminal), - create: props.onAddTerminal, - }, - { - section: "browser", - label: msg("Browser"), - icon: Globe2, - count: null, + browser: { available: props.browserAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.browser), + reason: messages(SURFACE_UNAVAILABLE_HINTS.browser), create: props.onAddBrowser, }, - ] as const; - const showSection = (section: RightPanelSection) => { - const target = rightPanelSectionTarget(props.surfaces, props.activeSurfaceId, section); + files: { + available: props.filesAvailable, + reason: messages(SURFACE_UNAVAILABLE_HINTS.files), + create: props.onAddFiles, + }, + reviews: { + available: props.pullRequestAvailable || props.pullRequestsAvailable, + reason: messages(SURFACE_UNAVAILABLE_HINTS.pullRequests), + create: props.pullRequestAvailable ? props.onAddPullRequest : props.onAddPullRequests, + }, + devices: { + available: props.deviceAvailable, + reason: messages(SURFACE_UNAVAILABLE_HINTS.device), + create: props.onAddDevice, + }, + threads: { + available: sideChatCanStart, + reason: props.sideChatDisabledReason ?? messages(SURFACE_UNAVAILABLE_HINTS.sideChat), + create: () => props.onAddSideChat?.(), + }, + } satisfies Record< + RightPanelToolGroup, + { available: boolean; reason: string; create: () => void } + >; + // A maximized drawer covers the tool, so picking one restores it. + const restoreFromMaximizedDrawer = () => { + if (props.terminalDrawer?.open && props.terminalDrawer.maximized) { + props.terminalDrawer.onToggleMaximized(); + } + }; + const selectGroup = (group: RightPanelToolGroup) => { + restoreFromMaximizedDrawer(); + const target = rightPanelGroupTarget(props.surfaces, props.activeSurfaceId, group); if (target) { props.onActivate(target); return; } - sectionTabs.find((tab) => tab.section === section)?.create(); + if (groupCreation[group].available) groupCreation[group].create(); }; + const railUnavailable = Object.fromEntries( + (rail?.groups ?? []).flatMap((group) => + groupCreation[group].available || rightPanelGroupTarget(props.surfaces, null, group) !== null + ? [] + : [[group, groupCreation[group].reason]], + ), + ) as Partial>; const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); @@ -1370,60 +1363,60 @@ export function RightPanelTabs(props: RightPanelTabsProps) { action.onClick(); }; - const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => { - event.preventDefault(); - event.stopPropagation(); - - const api = readLocalApi(); - if (!api) return; - - const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id); - if (surfaceIndex < 0) return; - + const surfaceMenuItems = ( + surface: RightPanelSurface, + resolve: MessageResolver, + ): ContextMenuItem[] => { + const group = props.surfaces.filter( + (entry) => rightPanelGroupOf(entry) === rightPanelGroupOf(surface), + ); + const groupIndex = group.findIndex((entry) => entry.id === surface.id); const items: ContextMenuItem[] = []; if ((surface.kind === "thread" || surface.kind === "linked-thread") && props.onOpenInMainView) { - items.push({ id: "open-in-main-view", label: gt("Open in main view") }); + items.push({ id: "open-in-main-view", label: resolve(msg("Open in main view")) }); } if (surface.kind === "device" && props.onRenameDevice) - items.push({ id: "rename", label: gt("Rename") }); + items.push({ id: "rename", label: resolve(msg("Rename")) }); if (surface.kind === "file" && surface.attachment === undefined) { - items.push({ id: "copy-path", label: gt("Copy path") }); + items.push({ id: "copy-path", label: resolve(msg("Copy path")) }); } - const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions); - const menuOverlay = menuPreviewTabId ? (props.desktopByTabId[menuPreviewTabId] ?? null) : null; - const menuMuted = menuOverlay?.audioMuted ?? false; if (surface.kind === "preview") { + const previewTabId = previewTabIdOf(surface, props.previewSessions); items.push({ id: "toggle-mute", ...tabMuteMenuItem( { - overlay: menuOverlay, + overlay: previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null, canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined, }, - messages, + resolve, ), }); } items.push( - { id: "close", label: gt("Close") }, + { id: "close", label: resolve(msg("Close")) }, { id: "close-others", - label: gt("Close others"), - disabled: props.surfaces.length <= 1, + label: resolve(msg("Close others")), + disabled: group.length <= 1, }, { id: "close-to-right", - label: gt("Close to the right"), - disabled: surfaceIndex >= props.surfaces.length - 1, + label: resolve(msg("Close to the right")), + disabled: groupIndex >= group.length - 1, }, { id: "close-all", - label: gt("Close all"), - disabled: props.surfaces.length === 0, + label: resolve(msg("Close all in this group")), + disabled: group.length === 0, }, ); - - const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY }); + return items; + }; + const runSurfaceMenuAction = ( + action: TabContextMenuAction | null, + surface: RightPanelSurface, + ) => { switch (action) { case "open-in-main-view": if (surface.kind === "thread" || surface.kind === "linked-thread") { @@ -1439,12 +1432,14 @@ export function RightPanelTabs(props: RightPanelTabsProps) { } break; case "toggle-mute": { + const previewTabId = previewTabIdOf(surface, props.previewSessions); + const overlay = previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null; const runtimeTabId = - menuPreviewTabId && menuOverlay - ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null) - : null; + previewTabId && overlay ? (props.previewRuntimeTabId?.(previewTabId) ?? null) : null; if (runtimeTabId) { - void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined); + void previewBridge + ?.setAudioMuted(runtimeTabId, !(overlay?.audioMuted ?? false)) + .catch(() => undefined); } break; } @@ -1458,19 +1453,35 @@ export function RightPanelTabs(props: RightPanelTabsProps) { props.onCloseSurfacesToRight(surface); break; case "close-all": - props.onCloseAllSurfaces(); + props.onCloseAllSurfaces(surface); break; case null: break; } }; + + const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => { + event.preventDefault(); + event.stopPropagation(); + const api = readLocalApi(); + if (!api) return; + if (!props.surfaces.some((entry) => entry.id === surface.id)) return; + const action = await api.contextMenu.show(surfaceMenuItems(surface, messages), { + x: event.clientX, + y: event.clientY, + }); + runSurfaceMenuAction(action, surface); + }; const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => { if (event.button !== 1) return; event.preventDefault(); event.stopPropagation(); props.onCloseSurface(surface); }; - const onActivateTab = useStableCallback(props.onActivate); + const onActivateTab = useStableCallback((surface: RightPanelSurface) => { + restoreFromMaximizedDrawer(); + props.onActivate(surface); + }); const onCloseTab = useStableCallback(props.onCloseSurface); const onTabAuxClick = useStableCallback(handleTabAuxClick); const onTabContextMenu = useStableCallback( @@ -1487,17 +1498,18 @@ export function RightPanelTabs(props: RightPanelTabsProps) { // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the active tab DOM node into view after it changes or the tab strip starts overflowing useEffect(() => { - if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return; + if (!props.activeSurfaceId || !tabStripOverflows) return; const activeTab = tabListRef.current?.querySelector("[data-active-tab='true']"); activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" }); - }, [props.activeSurfaceId, tabScrollState.hasOverflow]); + }, [props.activeSurfaceId, tabStripOverflows]); const attachTabList = (root: HTMLDivElement | null) => { tabListRef.current = root; const viewport = tabScrollViewport(root); if (!viewport) return; - const update = () => updateTabScrollState(viewport); + const update = () => + setTabStripOverflows(viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE); // Only a vertical mouse wheel is translated. Horizontal input scrolls natively, since // consuming it keeps Chromium from starting the gesture scroll that swipe navigation tracks. const handleWheel = (event: WheelEvent) => { @@ -1510,23 +1522,205 @@ export function RightPanelTabs(props: RightPanelTabsProps) { viewport.scrollLeft += delta; if (viewport.scrollLeft === previousScrollLeft) return; event.preventDefault(); - update(); }; const content = viewport.firstElementChild; const stopObserving = observeResize(content ? [viewport, content] : viewport, update); - viewport.addEventListener("scroll", update, { passive: true }); viewport.addEventListener("wheel", handleWheel, { passive: false }); update(); return () => { tabListRef.current = null; stopObserving(); - viewport.removeEventListener("scroll", update); viewport.removeEventListener("wheel", handleWheel); }; }; + const launcher = + props.open !== false ? ( + + + ) : ( + // The launcher opens from mod+t; it anchors at the rail's top with no visible button. + + ) : null; + + const groupLabel = activeGroup === null ? null : messages(RIGHT_PANEL_GROUP_LABELS[activeGroup]); + const groupAddButton = (() => { + if (rail === null || activeGroup === null) return null; + const addLabel = gt("New {group} tab", { group: groupLabel ?? "" }); + const plainButton = (onClick: () => void, available: boolean) => ( + + ); + switch (activeGroup) { + case "browser": + return browserProfiles.length > 1 && props.browserAvailable ? ( + + } + > + + + + {browserProfiles.map((profile) => ( + props.onAddBrowserInProfile(profile.id)}> + {profile.name} + + ))} + + + ) : ( + plainButton(props.onAddBrowser, props.browserAvailable) + ); + case "reviews": + return ( + + } + > + + + + + + {gt("Pull request")} + + + + {gt("Linked items")} + + + + ); + case "devices": + return plainButton(props.onAddDevice, props.deviceAvailable); + case "threads": + return props.onAddSideChat + ? plainButton(() => props.onAddSideChat?.(), sideChatCanStart) + : null; + case "changes": + case "files": + return null; + } + })(); + + const moreMenuItems = + focusedSurface && focusedSurface.kind !== "terminal" + ? surfaceMenuItems(focusedSurface, messages) + : []; + const moreMenu = + focusedSurface && moreMenuItems.length > 0 ? ( + + + } + > + + + + {moreMenuItems.map((item) => ( + runSurfaceMenuAction(item.id, focusedSurface)} + > + {item.label} + + ))} + + + ) : null; + return (
- -
-
- {sectionTabs.map((tab) => ( - showSection(tab.section)} - /> - ))} -
- {dynamicSurfaces.length > 0 ? ( - - ) : null} - - {dynamicSurfaces.map((surface) => { - const previewTabId = previewTabIdOf(surface, props.previewSessions); - const favicon = previewFaviconOf( - surface, - props.previewSessions, - props.desktopByTabId, - ); - return ( - - ); + {groupLabel !== null && rail !== null ? ( + + {groupLabel} + + ) : null} + {activeGroup === "changes" && props.changeTotals ? ( + + {/* The totals are the latest turn's, whatever scope the diff below shows. */} + + {gt("Last turn", { $context: "the Changes header totals cover the latest turn" })} + + + + {gt("{count, plural, one {# file} other {# files}}", { + count: props.changeTotals.count, })} - - {props.open !== false ? ( - - - } - > - - - - {addSurfaceActions.map((action) => { - const Icon = action.icon; - if (action.label === "Browser" && action.available) { - return ( - - { - const pointerType = - "pointerType" in event.nativeEvent && - typeof event.nativeEvent.pointerType === "string" - ? event.nativeEvent.pointerType - : undefined; - if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType)) - return; - setAddSurfaceMenuOpen(false); - action.onClick(); - }} - > - - {messages(action.label)} - {action.shortcut} - - - {browserProfiles.map((profile) => ( - props.onAddBrowserInProfile(profile.id)} - > - {profile.name} - - ))} - - - ); - } - return ( - - - {messages(action.label)} - - ); - })} - - - ) : null} -
-
- {tabScrollState.hasOverflow ? ( -
+ + ) : null} + {showTabStrip ? ( + - - - - - } - /> - - Scroll tabs left - - - - - - - } - /> - - Scroll tabs right - - -
+
+ + {headerSurfaces.map((surface) => { + const previewTabId = previewTabIdOf(surface, props.previewSessions); + const favicon = previewFaviconOf( + surface, + props.previewSessions, + props.desktopByTabId, + ); + return ( + + ); + })} + + {groupAddButton ? ( + {groupAddButton} + ) : null} + {rail === null ? launcher : null} +
+ + ) : ( +
+ )} + {moreMenu ? ( + {moreMenu} ) : null} {props.layoutControls} {ownsDesktopTitleBar && !props.layoutControls ? ( @@ -1786,32 +1875,61 @@ export function RightPanelTabs(props: RightPanelTabsProps) { /> ) : null}
-
- {props.activeSurfaceId === null ? ( - +
+
+ {props.activeSurfaceId === null ? ( + + ) : ( + props.children + )} +
+ {props.terminalDrawer ? ( + + ) : null} +
+ {rail ? ( + - ) : ( - props.children - )} + ) : null}
); diff --git a/apps/web/src/components/RightPanelTerminalBodies.tsx b/apps/web/src/components/RightPanelTerminalBodies.tsx new file mode 100644 index 0000000000000..6917a6a46c837 --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalBodies.tsx @@ -0,0 +1,90 @@ +import { memo, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { useShallow } from "zustand/react/shallow"; + +import { + selectActiveTerminalSurface, + useRightPanelStore, + type TerminalPanelSurface, +} from "~/rightPanelStore"; + +import type { RightPanelTerminalProps } from "./chat/RightPanelSurfaceContent"; +import { reconcileMountedTerminalThreads } from "./RightPanelTabs.logic"; +import { RightPanelTerminalBody } from "./RightPanelTerminalBody"; +import type { TerminalBodyHost, TerminalBodyHosts } from "./terminalBodyHosts"; + +const EMPTY_KEYS: readonly string[] = []; + +/** Keeps drawer terminals mounted for recently shown threads; only the active one is visible. */ +export function RightPanelTerminalBodies(props: { + hosts: TerminalBodyHosts; + activeThreadKey: string | null; + drawerVisible: boolean; + terminal: RightPanelTerminalProps; +}) { + const { hosts, activeThreadKey } = props; + const panelOpenKeys = useRightPanelStore( + useShallow((state) => + Object.entries(state.byThreadKey).flatMap(([threadKey, thread]) => + thread.isOpen && thread.surfaces.some((surface) => surface.kind === "terminal") + ? [threadKey] + : [], + ), + ), + ); + const [mounted, setMounted] = useState(EMPTY_KEYS); + const next = reconcileMountedTerminalThreads({ + current: mounted, + panelOpen: new Set(panelOpenKeys), + active: activeThreadKey, + activeShowing: props.drawerVisible, + }); + if (next.length !== mounted.length || next.some((key, index) => key !== mounted[index])) { + setMounted(next); + } + const holderRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- gives parked hosts a hidden DOM home and drops the hosts of threads whose terminals unmounted + useLayoutEffect(() => { + hosts.setHolder(holderRef.current); + hosts.retain(new Set(activeThreadKey === null ? mounted : [...mounted, activeThreadKey])); + }, [activeThreadKey, hosts, mounted]); + const hiddenTerminal = { ...props.terminal, launchContext: null }; + + return ( + + ); +} + +const ThreadTerminalBodyPortal = memo(function ThreadTerminalBodyPortal(props: { + host: TerminalBodyHost; + visible: boolean; + terminal: RightPanelTerminalProps; +}) { + const { threadRef } = props.host; + const surface = useRightPanelStore((state): TerminalPanelSurface | null => + selectActiveTerminalSurface(state.byThreadKey, threadRef), + ); + if (!surface || !threadRef) return null; + return createPortal( + , + props.host.element, + ); +}); diff --git a/apps/web/src/components/RightPanelTerminalBody.tsx b/apps/web/src/components/RightPanelTerminalBody.tsx new file mode 100644 index 0000000000000..f1c77d4a6467d --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalBody.tsx @@ -0,0 +1,103 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { AuthTerminalOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; +import { T } from "gt-react"; +import { memo } from "react"; + +import { Button } from "~/components/ui/button"; +import { + selectClaimedTerminalIds, + useRightPanelStore, + type TerminalPanelSurface, +} from "~/rightPanelStore"; +import { useEnvironmentScope } from "~/state/session"; +import { useTerminalDrawerSessions } from "~/state/terminalSessions"; + +import type { RightPanelTerminalProps } from "./chat/RightPanelSurfaceContent"; +import { PersistentThreadTerminalPanel } from "./PersistentThreadTerminals"; +import { currentTerminalClaims, terminalSurfaceMount } from "./RightPanelTabs.logic"; +import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions"; + +export interface RightPanelTerminalBodyProps { + threadRef: ScopedThreadRef; + surface: TerminalPanelSurface; + visible: boolean; + terminal: RightPanelTerminalProps; +} + +/** A drawer sub-tab's terminal, mounted only when attaching to it cannot start a new shell. */ +export const RightPanelTerminalBody = memo(function RightPanelTerminalBody( + props: RightPanelTerminalBodyProps, +) { + const { threadRef, surface } = props; + const listing = useTerminalDrawerSessions(threadRef.environmentId, threadRef.threadId); + const claimedIds = useRightPanelStore((state) => selectClaimedTerminalIds(state, threadRef)); + const observedSnapshotId = useRightPanelStore( + (state) => state.terminalServerObservationByThreadKey[scopedThreadKey(threadRef)]?.snapshotId, + ); + // Without read access the list never arrives, and the id may be live: Restart would replace + // it, so an unclaimed sub-tab stays pending rather than ended. + const serverIds = listing?.sessions.map((session) => session.target.terminalId) ?? null; + const mount = terminalSurfaceMount({ + terminalIds: surface.terminalIds, + serverIds, + claimedIds: currentTerminalClaims({ + claimedIds, + observedSnapshotId, + serverSnapshotId: listing?.snapshotId, + }), + }); + if (mount.kind === "mount") { + const { terminalIds } = mount; + return ( + + ); + } + if (mount.kind === "ended") return ; + return null; +}); + +function EndedTerminal(props: { threadRef: ScopedThreadRef; surface: TerminalPanelSurface }) { + const terminalActions = useThreadTerminalActions(props.threadRef); + const canOperate = useEnvironmentScope(props.threadRef.environmentId, AuthTerminalOperateScope); + const restart = () => { + for (const terminalId of props.surface.terminalIds) { + const launched = terminalActions.launchTerminal({ + terminalId, + place: (id) => useRightPanelStore.getState().openTerminal(props.threadRef, id), + }); + if (launched) void launched.result; + } + }; + // The server no longer has this terminal, so closing only forgets the sub-tab. + const close = () => useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id); + return ( +
+

+ This terminal has ended. +

+
+ + +
+
+ ); +} diff --git a/apps/web/src/components/RightPanelTerminalDrawer.tsx b/apps/web/src/components/RightPanelTerminalDrawer.tsx new file mode 100644 index 0000000000000..35644f586eac5 --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalDrawer.tsx @@ -0,0 +1,325 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { + ChevronDown, + ChevronRight, + Maximize2, + Minimize2, + Plus, + TerminalSquare, +} from "lucide-react"; +import { memo, useLayoutEffect, useRef, type PointerEvent as ReactPointerEvent } from "react"; + +import { Button } from "~/components/ui/button"; +import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; +import { cn } from "~/lib/utils"; +import { workspaceAreaProps } from "~/lib/workspaceFocus"; +import type { RightPanelSurface, TerminalPanelSurface } from "~/rightPanelStore"; +import { useKnownTerminalSessions } from "~/state/terminalSessions"; + +import type { TerminalBodyHost } from "./terminalBodyHosts"; +import { + clampTerminalDrawerHeight, + TERMINAL_DRAWER_COLLAPSED_HEIGHT, + TERMINAL_DRAWER_MIN_HEIGHT, + terminalDrawerStatus, + type TerminalDrawerStatus, +} from "./RightPanelTabs.logic"; + +export interface RightPanelTerminalDrawerProps { + threadRef: ScopedThreadRef; + surfaces: readonly TerminalPanelSurface[]; + activeSurfaceId: string | null; + open: boolean; + height: number; + maximized: boolean; + terminalAvailable: boolean; + /** Without operate access a close cannot end the session, so the server would list it again. */ + terminalClosable: boolean; + terminalLabelsById: ReadonlyMap; + /** The thread's terminals, rendered elsewhere so they outlive this drawer. */ + bodyHost: TerminalBodyHost | null; + onToggleOpen: () => void; + onHeightCommit: (height: number) => void; + onToggleMaximized: () => void; + onActivateSurface: (surfaceId: string) => void; + onCloseSurface: (surface: RightPanelSurface) => void; + onNewTerminal: () => void; +} + +const HEIGHT_PROPERTY = "--right-panel-terminal-height"; + +const STATUS_LABELS = { + running: msg("running", { $context: "a terminal command is still running" }), + ok: msg("ok", { $context: "a terminal command exited successfully" }), + failed: msg("failed", { $context: "a terminal command exited with an error" }), +} as const satisfies Record; + +/** Subscribes to terminal metadata alone, so output never re-renders the drawer or the tool. */ +const TerminalDrawerStatusText = memo(function TerminalDrawerStatusText(props: { + threadRef: ScopedThreadRef; + terminalId: string; +}) { + const messages = useMessages(); + const sessions = useKnownTerminalSessions({ + environmentId: props.threadRef.environmentId, + threadId: props.threadRef.threadId, + }); + const summary = + sessions?.find((session) => session.target.terminalId === props.terminalId)?.state.summary ?? + null; + const status = terminalDrawerStatus(summary); + if (status === null) return null; + return ( + + {status === "running" ? ( + + ) : null} + {messages(STATUS_LABELS[status])} + + ); +}); + +function terminalLabel(labels: ReadonlyMap, terminalId: string) { + return labels.get(terminalId) ?? getTerminalLabel(terminalId); +} + +export const RightPanelTerminalDrawer = memo(function RightPanelTerminalDrawer( + props: RightPanelTerminalDrawerProps, +) { + const gt = useGT(); + const drawerRef = useRef(null); + const dragRef = useRef<{ + pointerId: number; + startY: number; + startHeight: number; + containerHeight: number; + height: number; + } | null>(null); + const bodySlotRef = useRef(null); + const { bodyHost } = props; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves the thread's terminal host element into this drawer and back out, so the terminals never remount + useLayoutEffect(() => { + const slot = bodySlotRef.current; + if (!slot || !bodyHost) return; + bodyHost.place(slot); + return () => { + if (bodyHost.element.parentElement === slot) bodyHost.park(); + }; + }, [bodyHost]); + + const activeSurface = + props.surfaces.find((surface) => surface.id === props.activeSurfaceId) ?? + props.surfaces[0] ?? + null; + const activeLabel = activeSurface + ? terminalLabel(props.terminalLabelsById, activeSurface.activeTerminalId) + : null; + + const onResizePointerDown = (event: ReactPointerEvent) => { + const drawer = drawerRef.current; + if (!drawer || event.button !== 0) return; + event.preventDefault(); + event.currentTarget.setPointerCapture(event.pointerId); + const startHeight = drawer.getBoundingClientRect().height; + dragRef.current = { + pointerId: event.pointerId, + startY: event.clientY, + startHeight, + containerHeight: drawer.parentElement?.getBoundingClientRect().height ?? startHeight, + height: startHeight, + }; + }; + const onResizePointerMove = (event: ReactPointerEvent) => { + const drag = dragRef.current; + if (!drag || drag.pointerId !== event.pointerId) return; + drag.height = clampTerminalDrawerHeight( + drag.startHeight + (drag.startY - event.clientY), + drag.containerHeight, + ); + drawerRef.current?.style.setProperty(HEIGHT_PROPERTY, `${drag.height}px`); + }; + const onResizePointerEnd = (event: ReactPointerEvent) => { + const drag = dragRef.current; + if (!drag || drag.pointerId !== event.pointerId) return; + dragRef.current = null; + drawerRef.current?.style.removeProperty(HEIGHT_PROPERTY); + if (drag.height !== drag.startHeight) props.onHeightCommit(drag.height); + }; + + const terminalArea = props.open ? workspaceAreaProps("terminal", 5, gt("Terminal")) : {}; + + return ( +
+ {props.open && !props.maximized ? ( +
+ ) : null} + {props.open ? ( +
+
+ {props.surfaces.map((surface) => { + const label = terminalLabel(props.terminalLabelsById, surface.activeTerminalId); + const active = surface.id === activeSurface?.id; + return ( +
+ {props.terminalClosable ? ( + props.onCloseSurface(surface)} + > + + + ) : ( + + )} + +
+ ); + })} + + + +
+ + {props.maximized ? : } + + + + +
+ ) : ( + + )} + {/* One position for the body, so collapsing hides the terminal without remounting it. */} +
+
+ {activeSurface ? null : props.open ? ( +
+

+ No terminal +

+ +
+ ) : null} +
+
+ ); +}); + +function DrawerIconButton(props: { + label: string; + disabled?: boolean; + onClick: () => void; + children: React.ReactNode; +}) { + return ( + + + } + > + {props.children} + + {props.label} + + ); +} diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1c68dc7d9900b..0967a70ba57e7 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -25,8 +25,8 @@ import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; -import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { readLocalApi } from "../localApi"; +import { useRightPanelStore } from "../rightPanelStore"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -167,12 +167,12 @@ describe("sidebar render isolation", () => { routeThreadRef, }); const terminal = document.createElement("div"); - terminal.dataset.terminalOwner = "drawer"; + terminal.dataset.terminalOwner = "right-panel"; const terminalInput = document.createElement("textarea"); terminal.append(terminalInput); document.body.append(terminal); stack.defer(() => terminal.remove()); - stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false)); + stack.defer(() => useRightPanelStore.getState().setTerminalDrawerOpen(routeThreadRef, false)); await using screen = await render( @@ -185,7 +185,7 @@ describe("sidebar render isolation", () => { const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control"; const beforeShortcut = rowRenders(); await userEvent.keyboard(`{${modifier}>}`); - await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true)); + await act(() => useRightPanelStore.getState().openTerminal(routeThreadRef, "term-1")); await act(() => terminalInput.focus()); await userEvent.keyboard(`{/${modifier}}`); await act(() => terminalInput.blur()); diff --git a/apps/web/src/components/Sidebar.logic.browser.test.tsx b/apps/web/src/components/Sidebar.logic.browser.test.tsx index a323b5abdc094..8835775b8b9cd 100644 --- a/apps/web/src/components/Sidebar.logic.browser.test.tsx +++ b/apps/web/src/components/Sidebar.logic.browser.test.tsx @@ -5,7 +5,7 @@ import { userEvent } from "vite-plus/test/browser"; import { act, fakeTimers, render } from "../../test/render"; import { registerModelPickerContent } from "../modelPickerVisibility"; -import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { useRightPanelStore } from "../rightPanelStore"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS, useSnoozeWakeClock, @@ -81,15 +81,15 @@ describe("useThreadJumpHintsVisible", () => { await userEvent.keyboard(`{/${modifier}}`); }); - it("follows terminal focus and the route thread's terminal while the modifier is held", async () => { + it("terminalOpen context follows the right panel drawer, and terminal focus, while the modifier is held", async () => { using stack = new DisposableStack(); const terminal = document.createElement("div"); - terminal.dataset.terminalOwner = "drawer"; + terminal.dataset.terminalOwner = "right-panel"; const terminalInput = document.createElement("textarea"); terminal.append(terminalInput); document.body.append(terminal); stack.defer(() => terminal.remove()); - stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(ROUTE_THREAD_REF, false)); + stack.defer(() => useRightPanelStore.getState().setTerminalDrawerOpen(ROUTE_THREAD_REF, false)); const keybindings = compileResolvedKeybindingsConfig([ { key: "mod+1", command: "thread.jump.1", when: "terminalOpen" }, ]); @@ -104,7 +104,7 @@ describe("useThreadJumpHintsVisible", () => { await userEvent.keyboard(`{${modifier}>}`); await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS)); await expect.element(output).toHaveTextContent("hidden"); - await act(() => useTerminalUiStateStore.getState().setTerminalOpen(ROUTE_THREAD_REF, true)); + await act(() => useRightPanelStore.getState().openTerminal(ROUTE_THREAD_REF, "term-1")); await expect.element(output).toHaveTextContent("shown"); await act(() => terminalInput.focus()); await expect.element(output).toHaveTextContent("hidden"); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index aadec8ae7bb2c..ec88a24965af5 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -58,8 +58,11 @@ import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/termi import { isPreviewFocused } from "../lib/previewFocus"; import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility"; import { shortcutModifierStore } from "../shortcutModifierState"; -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; +import { + selectActiveRightPanel, + selectTerminalDrawerVisible, + useRightPanelStore, +} from "../rightPanelStore"; export function shouldNavigateAfterThreadPark(input: { readonly threadKey: string; @@ -669,10 +672,7 @@ export function threadShortcutContext(routeThreadRef: ScopedThreadRef | null) { terminalFocus: isTerminalFocused(), terminalOpen: routeThreadRef !== null && - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - routeThreadRef, - ).terminalOpen, + selectTerminalDrawerVisible(useRightPanelStore.getState(), routeThreadRef), previewFocus: isPreviewFocused(), previewOpen: selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) === @@ -731,14 +731,12 @@ function subscribeToThreadJumpHintInputs(listener: () => void): () => void { // The snapshot reads the modifiers; the hold stays silent when it is true across a change. const unsubscribeModifiers = shortcutModifierStore.subscribe(listener); const unsubscribeFocus = subscribeToTerminalFocusChanges(listener); - const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener); const unsubscribeRightPanels = useRightPanelStore.subscribe(listener); const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener); return () => { unsubscribeHold(); unsubscribeModifiers(); unsubscribeFocus(); - unsubscribeTerminals(); unsubscribeRightPanels(); unsubscribeModelPicker(); }; diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index 7632d01b5f907..1ade04570b319 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -15,7 +15,6 @@ import { Atom, AsyncResult } from "effect/reactivity"; import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface"; import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry"; import { useRightPanelStore } from "../rightPanelStore"; -import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { extractTerminalLinks } from "../terminal-links"; import { expect, it, vi } from "vite-plus/test"; import { act, fakeTimers, render } from "../../test/render"; @@ -224,7 +223,6 @@ function Drawer(props: { threadRef={props.threadRef} threadId={props.threadRef.threadId} cwd={props.cwd ?? "/repo"} - height={240} terminalIds={["term-1"]} activeTerminalId="term-1" terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]} @@ -234,7 +232,6 @@ function Drawer(props: { onNewTerminal={() => {}} onActiveTerminalChange={() => {}} onCloseTerminal={props.onCloseTerminal} - onHeightChange={() => {}} onAddTerminalContext={() => {}} keybindings={props.keybindings ?? []} /> @@ -266,7 +263,6 @@ function setup(originalStatus: "starting" | "exited" = "exited") { fixture.runWrite = () => Promise.resolve({ _tag: "Success" }); fixture.metadata.clear(); useRightPanelStore.setState(useRightPanelStore.getInitialState()); - useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); return { original, other }; } diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 54ae776e18559..7b4612c6cdfa1 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,5 +1,4 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; -import { workspaceAreaProps } from "../lib/workspaceFocus"; import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { msg, T, useGT, useMessages } from "gt-react"; import { m } from "../i18n/messages"; @@ -38,7 +37,6 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { - type PointerEvent as ReactPointerEvent, type ReactNode, useEffect, useContext, @@ -72,11 +70,7 @@ import { terminalDeleteShortcutData, terminalNavigationShortcutData, } from "../keybindings"; -import { - DEFAULT_THREAD_TERMINAL_HEIGHT, - MAX_TERMINALS_PER_GROUP, - type ThreadTerminalGroup, -} from "../types"; +import { MAX_TERMINALS_PER_GROUP, type ThreadTerminalGroup } from "../types"; import { readLocalApi } from "~/localApi"; import { confirmTerminalClose } from "~/lib/terminalCloseConfirm"; import { useClientSettings } from "../hooks/useSettings"; @@ -94,7 +88,6 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview"; import { terminalInputWriter } from "./terminal/terminalInputWriter"; import { useAtomCommand } from "../state/use-atom-command"; import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; -import { observeResize } from "../lib/observeResize"; import { threadShortcutContext } from "./Sidebar.logic"; import { consumePendingTerminalFocus, @@ -108,51 +101,6 @@ import { TYPOGRAPHY_ADVANCED_STORAGE_KEY, } from "../appearanceFonts"; -const MIN_DRAWER_HEIGHT = 180; -const MAX_DRAWER_HEIGHT_RATIO = 0.75; - -interface DrawerLayout { - viewportHeight: number; - chatColumnHeight?: number; - headerHeight?: number; - composerHeight?: number; -} - -function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number { - const windowCap = Math.max( - MIN_DRAWER_HEIGHT, - Math.floor(input.viewportHeight * MAX_DRAWER_HEIGHT_RATIO), - ); - if (input.chatColumnHeight === undefined) return windowCap; - // The composer overlays the timeline, so flex layout cannot reserve its - // height; without this cap a tall drawer pushes it into the header. - return Math.min( - windowCap, - Math.max(0, input.chatColumnHeight - (input.headerHeight ?? 0) - (input.composerHeight ?? 0)), - ); -} - -const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height"; - -function clampDrawerHeight(height: number, maxHeight: number): number { - const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT; - return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight); -} - -function chatColumnOf(drawer: HTMLElement | null): HTMLElement | null { - return drawer?.closest("[data-chat-column]") ?? null; -} - -function readDrawerLayout(column: HTMLElement | null): Omit { - const viewportHeight = typeof window === "undefined" ? 0 : window.innerHeight; - if (!column) return { viewportHeight }; - return { - viewportHeight, - chatColumnHeight: column.clientHeight, - headerHeight: column.querySelector("[data-chat-header]")?.offsetHeight ?? 0, - }; -} - function writeSystemMessage( terminal: Pick, message: string, @@ -1223,16 +1171,12 @@ function TerminalSessionViewport({ } interface ThreadTerminalDrawerProps { - mode?: "drawer" | "panel"; threadRef: ScopedThreadRef; threadId: ThreadId; cwd: string; worktreePath?: string | null; runtimeEnv?: Record; visible?: boolean; - height: number; - /** Space the chat column keeps for the composer overlay; only read in drawer mode. */ - composerHeight?: number; terminalIds: string[]; activeTerminalId: string; terminalGroups: ThreadTerminalGroup[]; @@ -1246,7 +1190,6 @@ interface ThreadTerminalDrawerProps { closeShortcutLabel?: string | undefined; onActiveTerminalChange: (terminalId: string) => void; onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; - onHeightChange: (height: number) => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; keybindings: ResolvedKeybindingsConfig; terminalLabelsById?: ReadonlyMap; @@ -1486,15 +1429,12 @@ function TerminalSidebarGroup({ } export default function ThreadTerminalDrawer({ - mode = "drawer", threadRef, threadId, cwd, worktreePath, runtimeEnv, visible = true, - height, - composerHeight = 0, terminalIds, activeTerminalId, terminalGroups, @@ -1508,7 +1448,6 @@ export default function ThreadTerminalDrawer({ closeShortcutLabel, onActiveTerminalChange, onCloseTerminal, - onHeightChange, onAddTerminalContext, keybindings, terminalLabelsById, @@ -1517,27 +1456,11 @@ export default function ThreadTerminalDrawer({ const gt = useGT(); const messages = useMessages(); const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); - const terminalArea = workspaceAreaProps("terminal", 5, gt("Terminal")); - const isPanel = mode === "panel"; const [advancedTypography] = useLocalStorage( TYPOGRAPHY_ADVANCED_STORAGE_KEY, false, Schema.Boolean, ); - const drawerRef = useRef(null); - const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null)); - const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight }); - const drawerHeight = clampDrawerHeight(height, maxDrawerHeight); - // A drag only writes the drawer's style; the store hears the height once, at - // pointerup. The custom property outranks the rendered height while it is set. - const resizeStateRef = useRef<{ - pointerId: number; - startY: number; - startHeight: number; - height: number; - drawer: HTMLElement | null; - } | null>(null); - const normalizedTerminalIds = (() => { const normalizedIds: string[] = []; const seen = new Set(); @@ -1709,123 +1632,13 @@ export default function ThreadTerminalDrawer({ }); }; - const handleResizePointerDown = (event: ReactPointerEvent) => { - if (event.button !== 0) return; - event.preventDefault(); - event.currentTarget.setPointerCapture(event.pointerId); - resizeStateRef.current = { - pointerId: event.pointerId, - startY: event.clientY, - startHeight: drawerHeight, - height: drawerHeight, - drawer: event.currentTarget.parentElement, - }; - }; - - const handleResizePointerMove = (event: ReactPointerEvent) => { - const resizeState = resizeStateRef.current; - if (!resizeState || resizeState.pointerId !== event.pointerId) return; - event.preventDefault(); - const clampedHeight = clampDrawerHeight( - resizeState.startHeight + (resizeState.startY - event.clientY), - maxDrawerHeight, - ); - if (clampedHeight === resizeState.height) { - return; - } - resizeState.height = clampedHeight; - resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`); - }; - - const handleResizePointerEnd = (event: ReactPointerEvent) => { - const resizeState = resizeStateRef.current; - if (!resizeState || resizeState.pointerId !== event.pointerId) return; - resizeStateRef.current = null; - if (event.currentTarget.hasPointerCapture(event.pointerId)) { - event.currentTarget.releasePointerCapture(event.pointerId); - } - resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY); - // A drag that ends where it started keeps the stored preference, which may - // be taller than the capped height the drag started from. - if (resizeState.height === resizeState.startHeight || resizeState.height === height) return; - onHeightChange(resizeState.height); - }; - - const drawerLayoutRef = useRef(drawerLayout); - const updateDrawerLayout = useEffectEvent( - (column: HTMLElement | null, source: "window" | "column") => { - const layout = readDrawerLayout(column); - const previous = drawerLayoutRef.current; - const heightBudgetChanged = - layout.viewportHeight !== previous.viewportHeight || - layout.chatColumnHeight !== previous.chatColumnHeight || - layout.headerHeight !== previous.headerHeight; - // The column also reports width-only changes, such as every frame of a - // right panel drag; the surface refits itself for those. - if (!heightBudgetChanged && source === "column") return; - drawerLayoutRef.current = layout; - const resizeState = resizeStateRef.current; - if (resizeState) { - const liveHeight = clampDrawerHeight( - resizeState.height, - resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }), - ); - if (liveHeight !== resizeState.height) { - resizeState.height = liveHeight; - resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`); - } - } - if (heightBudgetChanged) setDrawerLayout(layout); - }, - ); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the drawer before visible paint and observes window and chat column resizes while visible - useLayoutEffect(() => { - if (!visible) { - return; - } - // The column and window may have resized while the drawer was hidden and - // not listening, so measure before the first visible paint. - const column = isPanel ? null : chatColumnOf(drawerRef.current); - const onWindowResize = () => updateDrawerLayout(column, "window"); - onWindowResize(); - const header = column?.querySelector("[data-chat-header]"); - const stopObserving = column - ? observeResize(header ? [column, header] : column, () => - updateDrawerLayout(column, "column"), - ) - : undefined; - window.addEventListener("resize", onWindowResize); - return () => { - stopObserving?.(); - window.removeEventListener("resize", onWindowResize); - }; - }, [isPanel, visible]); - - const resizeHandle = isPanel ? null : ( -
- ); - if (normalizedTerminalIds.length === 0) { return (