Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge a8c8572fa0 Tighten relay lock Effect types
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:35:08 +00:00
Cursor AgentandJulius Marminge 8a817fbb26 Format relay client Effect refactor
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:33:15 +00:00
Cursor AgentandJulius Marminge 1c9464e389 Remove brittle relay lock exhaustion test
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:32:05 +00:00
Cursor AgentandJulius Marminge 2393953551 Advance relay lock retry test past boundary
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:30:38 +00:00
Cursor AgentandJulius Marminge eb78135632 Use finite schedule for relay lock retries
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:28:39 +00:00
Cursor AgentandJulius Marminge 86a88fb3ef Provide TestClock for relay lock tests
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:26:50 +00:00
Cursor AgentandJulius Marminge f1d324b9d2 Stabilize relay lock TestClock timing
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:24:32 +00:00
Cursor AgentandJulius Marminge 404cba92f6 Fix relay lock timeout test fiber
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:23:08 +00:00
Cursor AgentandJulius Marminge 5feb87d274 Make relay install lock more idiomatic Effect
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:09:04 +00:00
Julius Marmingeandcodex 3ea6adf17d [codex] Enrich relay authorization diagnostics (#2977)
Co-authored-by: codex <[email protected]>
2026-06-05 18:01:34 -07:00
Julius Marminge a56496c7f2 Annotate relay error spans with schema fields (#2976) 2026-06-05 16:35:14 -07:00
b76f161d55 fix(desktop): stop looping macOS TCC permission prompts (#2745)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 12:07:18 -07:00
Peter Hozák 75257d64e9 "claude system message" instead of "runtime warning" when using 4.8 from claude code (#2972) 2026-06-05 11:27:37 -07:00
Abdul AzeezandJulius Marminge e1ce9f8500 fix: handle Claude Agent SDK 0.3.x system messages to stop runtime-warning flood (#2872)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 18:26:32 +00:00
Julius Marminge 602148f8fe fix(cloud): use Electron fetch for proxying Clerk IPC requests (#2973) 2026-06-05 11:08:34 -07:00
Julius Marminge 92be60e7c1 include @latest 2026-06-04 23:01:09 -07:00
Julius Marminge 0d6e9e9add we support cursor, duhhh 2026-06-04 23:00:40 -07:00
Julius Marminge 8ab58a0b26 tip 2026-06-04 22:59:28 -07:00
Julius Marminge 6f42bd9c88 cleanup 2026-06-04 22:58:53 -07:00
Julius Marminge 5b26bd408b link 2026-06-04 22:57:04 -07:00
Julius Marminge c04d15d3be document vp instead of mise 2026-06-04 22:56:18 -07:00
Julius Marminge 9da430c828 Refactor recoverable Effect fallbacks to orElseSucceed (#2968) 2026-06-05 05:47:56 +00:00
Julius Marminge a084fbbc0a Remove duplicate 'publish' argument in CLI script 2026-06-04 22:39:59 -07:00
Julius Marminge b870a6e349 Rename function for publishing arguments to vp pm (#2967) 2026-06-05 05:22:37 +00:00
Julius Marminge e1cb19b55b Use pnpm for server publish workflow (#2966) 2026-06-04 22:16:52 -07:00
Julius Marminge 94fc117561 publish deploy status on relay deploy workflow 2026-06-04 21:47:12 -07:00
Julius Marminge 113b9d84c7 remove vp staged 2026-06-04 21:41:54 -07:00
Julius Marminge f60def2054 Migrate tests to vite-plus test APIs (#2964) 2026-06-05 04:39:19 +00:00
Julius Marminge eda163ca17 bump alchemy to fix drizzle schema out attempt 2 2026-06-04 21:03:05 -07:00
Julius Marminge 3579005114 bump alchemy to fix absolute drizzle schema out 2026-06-04 20:45:34 -07:00
Julius Marminge af3dfd229e forward args directly 2026-06-04 20:19:06 -07:00
Julius Marminge 969e6d274c implicit install from vp 2026-06-04 20:16:56 -07:00
Julius Marminge 769bdd251d fallback to None when RELAY_DOMAIN is unset 2026-06-04 20:16:23 -07:00
Julius Marminge 295b9db113 dont fail if env-file is unspecified 2026-06-04 20:12:42 -07:00
Julius Marminge b5a62504d4 move 2026-06-04 20:05:30 -07:00
Julius Marminge ec18938bf9 Restructure documentation into topical folders (#2963) 2026-06-04 20:03:12 -07:00
Julius Marmingeandcodex 5ae77c0d63 feat(relay): Add managed relay tunnels and APN service (#2837)
Co-authored-by: codex <[email protected]>
2026-06-04 19:53:56 -07:00
Julius MarmingeandJulius Marminge 300f7fd11d [codex] Avoid shell for system executables (#2950)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:25:46 -07:00
Guilherme Vieira 53042f47f8 fix(composer): support spaces in file mentions (#2625) 2026-06-04 15:19:06 -07:00
Julius MarmingeandJulius Marminge 6ce6f678b5 [codex] Avoid shell for Windows environment probe (#2951)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:15:26 -07:00
Julius MarmingeandJulius Marminge a74dfd4f3c [codex] Avoid shell for Node executable spawns (#2952)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:14:07 -07:00
Guilherme VieiraandJulius Marminge 49c1b64687 fix(source-control): handle self-hosted GitLab, multi-account GitHub auth & azure devops web url (#2480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 15:13:04 -07:00
Julius MarmingeandJulius Marminge dfdb5a46db [codex] fix release finalize install (#2961)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 21:57:43 +00:00
Julius Marminge b0fa60a121 Prevent settings layout shifts with scrollbar gutters (#2960) 2026-06-04 14:31:24 -07:00
Julius MarmingeandJulius Marminge 348a9140e9 fix(cli): bundle patched diff parser dependency (#2957)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-04 18:53:47 +00:00
Julius Marminge 9fc485afaf fix(release): install hosted web workspace closure (#2949) 2026-06-04 17:31:54 +00:00
242 changed files with 4090 additions and 6461 deletions

No files matched your search

+28 -6
View File
@@ -8,6 +8,7 @@ on:
permissions:
contents: read
id-token: none
statuses: write
concurrency:
group: relay-production
@@ -25,7 +26,8 @@ jobs:
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_ZONE_NAME: ${{ vars.RELAY_ZONE_NAME }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
@@ -42,13 +44,11 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: false
- name: Install dependencies
run: vp install --frozen-lockfile
run-install: true
- name: Deploy production relay stage
run: vp run --filter t3code-relay deploy -- --stage prod --yes
id: deploy
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
@@ -56,3 +56,25 @@ jobs:
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
- name: Publish relay deploy commit status
uses: actions/github-script@v8
with:
script: |
const result = "${{ steps.deploy.outputs.result }}";
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
const description = changed
? "Relay production deploy applied infrastructure changes."
: result === "noop"
? "Relay production deploy was a no-op."
: `Relay production deploy completed with result: ${result}.`;
await github.rest.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
sha: context.sha,
state: "success",
context: "Relay deploy / production",
description,
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
});
+8 -2
View File
@@ -181,6 +181,7 @@ jobs:
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
@@ -191,8 +192,12 @@ jobs:
run: |
set -euo pipefail
relay_domain="${RELAY_DOMAIN:-}"
if [[ -z "$relay_domain" && -n "${RELAY_API_ZONE_NAME:-}" ]]; then
relay_domain="relay.$RELAY_API_ZONE_NAME"
fi
required=(
RELAY_DOMAIN
relay_domain
CLERK_PUBLISHABLE_KEY
CLERK_JWT_TEMPLATE
CLERK_CLI_OAUTH_CLIENT_ID
@@ -211,7 +216,7 @@ jobs:
echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT"
echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT"
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$RELAY_DOMAIN" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
build:
name: Build ${{ matrix.label }}
@@ -768,6 +773,7 @@ jobs:
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/oxlint-plugin-t3code...
- id: update_versions
name: Update version strings
-2
View File
@@ -1,2 +0,0 @@
[tools]
node = "24.13.1"
-1
View File
@@ -1 +0,0 @@
vp staged
+32 -13
View File
@@ -1,23 +1,26 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, and OpenCode.
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Run without installing
```bash
npx t3
npx t3@latest
```
Tip: Use `npx t3@latest --help` for the full CLI reference.
### Desktop app
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
@@ -46,25 +49,41 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
Relay observability: [docs/relay-observability.md](./docs/relay-observability.md)
## Documentation
T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md)
- [Getting started](./docs/getting-started/quick-start.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
- [Reference](./docs/reference/encyclopedia.md)
## If you REALLY want to contribute still.... read this first
Before local development, prepare the environment and install dependencies:
### Install `vp`
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
#### macOS / Linux
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
vp install
curl -fsSL https://vite.plus | bash
```
T3 Cloud is optional and disabled in a fresh clone. To enable it for web, desktop, and mobile source
builds, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the canonical
public configuration there.
#### Windows
```bash
irm https://vite.plus/ps1 | iex
```
Checkout their getting started guide for more information: https://viteplus.dev/guide/
### Install dependencies
```bash
vp i
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+1 -2
View File
@@ -27,8 +27,7 @@
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"vite-plus": "catalog:",
"vitest": "catalog:"
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+1 -1
View File
@@ -52,7 +52,7 @@ const make = Effect.gen(function* () {
Effect.map((parsed) =>
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
),
Effect.catch(() => Effect.succeed(Option.none<string>())),
Effect.orElseSucceed(() => Option.none<string>()),
),
});
});
@@ -64,6 +64,13 @@ function mockSpawnerLayer(statusJson = "{}") {
);
}
function dieOnSpawnLayer() {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
);
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
@@ -86,6 +93,7 @@ function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -97,7 +105,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -116,13 +124,23 @@ const withHarness = <A, E, R>(
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-server-exposure-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
return yield* effect.pipe(
Effect.provide(
makeLayer({
baseDir,
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -239,6 +257,27 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
// mode stays at default "local-only", tailscaleServeEnabled stays false.
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
// would have crashed the test if the gate was missing.
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/"],
);
}),
{},
dieOnSpawnLayer(),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
@@ -12,6 +12,7 @@ import type {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -22,8 +23,11 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -412,6 +416,18 @@ const make = Effect.gen(function* () {
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
// spawn re-triggers the "Other apps" TCC prompt.
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
TAILSCALE_STATUS_CACHE_TTL,
);
const readNetworkInterfaces = networkInterfaces.read;
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
@@ -516,11 +532,20 @@ const make = Effect.gen(function* () {
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
// Don't spawn the Tailscale CLI when the user hasn't opted into any
// network exposure. The spawn itself triggers a macOS "Other apps"
// TCC prompt on Mac App Store Tailscale builds.
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
return coreEndpoints;
}
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
readMagicDnsName: cachedReadMagicDnsName,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
Effect.gen(function* () {
let readerCalls = 0;
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
readMagicDnsName: Effect.sync(() => {
readerCalls += 1;
return "desktop.tail.ts.net";
}),
});
assert.equal(readerCalls, 1);
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["https://desktop.tail.ts.net/"],
);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
@@ -105,6 +105,11 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
never,
ChildProcessSpawner.ChildProcessSpawner
>;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<
readonly AdvertisedEndpoint[],
@@ -112,15 +117,18 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const readDnsName =
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
)
? yield* readDnsName
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
)
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
+35 -43
View File
@@ -1,29 +1,35 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vitest";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
@@ -33,16 +39,8 @@ describe("Desktop cloud auth IPC", () => {
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -55,32 +53,25 @@ describe("Desktop cloud auth IPC", () => {
body,
});
assert(forwardedRequest !== null);
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
forwardedRequest.headers["content-type"],
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -89,9 +80,10 @@ describe("Desktop cloud auth IPC", () => {
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
+66 -43
View File
@@ -8,9 +8,11 @@ import {
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
@@ -52,6 +54,68 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
@@ -108,47 +172,6 @@ export const fetchCloudAuth = makeIpcMethod({
}),
});
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
@@ -209,7 +209,7 @@ function readSettings(
onSome: (raw) =>
decodeDesktopSettingsJson(raw).pipe(
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
Effect.catch(() => Effect.succeed(defaultSettings)),
Effect.orElseSucceed(() => defaultSettings),
),
}),
),
@@ -63,7 +63,7 @@ const readClientSettings = (
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
),
}),
),
@@ -185,7 +185,7 @@ function readRegistryDocument(
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
),
}),
),
@@ -196,7 +196,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
.pipe(
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.catch(() => Effect.succeed("")),
Effect.orElseSucceed(() => ""),
);
});
@@ -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);
+1 -1
View File
@@ -120,7 +120,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
return decodeAppUpdateYmlConfig(entries).pipe(
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
);
}
@@ -1,256 +0,0 @@
import { afterEach, beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { EnvironmentId, OrchestrationShellSnapshot, ThreadId } from "@t3tools/contracts";
import {
__resetAgentLiveActivitiesForTest,
refreshActiveLiveActivityRemoteRegistration,
syncAgentLiveActivitiesForSnapshot,
} from "./liveActivityController";
import { registerLiveActivityPushToken } from "./remoteRegistration";
const mocks = vi.hoisted(() => {
const existingActivity = {
update: vi.fn(() => Promise.resolve()),
end: vi.fn((_dismissal: unknown, _props?: unknown, _endedAt?: unknown) => Promise.resolve()),
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
return {
existingActivity,
getInstances: vi.fn(() => [existingActivity]),
start: vi.fn(() => existingActivity),
registerLiveActivityPushToken: vi.fn(
(): Effect.Effect<boolean, unknown> => Effect.succeed(true),
),
};
});
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
},
}));
vi.mock("expo-linking", () => ({
default: {
createURL: vi.fn((path: string) => `t3code://${path}`),
},
createURL: vi.fn((path: string) => `t3code://${path}`),
}));
vi.mock("expo-widgets", () => ({
after: (date: Date) => ({ after: date }),
}));
vi.mock("../../lib/runtime", () => ({
mobileRuntime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) => Effect.runPromise(operation),
},
}));
vi.mock("../../widgets/AgentActivity", () => ({
default: {
getInstances: mocks.getInstances,
start: mocks.start,
},
}));
vi.mock("./remoteRegistration", () => ({
registerLiveActivityPushToken: mocks.registerLiveActivityPushToken,
}));
const runManagedRelayEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
Effect.runPromise(effect.pipe(Effect.provideService(ManagedRelayClient, null as never)));
function runningSnapshot(): OrchestrationShellSnapshot {
return {
projects: [
{
id: "project-1",
title: "Project",
},
],
threads: [
{
id: "thread-1" as ThreadId,
projectId: "project-1",
title: "Thread",
modelSelection: {
model: "gpt-5",
},
session: {
status: "running",
providerName: "Codex",
},
latestTurn: {
state: "running",
},
updatedAt: "2026-05-25T00:00:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
},
],
} as unknown as OrchestrationShellSnapshot;
}
function completedSnapshot(): OrchestrationShellSnapshot {
return {
projects: [
{
id: "project-1",
title: "Project",
},
],
threads: [
{
id: "thread-1" as ThreadId,
projectId: "project-1",
title: "Thread",
modelSelection: {
model: "gpt-5",
},
session: null,
latestTurn: {
state: "completed",
},
updatedAt: "2026-05-25T00:01:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
},
],
} as unknown as OrchestrationShellSnapshot;
}
describe("liveActivityController", () => {
beforeEach(() => {
vi.stubGlobal("__DEV__", false);
__resetAgentLiveActivitiesForTest();
mocks.existingActivity.update.mockClear();
mocks.existingActivity.end.mockClear();
mocks.existingActivity.getPushToken.mockClear();
mocks.existingActivity.addPushTokenListener.mockClear();
mocks.getInstances.mockClear();
mocks.getInstances.mockReturnValue([mocks.existingActivity]);
mocks.start.mockClear();
mocks.registerLiveActivityPushToken.mockClear();
mocks.registerLiveActivityPushToken.mockReturnValue(Effect.succeed(true));
});
afterEach(() => {
vi.useRealTimers();
});
it("adopts an existing remote-started Live Activity instead of creating a duplicate", async () => {
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
expect(mocks.getInstances).toHaveBeenCalledTimes(1);
expect(mocks.existingActivity.update).toHaveBeenCalledTimes(1);
expect(mocks.start).not.toHaveBeenCalled();
expect(registerLiveActivityPushToken).toHaveBeenCalledWith({
activity: mocks.existingActivity,
});
});
it("keeps skipped remote token registrations retryable after cloud sign-in", async () => {
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(false))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration());
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, {
activity: mocks.existingActivity,
});
});
it("retries cloud sign-in Live Activity token refresh failures", async () => {
vi.useFakeTimers();
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(true))
.mockReturnValueOnce(Effect.fail(new Error("relay unavailable")))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration());
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(15_000);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(3);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(3, {
activity: mocks.existingActivity,
});
});
it("retries adopted remote-start Live Activity token registration when the token is initially unavailable", async () => {
vi.useFakeTimers();
mocks.registerLiveActivityPushToken
.mockReturnValueOnce(Effect.succeed(false))
.mockReturnValueOnce(Effect.succeed(true));
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(15_000);
expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2);
expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, {
activity: mocks.existingActivity,
});
});
it("ends active Live Activities with the terminal thread content state", async () => {
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: runningSnapshot(),
}),
);
await Effect.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId: "env-1" as EnvironmentId,
snapshot: completedSnapshot(),
}),
);
expect(mocks.existingActivity.end).toHaveBeenCalledTimes(1);
expect(mocks.existingActivity.end.mock.calls[0]?.[1]).toMatchObject({
activeCount: 1,
activities: [
{
environmentId: "env-1",
threadId: "thread-1",
phase: "completed",
status: "Done",
},
],
});
});
});
@@ -1,605 +0,0 @@
import {
isTerminalAgentAwarenessPhase,
projectThreadAwareness,
type AgentAwarenessState,
} from "@t3tools/shared/agentAwareness";
import type {
EnvironmentId,
OrchestrationProjectShell,
OrchestrationShellSnapshot,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import { after, type LiveActivity } from "expo-widgets";
import * as Linking from "expo-linking";
import { Platform } from "react-native";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { mobileRuntime } from "../../lib/runtime";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { registerLiveActivityPushToken } from "./remoteRegistration";
const MAX_LOCAL_LIVE_ACTIVITIES = 3;
const FINAL_ACTIVITY_DISMISSAL_MS = 5 * 60 * 1_000;
const REMOTE_TOKEN_REGISTRATION_RETRY_MS = 15_000;
const MISSING_STATE_GRACE_MS = 30_000;
interface ActiveDeviceActivity {
readonly instance: LiveActivity<AgentActivityProps>;
readonly props: AgentActivityProps;
readonly lastRemoteTokenRegistrationAttemptAt: number | null;
readonly remoteTokenRegistered: boolean;
readonly remoteTokenRetryScheduled: boolean;
readonly missingSince: number | null;
}
let activeActivity: ActiveDeviceActivity | null = null;
const environmentStates = new Map<EnvironmentId, ReadonlyArray<AgentAwarenessState>>();
let localLiveActivitiesEnabled = true;
const liveActivitySyncSemaphore = Effect.runSync(Semaphore.make(1));
function canUseLocalLiveActivities(): boolean {
return localLiveActivitiesEnabled && Platform.OS === "ios";
}
function logLiveActivityDebug(context: string, details?: unknown): void {
if (!__DEV__) {
return;
}
console.log(`[agent-awareness] ${context}`, details ?? "");
}
function logLiveActivityWarning(context: string, error: unknown): void {
if (!__DEV__) {
return;
}
console.warn(
`[agent-awareness] ${context}`,
error instanceof Error ? error.message : String(error),
);
}
function statusForPhase(phase: AgentAwarenessState["phase"]): string {
switch (phase) {
case "waiting_for_approval":
return "Approval";
case "waiting_for_input":
return "Input";
case "completed":
return "Done";
case "failed":
return "Failed";
case "starting":
return "Starting";
case "running":
return "Working";
case "stale":
return "Waiting";
}
}
function epochMillis(iso: string): number {
return Option.match(DateTime.make(iso), {
onNone: () => Number.NaN,
onSome: (dt) => dt.epochMilliseconds,
});
}
function currentTimeMillis(): number {
return Date.now();
}
function currentDateTime(): DateTime.Utc {
return DateTime.nowUnsafe();
}
function toActivityProps(states: ReadonlyArray<AgentAwarenessState>): AgentActivityProps {
const updatedAt = states.reduce<string | null>((latest, state) => {
if (latest === null) {
return state.updatedAt;
}
return epochMillis(state.updatedAt) > epochMillis(latest) ? state.updatedAt : latest;
}, null);
return {
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: states.length,
updatedAt: updatedAt ?? DateTime.formatIso(currentDateTime()),
activities: states.slice(0, MAX_LOCAL_LIVE_ACTIVITIES).map((state) => ({
environmentId: state.environmentId,
threadId: state.threadId,
projectTitle: state.projectTitle,
threadTitle: state.threadTitle,
modelTitle: state.modelTitle,
phase: state.phase,
status: statusForPhase(state.phase),
updatedAt: state.updatedAt,
deepLink: state.deepLink,
})),
};
}
function hasSameActivityContent(left: AgentActivityProps, right: AgentActivityProps): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
function sortByUpdatedAtDesc(left: AgentAwarenessState, right: AgentAwarenessState): number {
return epochMillis(right.updatedAt) - epochMillis(left.updatedAt);
}
function projectSnapshotAwareness(input: {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
}): ReadonlyArray<AgentAwarenessState> {
const projectsById = new Map<string, OrchestrationProjectShell>(
input.snapshot.projects.map((project) => [project.id, project]),
);
const states: AgentAwarenessState[] = [];
for (const thread of input.snapshot.threads) {
const project = projectsById.get(thread.projectId);
if (!project) {
continue;
}
const state = projectThreadAwareness({
environmentId: input.environmentId,
project,
thread,
});
if (state) {
states.push(state);
}
}
return states;
}
export function syncAgentLiveActivitiesForSnapshot(input: {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot | null;
}): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(
Effect.gen(function* () {
if (!canUseLocalLiveActivities()) {
return;
}
if (input.snapshot === null) {
return yield* endEnvironmentLiveActivitiesNow(input.environmentId);
}
const states = projectSnapshotAwareness({
environmentId: input.environmentId,
snapshot: input.snapshot,
});
environmentStates.set(input.environmentId, states);
return yield* syncAgentLiveActivities();
}),
);
}
export function endEnvironmentLiveActivities(
environmentId: EnvironmentId,
): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(endEnvironmentLiveActivitiesNow(environmentId));
}
function endEnvironmentLiveActivitiesNow(
environmentId: EnvironmentId,
): Effect.Effect<void, unknown> {
return Effect.gen(function* () {
environmentStates.delete(environmentId);
return yield* syncAgentLiveActivities();
});
}
export function endAllAgentLiveActivities(): Effect.Effect<void, unknown> {
return enqueueLiveActivitySync(endAllAgentLiveActivitiesNow());
}
function endAllAgentLiveActivitiesNow(): Effect.Effect<void, unknown> {
return Effect.gen(function* () {
environmentStates.clear();
return yield* endActiveActivity(null, "all-ended");
});
}
function enqueueLiveActivitySync<T, R>(
operation: Effect.Effect<T, unknown, R>,
): Effect.Effect<T, unknown, R> {
return liveActivitySyncSemaphore.withPermits(1)(operation);
}
function syncAgentLiveActivities(): Effect.Effect<void, unknown> {
const states = [...environmentStates.values()].flat().sort(sortByUpdatedAtDesc);
const activeNonTerminalStates = states.filter(
(state) => !isTerminalAgentAwarenessPhase(state.phase),
);
const terminalState = states.find((state) => isTerminalAgentAwarenessPhase(state.phase)) ?? null;
if (activeNonTerminalStates.length === 0) {
if (!activeActivity) {
return Effect.void;
}
if (terminalState) {
return endActiveActivity(terminalState, "terminal-state");
}
const now = currentTimeMillis();
if (activeActivity.missingSince === null) {
activeActivity = { ...activeActivity, missingSince: now };
logLiveActivityDebug("live activity missing state; waiting before ending", {
graceMs: MISSING_STATE_GRACE_MS,
});
return Effect.void;
}
if (now - activeActivity.missingSince >= MISSING_STATE_GRACE_MS) {
return endActiveActivity(null, "missing-state");
}
return Effect.void;
}
return startOrUpdateActivity(activeNonTerminalStates);
}
function startOrUpdateActivity(
states: ReadonlyArray<AgentAwarenessState>,
): Effect.Effect<void, unknown> {
const props = toActivityProps(states);
const primaryState = states[0];
if (activeActivity) {
const active = activeActivity;
if (!hasSameActivityContent(active.props, props)) {
logLiveActivityDebug("updating live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"update",
Effect.tryPromise({
try: () => active.instance.update(props),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((updated) =>
Effect.sync(() => {
if (!updated.ok) {
activeActivity = null;
return;
}
activeActivity = { ...active, props, missingSince: null };
retryRemoteTokenRegistration(activeActivity.instance);
}),
),
);
} else if (activeActivity.missingSince !== null) {
activeActivity = { ...activeActivity, missingSince: null };
}
retryRemoteTokenRegistration(activeActivity.instance);
return Effect.void;
}
return adoptExistingActivity(props, primaryState).pipe(
Effect.flatMap((adopted) => {
if (adopted) {
return Effect.void;
}
logLiveActivityDebug("starting live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"start",
Effect.try({
try: () => AgentActivity.start(props, Linking.createURL(primaryState?.deepLink ?? "/")),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((started) =>
Effect.sync(() => {
const instance = started.ok ? started.value : undefined;
if (instance) {
logLiveActivityDebug("live activity started", {
primaryThreadId: primaryState?.threadId ?? null,
localActivityCount: AgentActivity.getInstances().length,
rowCount: props.activeCount,
});
activeActivity = {
instance,
props,
lastRemoteTokenRegistrationAttemptAt: null,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
missingSince: null,
};
retryRemoteTokenRegistration(instance);
}
}),
),
);
}),
);
}
function adoptExistingActivity(
props: AgentActivityProps,
primaryState: AgentAwarenessState | undefined,
): Effect.Effect<boolean, unknown> {
const existingActivity = AgentActivity.getInstances()[0];
if (!existingActivity) {
return Effect.succeed(false);
}
logLiveActivityDebug("adopting existing live activity", {
activeCount: props.activeCount,
primaryThreadId: primaryState?.threadId ?? null,
});
return runLiveActivityOperation(
"update",
Effect.tryPromise({
try: () => existingActivity.update(props),
catch: (error) => error,
}),
).pipe(
Effect.flatMap((updated) =>
Effect.sync(() => {
if (!updated.ok) {
return false;
}
activeActivity = {
instance: existingActivity,
props,
lastRemoteTokenRegistrationAttemptAt: null,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
missingSince: null,
};
retryRemoteTokenRegistration(existingActivity);
return true;
}),
),
);
}
function retryRemoteTokenRegistration(activity: LiveActivity<AgentActivityProps>): void {
if (!activeActivity) {
return;
}
if (activeActivity.remoteTokenRegistered) {
return;
}
const now = currentTimeMillis();
if (
activeActivity.lastRemoteTokenRegistrationAttemptAt !== null &&
now - activeActivity.lastRemoteTokenRegistrationAttemptAt < REMOTE_TOKEN_REGISTRATION_RETRY_MS
) {
return;
}
activeActivity = {
...activeActivity,
lastRemoteTokenRegistrationAttemptAt: now,
};
void mobileRuntime
.runPromise(
registerRemoteActivityToken(activity).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (!registered) {
scheduleRemoteTokenRegistrationRetry(activity);
}
}),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning(
"live activity token registration failed; retry scheduled",
error,
);
scheduleRemoteTokenRegistrationRetry(activity);
}),
),
),
)
.catch((error: unknown) => {
logLiveActivityWarning("unexpected live activity token registration failure", error);
});
}
function registerRemoteActivityToken(
activity: LiveActivity<AgentActivityProps>,
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
return registerLiveActivityPushToken({ activity }).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (registered && activeActivity?.instance === activity) {
activeActivity = {
...activeActivity,
remoteTokenRegistered: true,
remoteTokenRetryScheduled: false,
};
}
return registered;
}),
),
);
}
function scheduleRemoteTokenRegistrationRetry(activity: LiveActivity<AgentActivityProps>): void {
if (
!activeActivity ||
activeActivity.instance !== activity ||
activeActivity.remoteTokenRegistered ||
activeActivity.remoteTokenRetryScheduled
) {
return;
}
activeActivity = {
...activeActivity,
remoteTokenRetryScheduled: true,
};
void mobileRuntime
.runPromise(
Effect.sleep(Duration.millis(REMOTE_TOKEN_REGISTRATION_RETRY_MS)).pipe(
Effect.flatMap(() =>
enqueueLiveActivitySync(
Effect.sync(() => {
if (!activeActivity || activeActivity.instance !== activity) {
return;
}
activeActivity = {
...activeActivity,
remoteTokenRetryScheduled: false,
lastRemoteTokenRegistrationAttemptAt: null,
};
retryRemoteTokenRegistration(activity);
}),
),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning("live activity token retry failed", error);
}),
),
),
)
.catch((error: unknown) => {
logLiveActivityWarning("unexpected live activity token retry failure", error);
});
}
export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
void,
unknown,
ManagedRelayClient
> {
return enqueueLiveActivitySync(
Effect.gen(function* () {
if (!activeActivity || !canUseLocalLiveActivities()) {
return;
}
const activity = activeActivity.instance;
activeActivity = {
...activeActivity,
remoteTokenRegistered: false,
remoteTokenRetryScheduled: false,
lastRemoteTokenRegistrationAttemptAt: currentTimeMillis(),
};
yield* registerRemoteActivityToken(activity).pipe(
Effect.flatMap((registered) =>
Effect.sync(() => {
if (!registered) {
scheduleRemoteTokenRegistrationRetry(activity);
}
}),
),
Effect.catch((error) =>
Effect.sync(() => {
logLiveActivityWarning("live activity token refresh failed; retry scheduled", error);
scheduleRemoteTokenRegistrationRetry(activity);
}),
),
);
}),
);
}
function endActiveActivity(
finalState: AgentAwarenessState | null,
reason: string,
): Effect.Effect<void, unknown> {
const active = activeActivity;
if (!active) {
return Effect.void;
}
activeActivity = null;
logLiveActivityDebug("ending live activity", {
reason,
finalPhase: finalState?.phase ?? null,
});
if (finalState) {
const now = currentDateTime();
return runLiveActivityOperation(
"end",
Effect.tryPromise({
try: () =>
active.instance.end(
after(
DateTime.toDateUtc(DateTime.add(now, { milliseconds: FINAL_ACTIVITY_DISMISSAL_MS })),
),
toActivityProps([finalState]),
DateTime.toDateUtc(now),
),
catch: (error) => error,
}),
).pipe(Effect.asVoid);
}
return runLiveActivityOperation(
"end",
Effect.tryPromise({
try: () => active.instance.end("immediate"),
catch: (error) => error,
}),
).pipe(Effect.asVoid);
}
type LiveActivityOperationResult<T> =
| {
readonly ok: true;
readonly value: T;
}
| {
readonly ok: false;
};
function runLiveActivityOperation<T>(
operationName: "start" | "update" | "end",
operation: Effect.Effect<T, unknown>,
): Effect.Effect<LiveActivityOperationResult<T>> {
return operation.pipe(
Effect.match({
onSuccess: (value) => ({ ok: true, value }) as const,
onFailure: (error): LiveActivityOperationResult<T> => {
if (
(operationName === "end" || operationName === "update") &&
isMissingNativeLiveActivityError(error)
) {
logLiveActivityWarning(
`live activity ${operationName} skipped; native activity was already gone`,
error,
);
return { ok: false };
}
logLiveActivityWarning(
"live activity operation failed; disabling local live activities",
error,
);
localLiveActivitiesEnabled = false;
activeActivity = null;
environmentStates.clear();
return { ok: false };
},
}),
);
}
function isMissingNativeLiveActivityError(error: unknown): boolean {
return error instanceof Error && error.message.includes("Can't find live activity with id:");
}
export function __resetAgentLiveActivitiesForTest(): void {
localLiveActivitiesEnabled = true;
activeActivity = null;
environmentStates.clear();
}
@@ -1,4 +1,4 @@
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
@@ -8,7 +8,6 @@ import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { endAllAgentLiveActivities } from "./liveActivityController";
import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
@@ -20,10 +19,6 @@ vi.mock("../cloud/linkEnvironment", () => ({
linkEnvironmentToCloud: vi.fn(() => Effect.void),
}));
vi.mock("./liveActivityController", () => ({
endAllAgentLiveActivities: vi.fn(() => Effect.void),
}));
vi.mock("./remoteRegistration", () => ({
refreshAgentAwarenessRegistration: vi.fn(() => Effect.void),
}));
@@ -56,7 +51,7 @@ describe("liveActivityPreferences", () => {
vi.clearAllMocks();
});
it("pushes disabled Live Activity preferences to local and relay registrations", async () => {
it("pushes disabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
@@ -66,7 +61,6 @@ describe("liveActivityPreferences", () => {
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(endAllAgentLiveActivities).toHaveBeenCalledTimes(1);
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
@@ -74,7 +68,7 @@ describe("liveActivityPreferences", () => {
});
});
it("pushes enabled Live Activity preferences without ending active local activities", async () => {
it("pushes enabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
@@ -84,7 +78,6 @@ describe("liveActivityPreferences", () => {
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(endAllAgentLiveActivities).not.toHaveBeenCalled();
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
@@ -5,7 +5,6 @@ import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { endAllAgentLiveActivities } from "./liveActivityController";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
export function setLiveActivityUpdatesEnabled(input: {
@@ -19,10 +18,6 @@ export function setLiveActivityUpdatesEnabled(input: {
catch: (error) => error,
});
if (!input.enabled) {
yield* endAllAgentLiveActivities();
}
yield* refreshAgentAwarenessRegistration();
const clerkToken = input.clerkToken;
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
extractAgentNotificationDeepLink,
@@ -2,7 +2,7 @@
import * as NodeCrypto from "node:crypto";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import Constants from "expo-constants";
import * as Effect from "effect/Effect";
@@ -18,6 +18,7 @@ import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
__resetAgentAwarenessRemoteRegistrationForTest,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
registerAgentAwarenessConnection,
@@ -29,6 +30,9 @@ import {
import * as Notifications from "expo-notifications";
const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []),
}));
vi.mock("expo-constants", () => ({
default: {
@@ -43,6 +47,12 @@ vi.mock("expo-widgets", () => ({
addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
}));
vi.mock("../../widgets/AgentActivity", () => ({
default: {
getInstances: widgetMocks.getInstances,
},
}));
vi.mock("expo-notifications", () => ({
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
@@ -158,6 +168,8 @@ describe("makeRelayDeviceRegistrationRequest", () => {
secureStore.clear();
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
});
it("preserves disabled Live Activity preferences in relay registrations", () => {
@@ -262,6 +274,25 @@ describe("makeRelayDeviceRegistrationRequest", () => {
).resolves.toBe(false);
});
it("registers APNS-started Live Activities for relay updates without mutating them locally", async () => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
start: vi.fn(),
update: vi.fn(),
end: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
await runRegistrationEffect(refreshActiveLiveActivityRemoteRegistration());
expect(activity.getPushToken).toHaveBeenCalled();
expect(activity.start).not.toHaveBeenCalled();
expect(activity.update).not.toHaveBeenCalled();
expect(activity.end).not.toHaveBeenCalled();
});
it("refreshes APNs registration for connected environments after settings changes", async () => {
registerAgentAwarenessConnection(savedConnection());
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -17,14 +17,16 @@ import {
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
} from "../../lib/storage";
import type { AgentActivityProps } from "../../widgets/AgentActivity";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
let pushTokenSubscription: { remove: () => void } | null = null;
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
@@ -73,10 +75,18 @@ export function setAgentAwarenessRelayTokenProvider(
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
return;
}
ensurePushToStartListener();
ensurePushTokenListener();
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after cloud sign-in failed",
);
if (isExistingIdentity) {
return;
}
@@ -310,6 +320,10 @@ export function registerAgentAwarenessConnection(connection: SavedRemoteConnecti
ensurePushToStartListener();
ensurePushTokenListener();
runRegistrationInBackground(registerDevice(), "device registration failed");
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after environment connection failed",
);
}
function removeAgentAwarenessConnection(environmentId: EnvironmentId): void {
@@ -326,6 +340,10 @@ export function unregisterAllAgentAwarenessConnections(): void {
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
}
export function refreshAgentAwarenessRegistration(): Effect.Effect<
@@ -348,6 +366,10 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
relayTokenProvider = null;
relayTokenProviderIdentity = null;
}
@@ -445,3 +467,57 @@ function registerLiveActivityPushTokenValue(input: {
return registered;
});
}
function scheduleActiveLiveActivityRegistrationRetry(): void {
if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
return;
}
activeLiveActivityRegistrationRetry = setTimeout(() => {
activeLiveActivityRegistrationRetry = null;
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity token retry failed",
);
}, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
}
export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
void,
never,
ManagedRelayClient
> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
return;
}
const activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (error) => error,
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("active live activity lookup failed", error);
return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
}),
),
);
const registrationResults = yield* Effect.forEach(activities, (activity) =>
registerLiveActivityPushToken({ activity }).pipe(
Effect.map((registered) => !registered),
Effect.catch((error) =>
Effect.sync(() => {
logRegistrationError("active live activity token registration failed", error);
return true;
}),
),
),
);
if (registrationResults.some(Boolean)) {
scheduleActiveLiveActivityRegistrationRetry();
}
});
}
@@ -1,59 +0,0 @@
import { shellSnapshotStateAtom } from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import {
endAllAgentLiveActivities,
endEnvironmentLiveActivities,
syncAgentLiveActivitiesForSnapshot,
} from "./liveActivityController";
import {
registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections,
} from "./remoteRegistration";
const environmentUnsubscribers = new Map<EnvironmentId, () => void>();
export function startAgentAwarenessForEnvironment(connection: SavedRemoteConnection): void {
const { environmentId } = connection;
if (environmentUnsubscribers.has(environmentId)) {
return;
}
registerAgentAwarenessConnection(connection);
const sync = () => {
const state = appAtomRegistry.get(shellSnapshotStateAtom(environmentId));
void mobileRuntime
.runPromise(
syncAgentLiveActivitiesForSnapshot({
environmentId,
snapshot: state.data,
}),
)
.catch(() => undefined);
};
const unsubscribe = appAtomRegistry.subscribe(shellSnapshotStateAtom(environmentId), sync);
environmentUnsubscribers.set(environmentId, unsubscribe);
sync();
}
export function stopAgentAwarenessForEnvironment(environmentId: EnvironmentId): void {
environmentUnsubscribers.get(environmentId)?.();
environmentUnsubscribers.delete(environmentId);
unregisterAgentAwarenessConnection(environmentId);
void mobileRuntime.runPromise(endEnvironmentLiveActivities(environmentId)).catch(() => undefined);
}
export function stopAllAgentAwareness(): void {
for (const unsubscribe of environmentUnsubscribers.values()) {
unsubscribe();
}
environmentUnsubscribers.clear();
unregisterAllAgentAwarenessConnections();
void mobileRuntime.runPromise(endAllAgentLiveActivities()).catch(() => undefined);
}
@@ -9,7 +9,6 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function CloudAuthBridge(props: { readonly children: ReactNode }) {
@@ -52,11 +51,6 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
readClerkToken: tokenProvider,
}),
);
if (!previous || previous.userId !== userId) {
void mobileRuntime
.runPromise(refreshActiveLiveActivityRemoteRegistration())
.catch(() => undefined);
}
}, [getToken, isLoaded, isSignedIn, userId]);
useEffect(
+1 -1
View File
@@ -2,7 +2,7 @@
import * as NodeCrypto from "node:crypto";
import { vi } from "vitest";
import { vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -1,4 +1,4 @@
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -147,10 +147,6 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return "Relay rejected an expired agent activity publish proof.";
case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayQuotaExceededError":
return `Relay quota exceeded for ${error.resource} (limit ${error.limit}).`;
case "RelayRateLimitedError":
return `Relay rate limit exceeded for ${error.operation}; retry in ${error.retryAfterSeconds} seconds.`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
}
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import { resolveCloudPublicConfig } from "./publicConfig";
@@ -10,6 +10,7 @@ import type {
import {
detectComposerTrigger,
replaceTextRange,
serializeComposerMentionPath,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
@@ -418,7 +419,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") {
+1 -1
View File
@@ -1,5 +1,5 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => {
const values = new Map<string, string>();
@@ -6,7 +6,7 @@ import {
setManagedRelaySession,
} from "@t3tools/client-runtime";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
import { beforeEach, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => {
const environmentConnection = {
@@ -45,8 +45,8 @@ const mocks = vi.hoisted(() => {
getEnvironmentSession: vi.fn(() => null),
setEnvironmentSession: vi.fn(),
notifyEnvironmentConnectionListeners: vi.fn(),
stopAgentAwarenessForEnvironment: vi.fn(),
startAgentAwarenessForEnvironment: vi.fn(),
unregisterAgentAwarenessConnection: vi.fn(),
registerAgentAwarenessConnection: vi.fn(),
shellSnapshotInvalidate: vi.fn(),
shellSnapshotMarkPending: vi.fn(),
environmentRuntimeInvalidate: vi.fn(),
@@ -118,10 +118,10 @@ vi.mock("./environment-session-registry", () => ({
setEnvironmentSession: mocks.setEnvironmentSession,
}));
vi.mock("../features/agent-awareness/shellLiveActivitySync", () => ({
startAgentAwarenessForEnvironment: mocks.startAgentAwarenessForEnvironment,
stopAgentAwarenessForEnvironment: mocks.stopAgentAwarenessForEnvironment,
stopAllAgentAwareness: vi.fn(),
vi.mock("../features/agent-awareness/remoteRegistration", () => ({
registerAgentAwarenessConnection: mocks.registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection: mocks.unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections: vi.fn(),
}));
vi.mock("../features/terminal/terminalDebugLog", () => ({
@@ -217,7 +217,7 @@ describe("mobile remote environment registry effects", () => {
expect(mocks.subscribeTerminalMetadata).toHaveBeenCalledWith(
expect.objectContaining({ environmentId: connection.environmentId }),
);
expect(mocks.startAgentAwarenessForEnvironment).toHaveBeenCalledWith(connection);
expect(mocks.registerAgentAwarenessConnection).toHaveBeenCalledWith(connection);
expect(mocks.environmentConnection.ensureBootstrapped).toHaveBeenCalledTimes(1);
}),
);
@@ -354,7 +354,7 @@ describe("mobile remote environment registry effects", () => {
);
expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1);
expect(mocks.subscribeTerminalMetadata).not.toHaveBeenCalled();
expect(mocks.startAgentAwarenessForEnvironment).not.toHaveBeenCalled();
expect(mocks.registerAgentAwarenessConnection).not.toHaveBeenCalled();
}),
);
@@ -376,7 +376,7 @@ describe("mobile remote environment registry effects", () => {
expect(mocks.environmentConnection.ensureBootstrapped).toHaveBeenCalledTimes(1);
expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1);
expect(mocks.subscribeTerminalMetadata).not.toHaveBeenCalled();
expect(mocks.startAgentAwarenessForEnvironment).not.toHaveBeenCalled();
expect(mocks.registerAgentAwarenessConnection).not.toHaveBeenCalled();
expect(mocks.environmentRuntimePatch).toHaveBeenCalledWith(
{ environmentId: connection.environmentId },
expect.any(Function),
@@ -419,7 +419,9 @@ describe("mobile remote environment registry effects", () => {
yield* disconnectEnvironment(connection.environmentId, { removeSaved: true });
expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1);
expect(mocks.stopAgentAwarenessForEnvironment).toHaveBeenCalledWith(connection.environmentId);
expect(mocks.unregisterAgentAwarenessConnection).toHaveBeenCalledWith(
connection.environmentId,
);
expect(mocks.clearSavedConnection).toHaveBeenCalledWith(connection.environmentId);
expect(mocks.clearCachedShellSnapshot).toHaveBeenCalledWith(connection.environmentId);
expect(mocks.clearCachedShellSnapshotMetadata).toHaveBeenCalledWith(connection.environmentId);
@@ -55,10 +55,10 @@ import {
resetSourceControlDiscoveryState,
} from "./use-source-control-discovery";
import {
startAgentAwarenessForEnvironment,
stopAgentAwarenessForEnvironment,
stopAllAgentAwareness,
} from "../features/agent-awareness/shellLiveActivitySync";
registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections,
} from "../features/agent-awareness/remoteRegistration";
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
import {
clearCachedShellSnapshotMetadata,
@@ -200,7 +200,7 @@ export function disconnectEnvironment(
}
terminalMetadataUnsubscribers.get(environmentId)?.();
terminalMetadataUnsubscribers.delete(environmentId);
stopAgentAwarenessForEnvironment(environmentId);
unregisterAgentAwarenessConnection(environmentId);
if (!options?.preserveShellSnapshot) {
shellSnapshotManager.invalidate({ environmentId });
}
@@ -454,7 +454,7 @@ export function connectSavedEnvironment(
terminalDebugLog("registry:terminal-metadata-subscribed", {
environmentId: connection.environmentId,
});
startAgentAwarenessForEnvironment(toStableSavedRemoteConnection(activeConnection));
registerAgentAwarenessConnection(toStableSavedRemoteConnection(activeConnection));
notifyEnvironmentConnectionListeners();
});
}
@@ -615,7 +615,7 @@ export function useRemoteEnvironmentBootstrap() {
}
terminalMetadataUnsubscribers.clear();
environmentConnectionAttempts.clear();
stopAllAgentAwareness();
unregisterAllAgentAwarenessConnections();
environmentRuntimeManager.invalidate();
shellSnapshotManager.invalidate();
resetSourceControlDiscoveryState();
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
vi.mock("@expo/ui/swift-ui", () => ({
HStack: "HStack",
@@ -161,7 +161,7 @@ class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<Orchestra
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
+2 -3
View File
@@ -38,12 +38,11 @@
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/bun": "1.3.14",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"vite-plus": "catalog:",
"vitest": "catalog:"
"vite-plus": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
+31 -9
View File
@@ -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",
}),
);
@@ -197,6 +195,31 @@ const buildCmd = Command.make(
// publish subcommand
// ---------------------------------------------------------------------------
interface PublishCommandConfig {
readonly access: string;
readonly tag: string;
readonly provenance: boolean;
readonly dryRun: boolean;
}
const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
const args = [
"publish",
"--filter",
"t3",
"--access",
config.access,
"--tag",
config.tag,
"--no-git-checks",
];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
return args;
};
const publishCmd = Command.make(
"publish",
{
@@ -262,17 +285,16 @@ const publishCmd = Command.make(
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: npm publish
// Use: pnpm publish from the workspace root so pnpm-only workspace
// config, including override selectors, is interpreted correctly.
() =>
Effect.gen(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
const args = createVpPmPublishArgs(config);
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
ChildProcess.make("vp", ["pm", ...args], {
cwd: repoRoot,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "./ServerSecretStore.ts";
+2 -2
View File
@@ -11,7 +11,7 @@ export class CheckpointUnavailableError extends Schema.TaggedErrorClass<Checkpoi
threadId: Schema.String,
turnCount: Schema.Number,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -27,7 +27,7 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -35,7 +35,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
@@ -1,5 +1,5 @@
import { describe, expect, it } from "@effect/vitest";
import { vi } from "vitest";
import { vi } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -152,9 +152,7 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
const nextConfigKey = runtimeConfigKey(config);
const active = yield* Ref.get(activeRef);
if (active?.configKey === nextConfigKey) {
const isRunning = yield* active.child.isRunning.pipe(
Effect.catch(() => Effect.succeed(false)),
);
const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
if (isRunning) {
return {
status: "running",
@@ -47,7 +47,7 @@ class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnostics
"ProcessDiagnosticsError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
@@ -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(
@@ -59,7 +59,6 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command,
args,
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
+7 -7
View File
@@ -702,7 +702,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const canonicalizeExistingPath = (value: string) =>
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
const normalizeStatusCacheKey = canonicalizeExistingPath;
const nonRepositoryStatusDetails = {
isRepo: false,
@@ -766,7 +766,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
if (details.isDefaultBranch && latest.state !== "open") return null;
return toStatusPr(latest);
}),
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
)
: null;
@@ -788,7 +788,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
cwd: string,
@@ -972,7 +972,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
) {
const terms = yield* sourceControlProvider(cwd).pipe(
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
Effect.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
);
const summary = summarizeGitActionResult(result, terms);
let latestOpenPr: PullRequestInfo | null = null;
@@ -1016,7 +1016,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
upstreamRef: finalBranchContext.upstreamRef,
}).pipe(
Effect.flatMap((headContext) => findOpenPr(cwd, headContext)),
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
}
@@ -1080,7 +1080,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
if (defaultFromProvider) {
return defaultFromProvider;
@@ -1686,7 +1686,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const changeRequestTerms = wantsPr
? yield* sourceControlProvider(input.cwd).pipe(
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
Effect.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
)
: null;
+8 -18
View File
@@ -156,8 +156,8 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
otlpTracesUrl,
}),
),
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
Effect.orElseSucceed(() =>
HttpServerResponse.text("Trace export failed.", { status: 502 }),
),
);
}).pipe(
@@ -205,9 +205,7 @@ export const attachmentsRouteLayer = HttpRouter.add(
}
const fileSystem = yield* FileSystem.FileSystem;
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
return HttpServerResponse.text("Not Found", { status: 404 });
}
@@ -218,9 +216,7 @@ export const attachmentsRouteLayer = HttpRouter.add(
"Cache-Control": "public, max-age=31536000, immutable",
},
}).pipe(
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
}).pipe(
Effect.catchTags({
@@ -265,9 +261,7 @@ export const projectFaviconRouteLayer = HttpRouter.add(
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
}).pipe(
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
}).pipe(
Effect.catchTags({
@@ -337,14 +331,12 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
if (!indexData) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
@@ -355,9 +347,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
if (!data) {
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}
+6 -6
View File
@@ -7,7 +7,7 @@ export class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<
"OrchestrationCommandJsonParseError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -19,7 +19,7 @@ export class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<Orc
"OrchestrationCommandDecodeError",
{
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -32,7 +32,7 @@ export class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass<
{
commandType: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -45,7 +45,7 @@ export class OrchestrationCommandPreviouslyRejectedError extends Schema.TaggedEr
{
commandId: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -58,7 +58,7 @@ export class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass<O
{
eventType: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -71,7 +71,7 @@ export class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<
{
listener: Schema.Literals(["read-model", "domain-event"]),
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -335,7 +335,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
const attachmentsRootDir = serverConfig.attachmentsDir;
const readAttachmentRootEntries = fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
function* (threadSegment: string, entry: string) {
@@ -397,9 +397,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem
.stat(absolutePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
return;
}
@@ -344,6 +344,26 @@ function runtimeEventToActivities(
];
}
case "tool.denied": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "error",
kind: "tool.denied",
summary: `Tool denied: ${event.payload.toolName}`,
payload: {
toolName: event.payload.toolName,
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "runtime.warning": {
return [
{
@@ -351,7 +371,9 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "info",
kind: "runtime.warning",
summary: "Runtime warning",
// Use the adapter-supplied message as the row label so the work log
// shows what the warning was about, not a generic "Runtime warning".
summary: truncateDetail(event.payload.message, 120),
payload: {
message: truncateDetail(event.payload.message),
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
+4 -4
View File
@@ -10,7 +10,7 @@ export class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlE
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -23,7 +23,7 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -72,7 +72,7 @@ export class ProviderSessionRepositoryValidationError extends Schema.TaggedError
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -85,7 +85,7 @@ export class ProviderSessionRepositoryPersistenceError extends Schema.TaggedErro
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -80,9 +80,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
if (!isPathWithinProject(projectCwd, candidate)) {
continue;
}
const stats = yield* fileSystem
.stat(candidate)
.pipe(Effect.catch(() => Effect.succeed(null)));
const stats = yield* fileSystem.stat(candidate).pipe(Effect.orElseSucceed(() => null));
if (stats?.type === "File") {
return candidate;
}
@@ -105,7 +103,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
const sourcePath = path.join(cwd, sourceFile);
const source = yield* fileSystem
.readFileString(sourcePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
if (!source) {
continue;
}
@@ -23,7 +23,6 @@ const git = (cwd: string, args: ReadonlyArray<string>) =>
return yield* processRunner.run({
command: "git",
args: ["-C", cwd, ...args],
shell: process.platform === "win32",
});
}).pipe(Effect.provide(ProcessRunner.layer));
@@ -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) {
+11 -11
View File
@@ -11,7 +11,7 @@ export class ProviderAdapterValidationError extends Schema.TaggedErrorClass<Prov
provider: Schema.String,
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -27,7 +27,7 @@ export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass
{
provider: Schema.String,
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -43,7 +43,7 @@ export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<P
{
provider: Schema.String,
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -60,7 +60,7 @@ export class ProviderAdapterRequestError extends Schema.TaggedErrorClass<Provide
provider: Schema.String,
method: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -77,7 +77,7 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
provider: Schema.String,
threadId: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -93,7 +93,7 @@ export class ProviderValidationError extends Schema.TaggedErrorClass<ProviderVal
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -108,7 +108,7 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUn
"ProviderUnsupportedError",
{
provider: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -129,7 +129,7 @@ export class ProviderInstanceNotFoundError extends Schema.TaggedErrorClass<Provi
"ProviderInstanceNotFoundError",
{
instanceId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -148,7 +148,7 @@ export class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverE
driver: Schema.String,
instanceId: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -163,7 +163,7 @@ export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<Provid
"ProviderSessionNotFoundError",
{
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -179,7 +179,7 @@ export class ProviderSessionDirectoryPersistenceError extends Schema.TaggedError
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -972,6 +972,52 @@ function sdkNativeMethod(message: SDKMessage): string {
return `claude/${message.type}`;
}
// Discriminator/identity keys carry no human-readable content; everything else
// on an unmodeled SDK message is potentially worth surfacing in the work log.
const SDK_MESSAGE_NOISE_KEYS = new Set([
"type",
"subtype",
"uuid",
"parent_uuid",
"session_id",
"parent_tool_use_id",
"request_id",
]);
// Pull the salient scalar content out of a message the adapter doesn't model
// yet, so the work-log row shows what actually arrived (e.g. a notification's
// text) instead of an opaque "unhandled subtype" placeholder. Nested structures
// are left to the full payload retained in the event's `detail`.
function previewUnknownSdkContent(message: unknown): string | undefined {
if (!message || typeof message !== "object") {
return undefined;
}
const parts: string[] = [];
for (const [key, value] of Object.entries(message as Record<string, unknown>)) {
if (SDK_MESSAGE_NOISE_KEYS.has(key)) {
continue;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed.length > 0) {
parts.push(`${key}: ${trimmed}`);
}
} else if (typeof value === "number" || typeof value === "boolean") {
parts.push(`${key}: ${String(value)}`);
}
}
if (parts.length === 0) {
return undefined;
}
const joined = parts.join(" · ");
return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;
}
function describeUnknownSdkMessage(kind: string, message: unknown): string {
const preview = previewUnknownSdkContent(message);
return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;
}
function sdkNativeItemId(message: SDKMessage): string | undefined {
if (message.type === "assistant") {
const maybeId = (message.message as { id?: unknown }).id;
@@ -2267,10 +2313,31 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "thinking_tokens":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
type: "tool.denied",
payload: {
toolName: message.tool_name,
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.decision_reason ? { reason: message.decision_reason } : {}),
...(message.agent_id ? { agentId: message.agent_id } : {}),
},
});
return;
case "mirror_error":
yield* emitRuntimeError(
context,
`Claude workspace mirror error: ${message.error}`,
message,
);
return;
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude system message subtype '${message.subtype}'.`,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
message,
);
return;
@@ -2384,7 +2451,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude SDK message type '${message.type}'.`,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
message,
);
return;
@@ -347,7 +347,7 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
const fileSystem = yield* FileSystem.FileSystem;
const realCommandPath = yield* fileSystem
.realPath(resolvedCommandPath)
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
.pipe(Effect.orElseSucceed(() => resolvedCommandPath));
return resolver.resolve({
...options,
realCommandPath,
@@ -406,7 +406,7 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
const response = yield* client.execute(request).pipe(
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
Effect.catch(() => Effect.succeed(Option.none())),
Effect.orElseSucceed(() => Option.none()),
);
if (Option.isNone(response)) {
return null;
@@ -417,7 +417,7 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
}
const payload = yield* httpResponse.json.pipe(
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
return payload ? nonEmptyString(payload.version) : null;
});
+1 -3
View File
@@ -35,9 +35,7 @@ export const make = Effect.fn("makeReviewService")(function* () {
const git = yield* GitVcsDriver.GitVcsDriver;
const canonicalizePath = (value: string) =>
fileSystem
.realPath(path.resolve(value))
.pipe(Effect.catch(() => Effect.succeed(path.resolve(value))));
fileSystem.realPath(path.resolve(value)).pipe(Effect.orElseSucceed(() => path.resolve(value)));
const isWithinRoot = (candidate: string, root: string) => {
const relative = path.relative(root, candidate);
@@ -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(
@@ -21,7 +21,7 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -37,7 +37,7 @@ export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -359,7 +359,7 @@ function responseError(
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.catch(() => Effect.succeed("")),
Effect.orElseSucceed(() => ""),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketApiError({
@@ -524,7 +524,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
);
const readConfigValueNullable = (cwd: string, key: string) =>
git.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
readonly cwd: string;
@@ -544,7 +544,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
if (!input.isCrossRepository) {
const remoteName = yield* git
.resolvePrimaryRemoteName(input.cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
if (remoteName) return remoteName;
}
@@ -575,7 +575,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
host: Option.some("bitbucket.org"),
detail: Option.none<string>(),
})),
Effect.catch(() => Effect.succeed(authFromConfig(config))),
Effect.orElseSucceed(() => authFromConfig(config)),
),
listPullRequests: (input) =>
resolveRepository(input).pipe(
@@ -685,8 +685,8 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
{
repository: getRepositoryFromLocator(locator),
branchingModel: getBranchingModelFromLocator(locator).pipe(
Effect.catch(() =>
Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
Effect.orElseSucceed(
(): typeof RawBitbucketBranchingModelSchema.Type | null => null,
),
),
},
+1 -1
View File
@@ -19,7 +19,7 @@ const DEFAULT_TIMEOUT_MS = 30_000;
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
@@ -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."),
},
);
});
@@ -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`).",
+1 -1
View File
@@ -18,7 +18,7 @@ const DEFAULT_TIMEOUT_MS = 30_000;
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
@@ -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<GitLabCli.GitLabCliShape>) {
@@ -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" },
],
);
});
@@ -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;
@@ -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") {
@@ -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<string>;
readonly authArgs: ReadonlyArray<string>;
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<SourceControlCliDiscoverySpec["refineUnknownRemote"]>;
};
interface DiscoveryProbeResult {
readonly kind: SourceControlProviderKind;
readonly label: string;
@@ -135,6 +150,12 @@ export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): 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<SourceControlProviderDiscoverySpec>;
readonly process: VcsProcess.VcsProcessShape;
readonly cwd: string;
readonly context: SourceControlProvider.SourceControlProviderContext | null;
}): Effect.fn.Return<SourceControlProvider.SourceControlProviderContext | null> {
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.orElseSucceed(() => null),
),
);
const provider = providers.find((candidate) => candidate !== null);
return provider ? { ...context, provider } : context;
},
);
@@ -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<VcsProcess.VcsProcessShape>;
}) {
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({
@@ -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,
});
},
);
@@ -277,12 +277,10 @@ export const make = Effect.fn("makeSourceControlRepositoryService")(function* ()
})
.pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
);
if (!hasCommits) {
const details = yield* git
.statusDetails(input.cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
@@ -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<typeof AzureDevOpsPullRequestSchema>,
): 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<typeof AzureDevOpsPullRequestSchema>,
): 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),
@@ -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<GitHubAuthStatusAccount>;
}
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>,
): GitHubAuthStatusAccount | undefined {
return (
accounts.find((account) => account.authenticated && account.active) ??
accounts.find((account) => account.authenticated)
);
}
@@ -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<GitLabAuthStatusHost> {
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>,
): GitLabAuthStatusHost | undefined {
return hosts.find((host) => host.account !== null);
}
+1 -1
View File
@@ -19,7 +19,7 @@ const ClaudeJsonSchema = Schema.Struct({
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
}) {}
const hash = (value: string) =>
@@ -62,7 +62,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
const payload = yield* request.json.pipe(
Effect.map((body) => body as RecordedBatchRequest["body"]),
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
capturedRequests.push({ path: request.url, body: payload });
@@ -1,3 +1,5 @@
/// <reference types="bun" />
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { PtyAdapter } from "../Services/PTY.ts";
+3 -4
View File
@@ -64,7 +64,7 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
"TerminalSubprocessCheckError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
terminalPid: Schema.Number,
command: Schema.Literals(["powershell", "pgrep", "ps"]),
},
@@ -74,7 +74,7 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
"TerminalProcessSignalError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
signal: Schema.Literals(["SIGTERM", "SIGKILL"]),
},
) {}
@@ -519,7 +519,6 @@ function windowsInspectSubprocess(
timeout: "1500 millis",
maxOutputBytes: 32_768,
outputMode: "truncate",
shell: process.platform === "win32",
timeoutBehavior: "timedOutResult",
});
}).pipe(
@@ -1290,7 +1289,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const threadPrefix = `${toSafeThreadId(threadId)}_`;
const entries = yield* fileSystem
.readDirectory(logsDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
yield* Effect.forEach(
entries.filter(
(name) =>
+1 -1
View File
@@ -16,7 +16,7 @@ import * as Context from "effect/Context";
export class PtySpawnError extends Schema.TaggedErrorClass<PtySpawnError>()("PtySpawnError", {
adapter: Schema.String,
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
}) {}
export interface PtyExitEvent {
@@ -140,9 +140,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
+1 -1
View File
@@ -403,7 +403,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
"GitVcsDriver.detectRepository.commonDir",
cwd,
["rev-parse", "--git-common-dir"],
).pipe(Effect.catch(() => Effect.succeed(null)));
).pipe(Effect.orElseSucceed(() => null));
return {
kind: "git" as const,
+29 -37
View File
@@ -885,7 +885,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const remoteNames = yield* runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNames),
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
Effect.orElseSucceed((): ReadonlyArray<string> => []),
);
return (
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
@@ -996,7 +996,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
cwd: string,
branchName: string,
) {
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.catch(() => Effect.succeed([])));
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => []));
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);
return parsedRemoteRef?.branchName ?? branchName;
});
@@ -1042,7 +1042,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return pushDefaultRemote;
}
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null)));
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null));
});
const ensureRemote: GitVcsDriver.GitVcsDriverShape["ensureRemote"] = Effect.fn("ensureRemote")(
@@ -1090,7 +1090,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
).pipe(Effect.map((stdout) => stdout.trim()));
const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
const defaultBranch =
primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);
@@ -1231,7 +1231,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
allowNonZeroExit: true,
},
),
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
originRemoteExists(cwd).pipe(Effect.orElseSucceed(() => false)),
],
{ concurrency: "unbounded" },
);
@@ -1276,9 +1276,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const fallbackAheadCount =
!upstreamRef && refName
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(
Effect.catch(() => Effect.succeed(0)),
)
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0))
: null;
if (fallbackAheadCount !== null) {
@@ -1294,9 +1292,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
aheadOfDefaultCount =
fallbackAheadCount !== null
? fallbackAheadCount
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(
Effect.catch(() => Effect.succeed(0)),
);
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0));
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
@@ -1494,11 +1490,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
if (comparableBaseBranch) {
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
if (!publishRemoteName) {
return {
@@ -1508,7 +1504,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
);
if (hasRemoteBranch) {
return {
@@ -1545,7 +1541,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
);
if (currentUpstream) {
yield* runGit("GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, [
@@ -1716,7 +1712,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
input.baseRef ??
(branch
? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
Effect.orElseSucceed(() => null),
)
: null);
@@ -1729,18 +1725,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
appendTruncationMarker: true,
},
).pipe(
Effect.catch(() =>
Effect.succeed({
exitCode: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
),
Effect.orElseSucceed(() => ({
exitCode: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
})),
);
const dirtyUntracked = yield* readUntrackedReviewDiffs(input.cwd).pipe(
Effect.catch(() => Effect.succeed({ diff: "", truncated: false })),
Effect.orElseSucceed(() => ({ diff: "", truncated: false })),
);
const dirtyDiff = [dirtyTrackedResult.stdout.trimEnd(), dirtyUntracked.diff.trimEnd()]
.filter((diff) => diff.length > 0)
@@ -1757,15 +1751,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
appendTruncationMarker: true,
},
).pipe(
Effect.catch(() =>
Effect.succeed({
exitCode: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
),
Effect.orElseSucceed(() => ({
exitCode: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
})),
)
: null;
const baseDiff = baseResult?.stdout ?? "";
@@ -1827,7 +1819,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const listRefs: GitVcsDriver.GitVcsDriverShape["listRefs"] = Effect.fn("listRefs")(
function* (input) {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
Effect.orElseSucceed(() => new Map<string, number>()),
);
const localBranchResult = yield* executeGit(
"GitVcsDriver.listRefs.branchNoColor",
@@ -1970,7 +1962,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const candidatePath = line.slice("worktree ".length);
const exists = yield* fileSystem.stat(candidatePath).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
);
currentPath = exists ? candidatePath : null;
} else if (line.startsWith("branch refs/heads/") && currentPath) {
@@ -392,5 +392,20 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
}),
);
it.effect("returns an empty listing when the OS denies directory access", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(denied);
const result = yield* workspaceEntries.browse({
partialPath: appendSeparator(cwd),
});
expect(result).toEqual({ parentPath: cwd, entries: [] });
}),
);
});
});
@@ -188,7 +188,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const isInsideVcsWorkTree = (cwd: string): Effect.Effect<boolean> =>
vcsRegistry.detect({ cwd }).pipe(
Effect.map((handle) => handle !== null),
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
);
const filterVcsIgnoredPaths = (
@@ -200,23 +200,23 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
handle
? handle.driver.filterIgnoredPaths(cwd, relativePaths).pipe(
Effect.map((paths) => [...paths]),
Effect.catch(() => Effect.succeed(relativePaths)),
Effect.orElseSucceed(() => relativePaths),
)
: Effect.succeed(relativePaths),
),
Effect.catch(() => Effect.succeed(relativePaths)),
Effect.orElseSucceed(() => relativePaths),
);
const buildWorkspaceIndexFromVcs = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromVcs")(
function* (cwd: string) {
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.catch(() => Effect.succeed(null)));
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.orElseSucceed(() => null));
if (!vcs) {
return null;
}
const listedFiles = yield* vcs.driver
.listWorkspaceFiles(cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
if (!listedFiles) {
return null;
@@ -431,7 +431,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")(
function* (cwd) {
const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
Effect.catch(() => Effect.succeed(cwd)),
Effect.orElseSucceed(() => cwd),
);
yield* Cache.invalidate(workspaceIndexCache, cwd);
if (normalizedCwd !== cwd) {
@@ -457,7 +457,18 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
}),
});
}).pipe(
// The user can deny macOS TCC prompts for the target dir (Documents,
// Downloads, Music, etc.); surface an empty listing instead of an
// error so the caller doesn't retry-loop the prompt.
Effect.catchIf(
(error) => {
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
return code === "EACCES" || code === "EPERM";
},
() => Effect.succeed<Dirent[]>([]),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
@@ -132,7 +132,7 @@ it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
const escapedPath = path.resolve(cwd, "..", "escape.md");
const escapedStat = yield* fileSystem
.stat(escapedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
expect(escapedStat).toBeNull();
}),
);
@@ -37,7 +37,7 @@ export const makeWorkspacePaths = Effect.gen(function* () {
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
let workspaceStat = yield* fileSystem
.stat(normalizedWorkspaceRoot)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
if (!workspaceStat && options?.createIfMissing) {
yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
Effect.mapError(
@@ -50,7 +50,7 @@ export const makeWorkspacePaths = Effect.gen(function* () {
);
workspaceStat = yield* fileSystem
.stat(normalizedWorkspaceRoot)
.pipe(Effect.catch(() => Effect.succeed(null)));
.pipe(Effect.orElseSucceed(() => null));
}
if (!workspaceStat) {
return yield* new WorkspaceRootNotExistsError({
@@ -23,7 +23,7 @@ export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntr
cwd: Schema.String,
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
@@ -34,7 +34,7 @@ export class WorkspaceEntriesBrowseError extends Schema.TaggedErrorClass<Workspa
partialPath: Schema.String,
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
@@ -20,7 +20,7 @@ export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceF
relativePath: Schema.optional(Schema.String),
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
+5 -5
View File
@@ -436,7 +436,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
repositoryIdentity,
},
} satisfies OrchestrationEvent;
}).pipe(Effect.catch(() => Effect.succeed(event)));
}).pipe(Effect.orElseSucceed(() => event));
default:
return Effect.succeed(event);
}
@@ -459,7 +459,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
project: nextProject,
})),
),
Effect.catch(() => Effect.succeed(Option.none())),
Effect.orElseSucceed(() => Option.none()),
);
case "project.deleted":
return Effect.succeed(
@@ -487,7 +487,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
thread: nextThread,
})),
),
Effect.catch(() => Effect.succeed(Option.none())),
Effect.orElseSucceed(() => Option.none()),
);
default:
if (event.aggregateKind !== "thread") {
@@ -503,7 +503,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
thread: nextThread,
})),
),
Effect.catch(() => Effect.succeed(Option.none())),
Effect.orElseSucceed(() => Option.none()),
);
}
};
@@ -777,7 +777,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
thread.session !== null && thread.session.status !== "stopped",
}),
),
Effect.catch(() => Effect.succeed(false)),
Effect.orElseSucceed(() => false),
)
: false;
const result = yield* dispatchNormalizedCommand(normalizedCommand);
+1 -1
View File
@@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node", "bun"],
"types": ["node"],
"lib": ["ESNext", "esnext.disposable"]
},
"include": ["src", "vite.config.ts", "scripts", "integration", "../../scripts/lib"]
+12 -3
View File
@@ -4,7 +4,17 @@ import { defineConfig, mergeConfig } from "vite-plus";
import baseConfig from "../../vite.config.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
const internalPackagePrefixes = ["@t3tools/", "effect-acp", "effect-codex-app-server"];
const bundledPackagePrefixes = [
"@pierre/diffs",
"@t3tools/",
"effect-acp",
"effect-codex-app-server",
];
export function shouldBundleCliDependency(id: string): boolean {
return bundledPackagePrefixes.some((prefix) => id.startsWith(prefix));
}
const repoEnv = loadRepoEnv();
export default mergeConfig(
@@ -25,8 +35,7 @@ export default mergeConfig(
sourcemap: true,
clean: true,
deps: {
alwaysBundle: (id: string) =>
internalPackagePrefixes.some((prefix) => id.startsWith(prefix)),
alwaysBundle: shouldBundleCliDependency,
onlyBundle: false,
},
banner: {
-1
View File
@@ -62,7 +62,6 @@
"tailwindcss": "^4.0.0",
"vite": "catalog:",
"vite-plus": "catalog:",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { resolveDesktopCloudAuthOAuthOptions } from "./desktopAuth";
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import {
makeDesktopClerkExternalAccountAdapter,
+1 -1
View File
@@ -1,6 +1,6 @@
import { verifyDpopProof } from "@t3tools/shared/dpop";
import * as Effect from "effect/Effect";
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
+1 -1
View File
@@ -1,6 +1,6 @@
import { EnvironmentId } from "@t3tools/contracts";
import { RelayWebClientId } from "@t3tools/contracts/relay";
import { afterEach, beforeEach, vi } from "vitest";
import { afterEach, beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
-4
View File
@@ -154,10 +154,6 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return "Relay rejected an expired agent activity publish proof.";
case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayQuotaExceededError":
return `Relay quota exceeded for ${error.resource} (limit ${error.limit}).`;
case "RelayRateLimitedError":
return `Relay rate limit exceeded for ${error.operation}; retry in ${error.retryAfterSeconds} seconds.`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { hasCloudPublicConfig } from "./publicConfig.ts";
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff. Show more