From b0fa60a121bd55f88c2432b1e29ec694c3d76863 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 4 Jun 2026 14:31:24 -0700 Subject: [PATCH 1/7] Prevent settings layout shifts with scrollbar gutters (#2960) --- apps/web/src/components/settings/settingsLayout.tsx | 2 +- apps/web/src/components/ui/scroll-area.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index 391898b111..a825463b3e 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -127,7 +127,7 @@ export function SettingsPageContainer({ className?: string; }) { return ( -
+
{children}
diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx index f9a3638675..d6f178a1f5 100644 --- a/apps/web/src/components/ui/scroll-area.tsx +++ b/apps/web/src/components/ui/scroll-area.tsx @@ -29,7 +29,7 @@ function ScrollArea({ chainVerticalScroll && "overscroll-y-auto", scrollFade && "mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]", - scrollbarGutter && "[scrollbar-gutter:stable]", + scrollbarGutter && "scrollbar-gutter-stable", hideScrollbars && "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden", )} From dfdb5a46db30fb46db5c58d5fe047b32483e2ad5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 4 Jun 2026 14:57:43 -0700 Subject: [PATCH 2/7] [codex] fix release finalize install (#2961) Co-authored-by: Julius Marminge --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 603aac30e4..f8d1d2efe8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -705,6 +705,7 @@ jobs: run-install: | args: - --filter=@t3tools/scripts... + - --filter=@t3tools/oxlint-plugin-t3code... - id: update_versions name: Update version strings From 49c1b64687f8acdbe145f760988314e397170da6 Mon Sep 17 00:00:00 2001 From: Guilherme Vieira <46866023+GuilhermeVieiraDev@users.noreply.github.com> Date: Thu, 4 Jun 2026 23:13:04 +0100 Subject: [PATCH 3/7] fix(source-control): handle self-hosted GitLab, multi-account GitHub auth & azure devops web url (#2480) Co-authored-by: Julius Marminge --- .../src/sourceControl/AzureDevOpsCli.test.ts | 38 ++++ .../GitHubSourceControlProvider.test.ts | 188 +++++++++++++++++- .../GitHubSourceControlProvider.ts | 34 +++- .../GitLabSourceControlProvider.test.ts | 72 +++++++ .../GitLabSourceControlProvider.ts | 44 +++- .../SourceControlDiscovery.test.ts | 48 +++-- .../SourceControlProviderDiscovery.ts | 62 ++++++ .../SourceControlProviderRegistry.test.ts | 73 ++++++- .../SourceControlProviderRegistry.ts | 8 +- .../sourceControl/azureDevOpsPullRequests.ts | 74 ++++++- .../src/sourceControl/gitHubAuthStatus.ts | 72 +++++++ .../src/sourceControl/gitLabAuthStatus.ts | 48 +++++ packages/shared/src/sourceControl.test.ts | 19 ++ packages/shared/src/sourceControl.ts | 25 ++- 14 files changed, 757 insertions(+), 48 deletions(-) create mode 100644 apps/server/src/sourceControl/gitHubAuthStatus.ts create mode 100644 apps/server/src/sourceControl/gitLabAuthStatus.ts diff --git a/apps/server/src/sourceControl/AzureDevOpsCli.test.ts b/apps/server/src/sourceControl/AzureDevOpsCli.test.ts index 6958f42fb1..f3078fcd06 100644 --- a/apps/server/src/sourceControl/AzureDevOpsCli.test.ts +++ b/apps/server/src/sourceControl/AzureDevOpsCli.test.ts @@ -64,6 +64,7 @@ describe("AzureDevOpsCli.layer", () => { assert.strictEqual(result.number, 42); assert.strictEqual(result.title, "Add Azure provider"); + assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42"); assert.strictEqual(result.baseRefName, "main"); assert.strictEqual(result.headRefName, "feature/source-control"); assert.strictEqual(result.state, "open"); @@ -89,6 +90,43 @@ describe("AzureDevOpsCli.layer", () => { }).pipe(Effect.provide(layer)), ); + it.effect("builds a web URL when Azure returns only the pull request REST URL", () => + Effect.gen(function* () { + mockRun.mockReturnValueOnce( + Effect.succeed( + processOutput( + // @effect-diagnostics-next-line preferSchemaOverJson:off + JSON.stringify({ + pullRequestId: 863, + title: "Fix Azure link", + url: "https://dev.azure.com/saplyai/a8fe4088-ad76-4eda-aaaa-e3329713a097/_apis/git/repositories/16108a25-93a3-4eff-b77d-85e894ee0fe4/pullRequests/863", + repository: { + name: "CV-engine", + project: { + name: "CV-engine", + }, + }, + sourceRefName: "refs/heads/feature/azure-pr-link", + targetRefName: "refs/heads/main", + status: "active", + }), + ), + ), + ); + + const az = yield* AzureDevOpsCli.AzureDevOpsCli; + const result = yield* az.getPullRequest({ + cwd: "/repo", + reference: "863", + }); + + assert.strictEqual( + result.url, + "https://dev.azure.com/saplyai/CV-engine/_git/CV-engine/pullrequest/863", + ); + }).pipe(Effect.provide(layer)), + ); + it.effect("lists pull requests with Azure status and source branch arguments", () => Effect.gen(function* () { mockRun.mockReturnValueOnce( diff --git a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts index a480f3bec8..32fd1a91ce 100644 --- a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts +++ b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts @@ -7,12 +7,19 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as GitHubCli from "./GitHubCli.ts"; +import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts"; import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts"; -const processResult = (stdout: string): VcsProcess.VcsProcessOutput => ({ - exitCode: ChildProcessSpawner.ExitCode(0), +const processResult = ( + stdout: string, + options?: { + readonly stderr?: string; + readonly exitCode?: ChildProcessSpawner.ExitCode; + }, +): VcsProcess.VcsProcessOutput => ({ + exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0), stdout, - stderr: "", + stderr: options?.stderr ?? "", stdoutTruncated: false, stderrTruncated: false, }); @@ -157,3 +164,178 @@ it.effect("creates GitHub PRs through provider-neutral input names", () => }); }), ); + +it("accepts active authenticated GitHub accounts when another account fails", () => { + const auth = GitHubSourceControlProvider.discovery.parseAuth( + processResult( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "success", + active: true, + host: "github.com", + login: "active-user", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + { + state: "error", + active: false, + host: "github.com", + login: "stale-user", + tokenSource: "keyring", + gitProtocol: "ssh", + error: "The token in keyring is invalid.", + }, + ], + }, + }), + ), + ); + + assert.deepStrictEqual( + { + status: auth.status, + account: auth.account, + host: auth.host, + }, + { + status: "authenticated", + account: Option.some("active-user"), + host: Option.some("github.com"), + }, + ); +}); + +it("parses GitHub auth JSON from stdout when stderr has warnings", () => { + const auth = GitHubSourceControlProvider.discovery.parseAuth( + processResult( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "success", + active: true, + host: "github.com", + login: "active-user", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + ], + }, + }), + { stderr: "warning: ignored diagnostic from gh\n" }, + ), + ); + + assert.deepStrictEqual( + { + status: auth.status, + account: auth.account, + host: auth.host, + }, + { + status: "authenticated", + account: Option.some("active-user"), + host: Option.some("github.com"), + }, + ); +}); + +it("parses GitHub auth status accounts by host and active state", () => { + assert.deepStrictEqual( + parseGitHubAuthStatus( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "success", + active: true, + host: "github.com", + login: "active-user", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + { + state: "error", + active: false, + host: "github.com", + login: "stale-user", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + ], + "github.example.test": [ + { + state: "success", + active: false, + host: "github.example.test", + login: "enterprise-user", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + ], + }, + }), + ).accounts, + [ + { + host: "github.com", + account: "active-user", + authenticated: true, + active: true, + error: null, + }, + { + host: "github.com", + account: "stale-user", + authenticated: false, + active: false, + error: null, + }, + { + host: "github.example.test", + account: "enterprise-user", + authenticated: true, + active: false, + error: null, + }, + ], + ); +}); + +it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => { + const auth = GitHubSourceControlProvider.discovery.parseAuth( + processResult( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "error", + active: true, + host: "github.com", + login: "stale-user", + tokenSource: "keyring", + gitProtocol: "ssh", + error: "The token in keyring is invalid.", + }, + ], + }, + }), + ), + ); + + assert.deepStrictEqual( + { + status: auth.status, + host: auth.host, + detail: auth.detail, + }, + { + status: "unauthenticated", + host: Option.some("github.com"), + detail: Option.some("The token in keyring is invalid."), + }, + ); +}); diff --git a/apps/server/src/sourceControl/GitHubSourceControlProvider.ts b/apps/server/src/sourceControl/GitHubSourceControlProvider.ts index cc892015fc..41329b97f7 100644 --- a/apps/server/src/sourceControl/GitHubSourceControlProvider.ts +++ b/apps/server/src/sourceControl/GitHubSourceControlProvider.ts @@ -10,6 +10,7 @@ import { } from "@t3tools/contracts"; import * as GitHubCli from "./GitHubCli.ts"; +import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts"; import * as GitHubPullRequests from "./gitHubPullRequests.ts"; import * as SourceControlProvider from "./SourceControlProvider.ts"; import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts"; @@ -51,11 +52,28 @@ function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeReq function parseGitHubAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) { const output = SourceControlProviderDiscovery.combinedAuthOutput(input); - const account = SourceControlProviderDiscovery.matchFirst(output, [ - /Logged in to .* account\s+([^\s(]+)/iu, - /Logged in to .* as\s+([^\s(]+)/iu, - ]); - const host = SourceControlProviderDiscovery.parseCliHost(output); + const authStatus = parseGitHubAuthStatus(input.stdout); + const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts); + const host = authenticatedAccount?.host; + + if (authenticatedAccount) { + return SourceControlProviderDiscovery.providerAuth({ + status: "authenticated", + account: authenticatedAccount.account, + host, + }); + } + + const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0]; + if (authStatus.parsed) { + return SourceControlProviderDiscovery.providerAuth({ + status: "unauthenticated", + host: failedAccount?.host, + detail: + failedAccount?.error ?? + "Run `gh auth login` to authenticate GitHub CLI with an active account.", + }); + } if (input.exitCode !== 0) { return SourceControlProviderDiscovery.providerAuth({ @@ -67,10 +85,6 @@ function parseGitHubAuth(input: SourceControlProviderDiscovery.SourceControlAuth }); } - if (account) { - return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host }); - } - return SourceControlProviderDiscovery.providerAuth({ status: "unknown", host, @@ -86,7 +100,7 @@ export const discovery = { label: "GitHub", executable: "gh", versionArgs: ["--version"], - authArgs: ["auth", "status"], + authArgs: ["auth", "status", "--json", "hosts"], parseAuth: parseGitHubAuth, installHint: "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).", diff --git a/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts b/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts index 94d363d1c1..842cf4a17c 100644 --- a/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts +++ b/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts @@ -2,8 +2,10 @@ import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import { ChildProcessSpawner } from "effect/unstable/process"; import * as GitLabCli from "./GitLabCli.ts"; +import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts"; import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts"; function makeProvider(gitlab: Partial) { @@ -107,3 +109,73 @@ it.effect("creates GitLab MRs through provider-neutral input names", () => }); }), ); + +it("accepts authenticated GitLab hosts when another configured host fails", () => { + const auth = GitLabSourceControlProvider.discovery.parseAuth({ + exitCode: ChildProcessSpawner.ExitCode(1), + stdout: `gitlab.com + x gitlab.com: API call failed: 401 Unauthorized + ! No token found +self-hosted.example.test + ✓ Logged in to self-hosted.example.test as gitlab-user + ✓ Token found: ****** +`, + stderr: "", + }); + + assert.deepStrictEqual( + { + status: auth.status, + account: auth.account, + host: auth.host, + }, + { + status: "authenticated", + account: Option.some("gitlab-user"), + host: Option.some("self-hosted.example.test"), + }, + ); +}); + +it("refines unknown GitLab remotes with mixed-case provider hosts", () => { + const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({ + cwd: "/repo", + context: { + provider: { + kind: "unknown", + name: "Self-Hosted.Example.Test", + baseUrl: "https://Self-Hosted.Example.Test", + }, + remoteName: "origin", + remoteUrl: "https://Self-Hosted.Example.Test/group/project.git", + }, + auth: { + exitCode: ChildProcessSpawner.ExitCode(0), + stdout: `self-hosted.example.test + ✓ Logged in to self-hosted.example.test as gitlab-user + ✓ Token found: ****** +`, + stderr: "", + }, + }); + + assert.deepStrictEqual(provider, { + kind: "gitlab", + name: "GitLab Self-Hosted", + baseUrl: "https://Self-Hosted.Example.Test", + }); +}); + +it("parses authenticated GitLab auth status hosts with ports and single-label names", () => { + assert.deepStrictEqual( + parseGitLabAuthStatusHosts(`localhost:8080 + ✓ Logged in to localhost:8080 as local-user +selfhosted + ✓ Logged in to selfhosted as single-label-user +`), + [ + { host: "localhost:8080", account: "local-user" }, + { host: "selfhosted", account: "single-label-user" }, + ], + ); +}); diff --git a/apps/server/src/sourceControl/GitLabSourceControlProvider.ts b/apps/server/src/sourceControl/GitLabSourceControlProvider.ts index ccab2bd1f7..77f41600e0 100644 --- a/apps/server/src/sourceControl/GitLabSourceControlProvider.ts +++ b/apps/server/src/sourceControl/GitLabSourceControlProvider.ts @@ -6,6 +6,7 @@ import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contrac import * as GitLabCli from "./GitLabCli.ts"; import * as SourceControlProvider from "./SourceControlProvider.ts"; import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts"; +import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts"; function providerError( operation: string, @@ -43,12 +44,19 @@ function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRe function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) { const output = SourceControlProviderDiscovery.combinedAuthOutput(input); - const account = SourceControlProviderDiscovery.matchFirst(output, [ - /Logged in to .* as\s+([^\s(]+)/iu, - /Logged in to .* account\s+([^\s(]+)/iu, - /account:\s*([^\s(]+)/iu, - ]); - const host = SourceControlProviderDiscovery.parseCliHost(output); + const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output)); + const account = + authenticatedHost?.account ?? + SourceControlProviderDiscovery.matchFirst(output, [ + /Logged in to .* as\s+([^\s(]+)/iu, + /Logged in to .* account\s+([^\s(]+)/iu, + /account:\s*([^\s(]+)/iu, + ]); + const host = authenticatedHost?.host ?? SourceControlProviderDiscovery.parseCliHost(output); + + if (account) { + return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host }); + } if (input.exitCode !== 0) { return SourceControlProviderDiscovery.providerAuth({ @@ -60,10 +68,6 @@ function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuth }); } - if (account) { - return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host }); - } - return SourceControlProviderDiscovery.providerAuth({ status: "unknown", host, @@ -73,6 +77,25 @@ function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuth }); } +function refineUnknownGitLabRemote( + input: SourceControlProviderDiscovery.SourceControlUnknownRemoteRefinementInput, +) { + const host = input.context.provider.name.toLowerCase(); + const authenticated = parseGitLabAuthStatusHosts( + SourceControlProviderDiscovery.combinedAuthOutput(input.auth), + ).some((entry) => entry.account !== null && entry.host === host); + + if (!authenticated) { + return null; + } + + return { + kind: "gitlab", + name: "GitLab Self-Hosted", + baseUrl: input.context.provider.baseUrl, + } as const; +} + export const discovery = { type: "cli", kind: "gitlab", @@ -81,6 +104,7 @@ export const discovery = { versionArgs: ["--version"], authArgs: ["auth", "status"], parseAuth: parseGitLabAuth, + refineUnknownRemote: refineUnknownGitLabRemote, installHint: "Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).", } satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec; diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts index d1c6c65c75..f65710c4c9 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts @@ -59,15 +59,24 @@ it.effect("reports implemented tools separately from locally available executabl if (input.command === "gh" && input.args[0] === "--version") { return Effect.succeed(processOutput("gh version 2.83.0\n")); } - if (input.command === "gh" && input.args.join(" ") === "auth status") { + if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") { return Effect.succeed( - processOutput(`github.com -Logged in to github.com account juliusmarminge (keyring) -- Active account: true -- Git operations protocol: ssh -- Token: gho_************************************ -- Token scopes: 'admin:public_key', 'gist', 'read:org', 'repo' -`), + processOutput( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "success", + active: true, + host: "github.com", + login: "juliusmarminge", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + ], + }, + }), + ), ); } return Effect.fail( @@ -164,13 +173,24 @@ it.effect("probes provider authentication without exposing token details", () => if (input.args[0] === "--version") { return Effect.succeed(processOutput(`${input.command} version test\n`)); } - if (input.command === "gh" && input.args.join(" ") === "auth status") { + if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") { return Effect.succeed( - processOutput(`github.com -Logged in to github.com account octocat (keyring) -- Token: gho_************************************ -- Token scopes: 'repo' -`), + processOutput( + JSON.stringify({ + hosts: { + "github.com": [ + { + state: "success", + active: true, + host: "github.com", + login: "octocat", + tokenSource: "keyring", + gitProtocol: "ssh", + }, + ], + }, + }), + ), ); } if (input.command === "glab" && input.args.join(" ") === "auth status") { diff --git a/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts b/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts index b42cb853a5..c5ab091ac4 100644 --- a/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts +++ b/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts @@ -1,11 +1,13 @@ import type { SourceControlProviderAuth, SourceControlProviderDiscoveryItem, + SourceControlProviderInfo, SourceControlProviderKind, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import type * as SourceControlProvider from "./SourceControlProvider.ts"; import type * as VcsProcess from "../vcs/VcsProcess.ts"; export interface SourceControlAuthProbeInput { @@ -14,6 +16,12 @@ export interface SourceControlAuthProbeInput { readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"]; } +export interface SourceControlUnknownRemoteRefinementInput { + readonly cwd: string; + readonly context: SourceControlProvider.SourceControlProviderContext; + readonly auth: SourceControlAuthProbeInput; +} + interface SourceControlDiscoverySpecBase { readonly kind: SourceControlProviderKind; readonly label: string; @@ -26,6 +34,9 @@ export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & { readonly versionArgs: ReadonlyArray; readonly authArgs: ReadonlyArray; readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth; + readonly refineUnknownRemote?: ( + input: SourceControlUnknownRemoteRefinementInput, + ) => SourceControlProviderInfo | null; }; export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & { @@ -37,6 +48,10 @@ export type SourceControlProviderDiscoverySpec = | SourceControlCliDiscoverySpec | SourceControlApiDiscoverySpec; +type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & { + readonly refineUnknownRemote: NonNullable; +}; + interface DiscoveryProbeResult { readonly kind: SourceControlProviderKind; readonly label: string; @@ -135,6 +150,12 @@ export function matchFirst(text: string, patterns: ReadonlyArray): strin return undefined; } +function isCliRemoteRefinementSpec( + spec: SourceControlProviderDiscoverySpec, +): spec is SourceControlCliRemoteRefinementSpec { + return spec.type === "cli" && spec.refineUnknownRemote !== undefined; +} + function probeCli(input: { readonly spec: SourceControlCliDiscoverySpec; readonly process: VcsProcess.VcsProcessShape; @@ -245,3 +266,44 @@ export function probeSourceControlProvider(input: { }), ); } + +export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")( + function* (input: { + readonly specs: ReadonlyArray; + readonly process: VcsProcess.VcsProcessShape; + readonly cwd: string; + readonly context: SourceControlProvider.SourceControlProviderContext | null; + }): Effect.fn.Return { + if (input.context === null || input.context.provider.kind !== "unknown") { + return input.context; + } + const context = input.context; + + const providers = yield* Effect.forEach(input.specs.filter(isCliRemoteRefinementSpec), (spec) => + input.process + .run({ + operation: "source-control.discovery.refine-unknown-remote", + command: spec.executable, + args: spec.authArgs, + cwd: input.cwd, + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 8_000, + appendTruncationMarker: true, + }) + .pipe( + Effect.map((auth) => + spec.refineUnknownRemote({ + cwd: input.cwd, + context, + auth, + }), + ), + Effect.catch(() => Effect.succeed(null)), + ), + ); + const provider = providers.find((candidate) => candidate !== null); + + return provider ? { ...context, provider } : context; + }, +); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index 829f6be1eb..833956ecc7 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -4,6 +4,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import { ChildProcessSpawner } from "effect/unstable/process"; import { ServerConfig } from "../config.ts"; import type * as VcsDriver from "../vcs/VcsDriver.ts"; @@ -17,11 +18,26 @@ import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry. const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); +const processOutput = ( + stdout: string, + options?: { + readonly stderr?: string; + readonly exitCode?: ChildProcessSpawner.ExitCode; + }, +): VcsProcess.VcsProcessOutput => ({ + exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0), + stdout, + stderr: options?.stderr ?? "", + stdoutTruncated: false, + stderrTruncated: false, +}); + function makeRegistry(input: { readonly remotes: ReadonlyArray<{ readonly name: string; readonly url: string; }>; + readonly process?: Partial; }) { const driver = { listRemotes: () => @@ -58,15 +74,20 @@ function makeRegistry(input: { }), }); + const processLayer = Layer.mock(VcsProcess.VcsProcess)({ + run: () => Effect.succeed(processOutput("")), + ...input.process, + }); + return SourceControlProviderRegistry.make().pipe( Effect.provide( Layer.mergeAll( registryLayer, + processLayer, Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}), Layer.mock(BitbucketApi.BitbucketApi)({}), Layer.mock(GitHubCli.GitHubCli)({}), Layer.mock(GitLabCli.GitLabCli)({}), - Layer.mock(VcsProcess.VcsProcess)({}), ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-" }).pipe( Layer.provide(NodeServices.layer), ), @@ -111,6 +132,56 @@ it.effect("routes GitLab remotes to the GitLab provider", () => }), ); +it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () => + Effect.gen(function* () { + const registry = yield* makeRegistry({ + remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }], + process: { + run: () => + Effect.succeed( + processOutput( + `gitlab.com + x gitlab.com: API call failed: 401 Unauthorized + ! No token found +self-hosted.example.test + ✓ Logged in to self-hosted.example.test as gitlab-user + ✓ Token found: ****** +`, + { exitCode: ChildProcessSpawner.ExitCode(1) }, + ), + ), + }, + }); + + const provider = yield* registry.resolve({ cwd: "/repo" }); + + assert.strictEqual(provider.kind, "gitlab"); + }), +); + +it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () => + Effect.gen(function* () { + const registry = yield* makeRegistry({ + remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }], + process: { + run: () => + Effect.succeed( + processOutput( + `self-hosted.example.test:8443 + ✓ Logged in to self-hosted.example.test:8443 as gitlab-user + ✓ Token found: ****** +`, + ), + ), + }, + }); + + const provider = yield* registry.resolve({ cwd: "/repo" }); + + assert.strictEqual(provider.kind, "gitlab"); + }), +); + it.effect("routes Bitbucket remotes to the Bitbucket provider", () => Effect.gen(function* () { const registry = yield* makeRegistry({ diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index b927d8c77b..08f794d1f5 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -178,8 +178,14 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit const remotes = yield* handle.driver .listRemotes(cwd) .pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error))); + const context = selectProviderContext(remotes.remotes); - return selectProviderContext(remotes.remotes); + return yield* SourceControlProviderDiscovery.refineUnknownRemoteProvider({ + specs: discoverySpecs, + process, + cwd, + context, + }); }, ); diff --git a/apps/server/src/sourceControl/azureDevOpsPullRequests.ts b/apps/server/src/sourceControl/azureDevOpsPullRequests.ts index e8f138e0e3..c059f6f0f9 100644 --- a/apps/server/src/sourceControl/azureDevOpsPullRequests.ts +++ b/apps/server/src/sourceControl/azureDevOpsPullRequests.ts @@ -21,6 +21,17 @@ const AzureDevOpsPullRequestSchema = Schema.Struct({ pullRequestId: PositiveInt, title: TrimmedNonEmptyString, url: Schema.optional(Schema.String), + repository: Schema.optional( + Schema.Struct({ + name: Schema.optional(Schema.String), + webUrl: Schema.optional(Schema.String), + project: Schema.optional( + Schema.Struct({ + name: Schema.optional(Schema.String), + }), + ), + }), + ), sourceRefName: TrimmedNonEmptyString, targetRefName: TrimmedNonEmptyString, status: Schema.String, @@ -57,13 +68,74 @@ function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" } } +function encodeAzureDevOpsPathSegment(segment: string): string { + return encodeURIComponent(segment); +} + +function azureDevOpsOrganizationBaseFromRestApiUrl( + value: string | null | undefined, +): string | null { + const rawUrl = trimOptionalString(value); + if (!rawUrl) { + return null; + } + + try { + const url = new URL(rawUrl); + const hostname = url.hostname.toLowerCase(); + const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0); + const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis"); + if (!isAzureRestUrl) { + return null; + } + + if (hostname === "dev.azure.com") { + const organization = pathSegments[0]; + return organization ? `${url.origin}/${organization}` : null; + } + + if (hostname.endsWith(".visualstudio.com")) { + return url.origin; + } + + return null; + } catch { + return null; + } +} + +function normalizeAzureDevOpsPullRequestUrl( + raw: Schema.Schema.Type, +): string { + const webLink = trimOptionalString(raw._links?.web?.href); + if (webLink) { + return webLink; + } + + const repositoryWebUrl = trimOptionalString(raw.repository?.webUrl); + if (repositoryWebUrl) { + return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${raw.pullRequestId}`; + } + + const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url); + const projectName = trimOptionalString(raw.repository?.project?.name); + const repositoryName = trimOptionalString(raw.repository?.name); + if (organizationBase && projectName && repositoryName) { + const encodedProjectName = encodeAzureDevOpsPathSegment(projectName); + const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName); + return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${raw.pullRequestId}`; + } + + return trimOptionalString(raw.url) ?? ""; +} + function normalizeAzureDevOpsPullRequestRecord( raw: Schema.Schema.Type, ): NormalizedAzureDevOpsPullRequestRecord { return { number: raw.pullRequestId, title: raw.title, - url: trimOptionalString(raw._links?.web?.href) ?? trimOptionalString(raw.url) ?? "", + url: normalizeAzureDevOpsPullRequestUrl(raw), baseRefName: normalizeRefName(raw.targetRefName), headRefName: normalizeRefName(raw.sourceRefName), state: normalizeAzureDevOpsPullRequestState(raw.status), diff --git a/apps/server/src/sourceControl/gitHubAuthStatus.ts b/apps/server/src/sourceControl/gitHubAuthStatus.ts new file mode 100644 index 0000000000..d58909c560 --- /dev/null +++ b/apps/server/src/sourceControl/gitHubAuthStatus.ts @@ -0,0 +1,72 @@ +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +const GitHubAuthStatusAccountSchema = Schema.Struct({ + state: Schema.String, + error: Schema.optional(Schema.String), + active: Schema.Boolean, + host: Schema.String, + login: Schema.String, +}); + +const GitHubAuthStatusSchema = Schema.Struct({ + hosts: Schema.Record(Schema.String, Schema.Array(GitHubAuthStatusAccountSchema)), +}); + +const decodeGitHubAuthStatusJson = Schema.decodeUnknownOption( + Schema.fromJsonString(GitHubAuthStatusSchema), +); + +export interface GitHubAuthStatusAccount { + readonly host: string; + readonly account: string; + readonly authenticated: boolean; + readonly active: boolean; + readonly error: string | null; +} + +export interface GitHubAuthStatus { + readonly parsed: boolean; + readonly accounts: ReadonlyArray; +} + +function nonEmptyString(value: string): string | null { + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +export function parseGitHubAuthStatus(text: string): GitHubAuthStatus { + return Option.match(decodeGitHubAuthStatusJson(text), { + onNone: () => ({ parsed: false, accounts: [] }), + onSome: (status) => + ({ + parsed: true, + accounts: Object.values(status.hosts).flatMap((accounts) => + accounts.flatMap((account) => { + const host = nonEmptyString(account.host); + const login = nonEmptyString(account.login); + if (host === null || login === null) return []; + + return [ + { + host: host.toLowerCase(), + account: login, + authenticated: account.state === "success", + active: account.active, + error: account.error?.trim() || null, + }, + ]; + }), + ), + }) satisfies GitHubAuthStatus, + }); +} + +export function findAuthenticatedGitHubAccount( + accounts: ReadonlyArray, +): GitHubAuthStatusAccount | undefined { + return ( + accounts.find((account) => account.authenticated && account.active) ?? + accounts.find((account) => account.authenticated) + ); +} diff --git a/apps/server/src/sourceControl/gitLabAuthStatus.ts b/apps/server/src/sourceControl/gitLabAuthStatus.ts new file mode 100644 index 0000000000..f54e300353 --- /dev/null +++ b/apps/server/src/sourceControl/gitLabAuthStatus.ts @@ -0,0 +1,48 @@ +const HOST_LINE_PATTERN = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[[a-f0-9:.]+\])(?::\d+)?$/iu; +const LOGGED_IN_PATTERN = /Logged in to .+? as\s+([^\s(]+)/iu; + +export interface GitLabAuthStatusHost { + readonly host: string; + readonly account: string | null; +} + +export function parseGitLabAuthStatusHosts(text: string): ReadonlyArray { + const hosts: GitLabAuthStatusHost[] = []; + let currentHost: string | null = null; + let currentLines: string[] = []; + + const flush = () => { + if (currentHost === null) return; + + const account = LOGGED_IN_PATTERN.exec(currentLines.join("\n"))?.[1]?.trim() || null; + hosts.push({ host: currentHost, account }); + currentHost = null; + currentLines = []; + }; + + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line.length === 0) continue; + + const isHostLine = + rawLine.length === rawLine.trimStart().length && HOST_LINE_PATTERN.test(line); + if (isHostLine) { + flush(); + currentHost = line.toLowerCase(); + continue; + } + + if (currentHost !== null) { + currentLines.push(line); + } + } + + flush(); + return hosts; +} + +export function findAuthenticatedGitLabHost( + hosts: ReadonlyArray, +): GitLabAuthStatusHost | undefined { + return hosts.find((host) => host.account !== null); +} diff --git a/packages/shared/src/sourceControl.test.ts b/packages/shared/src/sourceControl.test.ts index 5e42199052..368e8387ee 100644 --- a/packages/shared/src/sourceControl.test.ts +++ b/packages/shared/src/sourceControl.test.ts @@ -56,4 +56,23 @@ describe("detectSourceControlProviderFromRemoteUrl", () => { detectSourceControlProviderFromRemoteUrl("git@bitbucket.org:workspace/repo.git")?.kind, ).toBe("bitbucket"); }); + + it("preserves ports while classifying by hostname", () => { + expect( + detectSourceControlProviderFromRemoteUrl("https://gitlab.com:8443/group/repo.git"), + ).toEqual({ + kind: "gitlab", + name: "GitLab", + baseUrl: "https://gitlab.com:8443", + }); + expect( + detectSourceControlProviderFromRemoteUrl( + "https://self-hosted.example.test:8443/group/repo.git", + ), + ).toEqual({ + kind: "unknown", + name: "self-hosted.example.test:8443", + baseUrl: "https://self-hosted.example.test:8443", + }); + }); }); diff --git a/packages/shared/src/sourceControl.ts b/packages/shared/src/sourceControl.ts index 24ff3a0da8..15a98dc735 100644 --- a/packages/shared/src/sourceControl.ts +++ b/packages/shared/src/sourceControl.ts @@ -149,12 +149,20 @@ function parseRemoteHost(remoteUrl: string): string | null { } try { - return new URL(trimmed).hostname.toLowerCase(); + return new URL(trimmed).host.toLowerCase(); } catch { return null; } } +function parseHostName(host: string): string { + try { + return new URL(`https://${host}`).hostname.toLowerCase(); + } catch { + return host.replace(/:\d+$/u, "").toLowerCase(); + } +} + function toBaseUrl(host: string): string { return `https://${host}`; } @@ -182,24 +190,25 @@ export function detectSourceControlProviderFromRemoteUrl( if (!host) { return null; } + const hostname = parseHostName(host); - if (isGitHubHost(host)) { + if (isGitHubHost(hostname)) { return { kind: "github", - name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted", + name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted", baseUrl: toBaseUrl(host), }; } - if (isGitLabHost(host)) { + if (isGitLabHost(hostname)) { return { kind: "gitlab", - name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted", + name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted", baseUrl: toBaseUrl(host), }; } - if (isAzureDevOpsHost(host)) { + if (isAzureDevOpsHost(hostname)) { return { kind: "azure-devops", name: "Azure DevOps", @@ -207,10 +216,10 @@ export function detectSourceControlProviderFromRemoteUrl( }; } - if (isBitbucketHost(host)) { + if (isBitbucketHost(hostname)) { return { kind: "bitbucket", - name: host === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted", + name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted", baseUrl: toBaseUrl(host), }; } From a74dfd4f3c06e5028b43af51d2e35139f7ac2c00 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 4 Jun 2026 15:14:07 -0700 Subject: [PATCH 4/7] [codex] Avoid shell for Node executable spawns (#2952) Co-authored-by: Julius Marminge --- apps/server/scripts/cli.ts | 2 -- packages/effect-acp/src/client.test.ts | 3 +-- packages/effect-acp/src/protocol.test.ts | 3 +-- packages/effect-codex-app-server/src/client.test.ts | 3 +-- 4 files changed, 3 insertions(+), 8 deletions(-) diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts index 63a8d1e9fa..65f99505a8 100644 --- a/apps/server/scripts/cli.ts +++ b/apps/server/scripts/cli.ts @@ -175,8 +175,6 @@ const buildCmd = Command.make( cwd: serverDir, stdout: config.verbose ? "inherit" : "ignore", stderr: "inherit", - // Windows needs shell mode to resolve `.cmd` shims on PATH. - shell: process.platform === "win32", }), ); diff --git a/packages/effect-acp/src/client.test.ts b/packages/effect-acp/src/client.test.ts index 88ec189a1f..aca87d45c6 100644 --- a/packages/effect-acp/src/client.test.ts +++ b/packages/effect-acp/src/client.test.ts @@ -34,9 +34,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => { Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; - const command = ChildProcess.make("node", mockPeerArgs(yield* mockPeerPath), { + const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), { cwd: path.join(import.meta.dirname, ".."), - shell: process.platform === "win32", ...(env ? { env: { ...process.env, ...env } } : {}), }); return yield* spawner.spawn(command); diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 385006078f..093d4acfcf 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -57,9 +57,8 @@ const makeHandle = (env?: Record) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; - const command = ChildProcess.make("node", mockPeerArgs(yield* mockPeerPath), { + const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), { cwd: path.join(import.meta.dirname, ".."), - shell: process.platform === "win32", ...(env ? { env: { ...process.env, ...env } } : {}), }); return yield* spawner.spawn(command); diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.ts index c8da7b18a1..77b5a16355 100644 --- a/packages/effect-codex-app-server/src/client.test.ts +++ b/packages/effect-codex-app-server/src/client.test.ts @@ -22,9 +22,8 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; const peerCwd = path.join(import.meta.dirname, ".."); - const command = ChildProcess.make("node", mockPeerArgs(yield* mockPeerPath), { + const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), { cwd: peerCwd, - shell: process.platform === "win32", }); return yield* spawner.spawn(command); }); From 6ce6f678b5d70a8d2b7230ec45cbde04d54f80dc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 4 Jun 2026 15:15:26 -0700 Subject: [PATCH 5/7] [codex] Avoid shell for Windows environment probe (#2951) Co-authored-by: Julius Marminge --- apps/desktop/src/shell/DesktopShellEnvironment.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f57873d9fb..a7d775d68f 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -241,7 +241,6 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn const output = yield* runCommandOutput({ command, args, - shell: true, timeout: LOGIN_SHELL_TIMEOUT, }); const environment = extractEnvironment(output, names); From 53042f47f85a986257573773d9854cf59b957514 Mon Sep 17 00:00:00 2001 From: Guilherme Vieira <46866023+GuilhermeVieiraDev@users.noreply.github.com> Date: Thu, 4 Jun 2026 23:19:06 +0100 Subject: [PATCH 6/7] fix(composer): support spaces in file mentions (#2625) --- .../src/features/threads/ThreadComposer.tsx | 3 +- .../src/components/ComposerPromptEditor.tsx | 3 +- apps/web/src/components/chat/ChatComposer.tsx | 3 +- apps/web/src/composer-editor-mentions.test.ts | 26 ++++++++++++++++ apps/web/src/composer-editor-mentions.ts | 30 ++++++++++++------- apps/web/src/composer-logic.test.ts | 20 +++++++++++++ apps/web/src/composer-logic.ts | 5 ++-- packages/shared/src/composerTrigger.test.ts | 17 +++++++++++ packages/shared/src/composerTrigger.ts | 9 ++++++ 9 files changed, 100 insertions(+), 16 deletions(-) create mode 100644 packages/shared/src/composerTrigger.test.ts diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index e13115d205..8f6d50482f 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -10,6 +10,7 @@ import type { import { detectComposerTrigger, replaceTextRange, + serializeComposerMentionPath, type ComposerTrigger, } from "@t3tools/shared/composerTrigger"; import { TextInputWrapper } from "expo-paste-input"; @@ -408,7 +409,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer let replacement = ""; if (item.type === "path") { - replacement = `@${item.path} `; + replacement = `@${serializeComposerMentionPath(item.path)} `; } else if (item.type === "skill") { replacement = `$${item.skill.name} `; } else if (item.type === "slash-command") { diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx index 6f17c86630..ab8e597ea6 100644 --- a/apps/web/src/components/ComposerPromptEditor.tsx +++ b/apps/web/src/components/ComposerPromptEditor.tsx @@ -6,6 +6,7 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin"; import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin"; import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin"; import { type ServerProviderSkill } from "@t3tools/contracts"; +import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger"; import { $applyNodeReplacement, $createRangeSelection, @@ -198,7 +199,7 @@ class ComposerMentionNode extends DecoratorNode { } override getTextContent(): string { - return `@${this.__path}`; + return `@${serializeComposerMentionPath(this.__path)}`; } override isInline(): true { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index d6677fa172..1185817454 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -17,6 +17,7 @@ import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, } from "@t3tools/contracts"; +import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; import { memo, @@ -1471,7 +1472,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { snapshot, trigger } = resolveActiveComposerTrigger(); if (!trigger) return; if (item.type === "path") { - const replacement = `@${item.path} `; + const replacement = `@${serializeComposerMentionPath(item.path)} `; const replacementRangeEnd = extendReplacementRangeForTrailingSpace( snapshot.value, trigger.rangeEnd, diff --git a/apps/web/src/composer-editor-mentions.test.ts b/apps/web/src/composer-editor-mentions.test.ts index 3a305424fb..af342b4c8b 100644 --- a/apps/web/src/composer-editor-mentions.test.ts +++ b/apps/web/src/composer-editor-mentions.test.ts @@ -29,6 +29,22 @@ describe("splitPromptIntoComposerSegments", () => { ]); }); + it("splits quoted mention tokens containing whitespace", () => { + expect(splitPromptIntoComposerSegments('Inspect @"My File.md" please')).toEqual([ + { type: "text", text: "Inspect " }, + { type: "mention", path: "My File.md" }, + { type: "text", text: " please" }, + ]); + }); + + it("unescapes quoted mention token content", () => { + expect(splitPromptIntoComposerSegments('Inspect @"docs/My \\"File\\".md" please')).toEqual([ + { type: "text", text: "Inspect " }, + { type: "mention", path: 'docs/My "File".md' }, + { type: "text", text: " please" }, + ]); + }); + it("splits skill tokens followed by whitespace into skill segments", () => { expect(splitPromptIntoComposerSegments("Use $review-follow-up please")).toEqual([ { type: "text", text: "Use " }, @@ -125,4 +141,14 @@ describe("selectionTouchesMentionBoundary", () => { ), ).toBe(true); }); + + it("returns true when selection includes whitespace after a quoted mention", () => { + expect( + selectionTouchesMentionBoundary( + 'hi @"My File.md" there', + 'hi @"My File.md"'.length, + 'hi @"My File.md" there'.length, + ), + ).toBe(true); + }); }); diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 9f4492cabf..1f93e68346 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -21,8 +21,8 @@ export type ComposerPromptSegment = context: TerminalContextDraft | null; }; -const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g; const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g; +const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g; function rangeIncludesIndex(start: number, end: number, index: number): boolean { return start <= index && index < end; @@ -52,13 +52,18 @@ type InlineTokenMatch = end: number; }; -function collectInlineTokenMatches(text: string): InlineTokenMatch[] { - const matches: InlineTokenMatch[] = []; +type MentionTokenMatch = Extract; + +function collectMentionTokenMatches(text: string): MentionTokenMatch[] { + const matches: MentionTokenMatch[] = []; for (const match of text.matchAll(MENTION_TOKEN_REGEX)) { const fullMatch = match[0]; const prefix = match[1] ?? ""; - const path = match[2] ?? ""; + const quotedPath = match[2]; + const unquotedPath = match[3]; + const path = + quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (unquotedPath ?? ""); const matchIndex = match.index ?? 0; const start = matchIndex + prefix.length; const end = start + fullMatch.length - prefix.length; @@ -67,6 +72,12 @@ function collectInlineTokenMatches(text: string): InlineTokenMatch[] { } } + return matches; +} + +function collectInlineTokenMatches(text: string): InlineTokenMatch[] { + const matches: InlineTokenMatch[] = collectMentionTokenMatches(text); + for (const match of text.matchAll(SKILL_TOKEN_REGEX)) { const fullMatch = match[0]; const prefix = match[1] ?? ""; @@ -148,10 +159,10 @@ function forEachPromptTextSlice( function forEachMentionMatch( prompt: string, - visitor: (match: RegExpMatchArray, promptOffset: number) => boolean | void, + visitor: (match: MentionTokenMatch, promptOffset: number) => boolean | void, ): boolean { return forEachPromptTextSlice(prompt, (text, promptOffset) => { - for (const match of text.matchAll(MENTION_TOKEN_REGEX)) { + for (const match of collectMentionTokenMatches(text)) { if (visitor(match, promptOffset) === true) { return true; } @@ -203,11 +214,8 @@ export function selectionTouchesMentionBoundary( } return forEachMentionMatch(prompt, (match, promptOffset) => { - const fullMatch = match[0]; - const prefix = match[1] ?? ""; - const matchIndex = match.index ?? 0; - const mentionStart = promptOffset + matchIndex + prefix.length; - const mentionEnd = mentionStart + fullMatch.length - prefix.length; + const mentionStart = promptOffset + match.start; + const mentionEnd = promptOffset + match.end; const beforeMentionIndex = mentionStart - 1; const afterMentionIndex = mentionEnd; diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts index ed4e017cb8..91c323638d 100644 --- a/apps/web/src/composer-logic.test.ts +++ b/apps/web/src/composer-logic.test.ts @@ -157,6 +157,16 @@ describe("expandCollapsedComposerCursor", () => { ); }); + it("maps collapsed quoted mention cursor to expanded text cursor", () => { + const text = 'what is in @"My File.md" please'; + const collapsedCursorAfterMention = "what is in ".length + 2; + const expandedCursorAfterMention = 'what is in @"My File.md" '.length; + + expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe( + expandedCursorAfterMention, + ); + }); + it("allows path trigger detection to close after selecting a mention", () => { const text = "what's in my @AGENTS.md "; const collapsedCursorAfterMention = "what's in my ".length + 2; @@ -191,6 +201,16 @@ describe("collapseExpandedComposerCursor", () => { ); }); + it("maps expanded quoted mention cursor back to collapsed cursor", () => { + const text = 'what is in @"My File.md" please'; + const collapsedCursorAfterMention = "what is in ".length + 2; + const expandedCursorAfterMention = 'what is in @"My File.md" '.length; + + expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe( + collapsedCursorAfterMention, + ); + }); + it("keeps replacement cursors aligned when another mention already exists earlier", () => { const text = "open @AGENTS.md then @src/index.ts "; const expandedCursor = text.length; diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index fb63d2581c..ef3243f4aa 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -1,3 +1,4 @@ +import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger"; import { splitPromptIntoComposerSegments } from "./composer-editor-mentions"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext"; @@ -54,7 +55,7 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number) for (const segment of segments) { if (segment.type === "mention") { - const expandedLength = segment.path.length + 1; + const expandedLength = serializeComposerMentionPath(segment.path).length + 1; if (remaining <= 1) { return expandedCursor + (remaining === 0 ? 0 : expandedLength); } @@ -142,7 +143,7 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number for (const segment of segments) { if (segment.type === "mention") { - const expandedLength = segment.path.length + 1; + const expandedLength = serializeComposerMentionPath(segment.path).length + 1; if (remaining === 0) { return collapsedCursor; } diff --git a/packages/shared/src/composerTrigger.test.ts b/packages/shared/src/composerTrigger.test.ts new file mode 100644 index 0000000000..99c34a3731 --- /dev/null +++ b/packages/shared/src/composerTrigger.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; + +import { serializeComposerMentionPath } from "./composerTrigger.ts"; + +describe("serializeComposerMentionPath", () => { + it("keeps simple mention paths unquoted", () => { + expect(serializeComposerMentionPath("src/index.ts")).toBe("src/index.ts"); + }); + + it("quotes mention paths containing whitespace", () => { + expect(serializeComposerMentionPath("docs/My File.md")).toBe('"docs/My File.md"'); + }); + + it("escapes quoted mention path content", () => { + expect(serializeComposerMentionPath('docs/My "File".md')).toBe('"docs/My \\"File\\".md"'); + }); +}); diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 8d12f954f6..8bc343efdb 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -8,6 +8,15 @@ export interface ComposerTrigger { rangeEnd: number; } +const SIMPLE_MENTION_PATH_REGEX = /^[^\s@"\\]+$/; + +export function serializeComposerMentionPath(path: string): string { + if (SIMPLE_MENTION_PATH_REGEX.test(path)) { + return path; + } + return `"${path.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; +} + function clampCursor(text: string, cursor: number): number { if (!Number.isFinite(cursor)) return text.length; return Math.max(0, Math.min(text.length, Math.floor(cursor))); From 300f7fd11d61704617119634a99563e16c0e6913 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 4 Jun 2026 15:25:46 -0700 Subject: [PATCH 7/7] [codex] Avoid shell for system executables (#2950) Co-authored-by: Julius Marminge --- apps/server/src/diagnostics/ProcessDiagnostics.ts | 1 - .../environment/Layers/ServerEnvironmentLabel.ts | 1 - .../Layers/RepositoryIdentityResolver.test.ts | 1 - .../project/Layers/RepositoryIdentityResolver.ts | 2 -- apps/server/src/terminal/Layers/Manager.ts | 1 - packages/ssh/src/command.ts | 8 ++++---- packages/ssh/src/tunnel.ts | 6 +++--- packages/tailscale/src/tailscale.ts | 13 +++---------- 8 files changed, 10 insertions(+), 23 deletions(-) diff --git a/apps/server/src/diagnostics/ProcessDiagnostics.ts b/apps/server/src/diagnostics/ProcessDiagnostics.ts index f56bf21651..b8ace8ccb3 100644 --- a/apps/server/src/diagnostics/ProcessDiagnostics.ts +++ b/apps/server/src/diagnostics/ProcessDiagnostics.ts @@ -280,7 +280,6 @@ const runProcess = Effect.fn("runProcess")( const child = yield* spawner.spawn( ChildProcess.make(input.command, input.args, { cwd: process.cwd(), - shell: process.platform === "win32", }), ); const [stdout, stderr, exitCode] = yield* Effect.all( diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts index 7dc6bc34a4..b07425b936 100644 --- a/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts +++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts @@ -59,7 +59,6 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* ( command, args, timeoutBehavior: "timedOutResult", - shell: process.platform === "win32", }) .pipe(Effect.option); diff --git a/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts b/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts index a47181c866..1c985cd859 100644 --- a/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts @@ -23,7 +23,6 @@ const git = (cwd: string, args: ReadonlyArray) => return yield* processRunner.run({ command: "git", args: ["-C", cwd, ...args], - shell: process.platform === "win32", }); }).pipe(Effect.provide(ProcessRunner.layer)); diff --git a/apps/server/src/project/Layers/RepositoryIdentityResolver.ts b/apps/server/src/project/Layers/RepositoryIdentityResolver.ts index 926c1d0c2e..4fdaa71de2 100644 --- a/apps/server/src/project/Layers/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/Layers/RepositoryIdentityResolver.ts @@ -94,7 +94,6 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCa command: "git", args: ["-C", cwd, "rev-parse", "--show-toplevel"], timeoutBehavior: "timedOutResult", - shell: process.platform === "win32", }) .pipe(Effect.option); if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) { @@ -119,7 +118,6 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdenti command: "git", args: ["-C", cacheKey, "remote", "-v"], timeoutBehavior: "timedOutResult", - shell: process.platform === "win32", }) .pipe(Effect.option); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 82eb9502cf..2eaf19ec16 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -519,7 +519,6 @@ function windowsInspectSubprocess( timeout: "1500 millis", maxOutputBytes: 32_768, outputMode: "truncate", - shell: process.platform === "win32", timeoutBehavior: "timedOutResult", }); }).pipe( diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index 06aa1109ed..44cc047aae 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -16,6 +16,7 @@ import { SshCommandError, SshInvalidTargetError } from "./errors.ts"; const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u; const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000; const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000; +export const SSH_COMMAND = process.platform === "win32" ? "ssh.exe" : "ssh"; const encoder = new TextEncoder(); @@ -192,15 +193,14 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; yield* Effect.logDebug("ssh.command.start", { ...sshTargetLogFields(target), - command: ["ssh", ...args], + command: [SSH_COMMAND, ...args], hasStdin: input.stdin !== undefined, timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, }); const child = yield* spawner .spawn( - ChildProcess.make("ssh", args, { + ChildProcess.make(SSH_COMMAND, args, { env: environment, - shell: process.platform === "win32", stdin: { stream: stdinStream(input.stdin), endOnDone: true, @@ -212,7 +212,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func Effect.mapError( (cause) => new SshCommandError({ - command: ["ssh", ...args], + command: [SSH_COMMAND, ...args], exitCode: null, stderr: "", message: diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 88a30960e8..029b764489 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -36,6 +36,7 @@ import { remoteStateKey, resolveSshTarget, runSshCommand, + SSH_COMMAND, targetConnectionKey, } from "./command.ts"; import { @@ -1068,7 +1069,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: `${input.localPort}:127.0.0.1:${input.remotePort}`, hostSpec, ]; - const tunnelCommand = ["ssh", ...args]; + const tunnelCommand = [SSH_COMMAND, ...args]; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const scope = yield* Scope.Scope; yield* Effect.logDebug("ssh.tunnel.spawn.start", { @@ -1081,9 +1082,8 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }); const child = yield* spawner .spawn( - ChildProcess.make("ssh", args, { + ChildProcess.make(SSH_COMMAND, args, { env: childEnvironment, - shell: process.platform === "win32", stdin: { stream: Stream.empty, endOnDone: true, diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts index c8d9cab462..cdb549232b 100644 --- a/packages/tailscale/src/tailscale.ts +++ b/packages/tailscale/src/tailscale.ts @@ -10,6 +10,7 @@ export const DEFAULT_TAILSCALE_SERVE_PORT = 443; export const TAILSCALE_STATUS_TIMEOUT_MS = 1_500; export const TAILSCALE_SERVE_TIMEOUT_MS = 10_000; export const TAILSCALE_PROBE_TIMEOUT_MS = 2_500; +const TAILSCALE_COMMAND = process.platform === "win32" ? "tailscale.exe" : "tailscale"; export class TailscaleCommandError extends Data.TaggedError("TailscaleCommandError")<{ readonly command: readonly string[]; @@ -136,11 +137,7 @@ export const readTailscaleStatus: Effect.Effect< const args = ["status", "--json"]; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const child = yield* spawner - .spawn( - ChildProcess.make("tailscale", args, { - shell: process.platform === "win32", - }), - ) + .spawn(ChildProcess.make(TAILSCALE_COMMAND, args)) .pipe( Effect.mapError((cause) => tailscaleCommandError( @@ -215,11 +212,7 @@ const runTailscaleCommand = ( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const child = yield* spawner - .spawn( - ChildProcess.make("tailscale", args, { - shell: process.platform === "win32", - }), - ) + .spawn(ChildProcess.make(TAILSCALE_COMMAND, args)) .pipe( Effect.mapError((cause) => tailscaleCommandError(