Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 46afa39c29 refactor(relay): clean up resource limit enforcement
Co-authored-by: codex <[email protected]>
2026-06-03 23:56:39 -07:00
Julius Marmingeandcodex d3d38272d7 feat(relay): enforce resource limits
Co-authored-by: codex <[email protected]>
2026-06-03 23:56:39 -07:00
Julius Marmingeandcodex 974463ee9d Refine mobile composer and sheet controls
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marminge 1649f83f0f Refine mobile new task toolbar labels and focus 2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 3a06a1be65 fix(deps): omit unused Clerk wallet integrations
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex c6bd783e43 feat(cloud): add headless cloud CLI control plane (#2905)
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 076cfe339d fix(relay): run tests through vite plus
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 3a81842415 fix(release): include relay in smoke lockfile fixture
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex ee87e7ff1b chore(relay): migrate deployment workflow to vite plus
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 5ad99dc6f6 chore(relay): refresh pnpm lockfile
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 11cd7247ab docs(relay): redirect root to API docs
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex e4609b0090 docs(relay): emit lowercase bearer schemes
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 34b6cff753 docs(relay): describe endpoint authentication schemes
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 1a3bd37399 fix(relay): harden cloud lifecycle security
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 8292f8ae94 feat(relay): expose Scalar API docs
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 24f5a82a5d fix(cloud): validate relay URL origins
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex c7e4e2fc56 ci(relay): scope production deploy secrets
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 2e9e633d9a fix(relay): restrict connector egress to managed endpoints
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 0ccb1efdce fix(cloud): spawn relay client without shell
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 0644077a52 refactor(cloud): clarify agent activity publishing logs
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 92673bce0f refactor(cloud): use relay client runtime wording
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 861f73346e fix(relay): clean up managed endpoints on unlink
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 0fb87aad6a fix(relay): reconcile managed endpoint provisioning
Persist per-user environment allocations and checkpoint Cloudflare resources so retries converge partial provisioning state.

Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 5af1a917df refactor(cloud): simplify relay install progress
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:06 -07:00
Julius Marmingeandcodex 631f93a04e feat(cloud): add relay client install dialog
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 5bb5be63ac feat(cloud): stream relay client installation over rpc
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 944e73ff9a refactor(cloud): name managed connector relay client
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex bb99d264b4 fix(relay): use stable Clerk JWT audience
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 846b3edba9 fix(relay): keep managed endpoint zone prod-owned
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 8d2256abcd fix(relay): name singleton database explicitly
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex f936162898 fix(relay): read stage from worker stack context
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 6fd38f88a7 fix(relay): suffix production Axiom resource names
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 69d706ff8d fix(relay): scope Axiom resources by stage
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 4bace7cd62 test(cloud): remove rename-only relay config coverage
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex c48c560457 refactor(cloud): keep relay infra config unprefixed
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex cc24a99047 docs(cloud): use canonical CLI OAuth variable
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 52f056158b refactor(cloud): standardize relay environment prefix
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 4600dd719f feat(cloud): make relay public config opt-in
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex c2d004a20e docs(relay): clarify deployment environment variables
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 73f2fdc9c5 refactor(relay): simplify deploy wiring
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex e31b0f794f refactor(relay): deploy stack programmatically
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 8cf8c13d84 refactor(http): use context-backed API clients
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 10f269ceab ci(cloud): stop injecting CLI oauth config into relay
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 56d1cbebdb feat(cloud): isolate relay resources by stage
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 6c89f75d4e ci(cloud): deploy production relay from main
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 91e8bffc28 feat(cloud): manage cloudflared installation and relay defaults
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex b9c613abab feat(web): add desktop Clerk-compatible cloud auth UI
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 03e5e416d3 fix(mobile): keep live activity layout self-contained
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 4aebaca9d0 fix(mobile): reconnect saved environments after resume
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 5f4c05caa5 chore(cloud): clarify private beta settings copy
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex ce7a03bb8f fix(mobile): refresh cloud environment credentials on reconnect
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 4453bd0fd9 refactor(cloud): retain relay queries with atoms
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marmingeandcodex 15b21b6e35 feat(cloud): integrate relay environments and notification settings
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:05 -07:00
Julius Marminge d613d755d1 rename 2026-06-03 23:48:05 -07:00
Julius Marminge d03af32817 chore: update alchemy package to version 2.0.0-beta.49
refactor: remove cloudflare settings from RelayConfigurationShape and related tests

test: clean up tests by removing cloudflare settings from configuration

feat: implement ManagedEndpointDnsClient for DNS operations with Cloudflare

refactor: simplify ManagedEndpointProvider by removing HTTP client dependencies

fix: update ManagedEndpointProvider to use new DNS client for CNAME record management

chore: adjust Api to use new DNS binding and remove deprecated cloudflare settings

refactor: streamline ManagedEndpointZone creation by removing unnecessary token generation
2026-06-03 23:48:05 -07:00
Julius Marminge baa9f7cd8f renames 2026-06-03 23:48:05 -07:00
Julius Marminge 5638662ea2 fmt 2026-06-03 23:48:05 -07:00
Julius Marminge 622b901863 Simplify Cloudflare zone resource mapping 2026-06-03 23:48:05 -07:00
Julius Marminge 8aae1d0bef Flatten relay worker layer graph and managed endpoint bindings 2026-06-03 23:48:05 -07:00
Julius Marminge e55a779e5f Refactor relay bindings for Alchemy Cloudflare integration 2026-06-03 23:48:04 -07:00
Julius Marminge f5f700f006 Update relay for Alchemy beta.48 and Cloudflare bindings 2026-06-03 23:48:04 -07:00
Julius Marminge 02353974fb refactor relay/ 2026-06-03 23:48:04 -07:00
Julius Marmingeandcodex 02beeaa86c add managed relay tunnels and standards-based auth
Co-authored-by: codex <[email protected]>
2026-06-03 23:48:04 -07:00
328 changed files with 7179 additions and 9205 deletions

No files matched your search

File renamed without changes.
+1 -1
View File
@@ -3,4 +3,4 @@
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See [Release Checklist](./release.md) for the full release/signing setup checklist.
- See `docs/release.md` for full release/signing setup checklist.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2 -7
View File
@@ -1,5 +1,5 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
@@ -10,8 +10,3 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
+7 -29
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Connect relay
name: Deploy T3 Cloud relay
on:
push:
@@ -8,7 +8,6 @@ on:
permissions:
contents: read
id-token: none
statuses: write
concurrency:
group: relay-production
@@ -26,8 +25,7 @@ jobs:
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
RELAY_ZONE_NAME: ${{ vars.RELAY_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
@@ -44,11 +42,13 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: true
run-install: false
- name: Install dependencies
run: vp install --frozen-lockfile
- name: Deploy production relay stage
id: deploy
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
run: vp run --filter t3code-relay deploy -- --stage prod --yes
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
@@ -56,25 +56,3 @@ 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}`,
});
+3 -9
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Connect public config
name: Resolve T3 Cloud public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
@@ -181,7 +181,6 @@ 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 }}
@@ -192,12 +191,8 @@ 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
@@ -216,7 +211,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 }}
@@ -773,7 +768,6 @@ jobs:
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/oxlint-plugin-t3code...
- id: update_versions
name: Update version strings
+2
View File
@@ -0,0 +1,2 @@
[tools]
node = "24.13.1"
+1
View File
@@ -0,0 +1 @@
vp staged
+2 -2
View File
@@ -13,7 +13,7 @@ The file must be a JSON array of rules:
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](../../packages/contracts/src/keybindings.ts)
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
@@ -31,7 +31,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](../../apps/server/src/keybindings.ts)
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
+13 -32
View File
@@ -1,26 +1,23 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> T3 Code currently supports Codex, Claude, 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@latest
npx t3
```
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:
@@ -49,41 +46,25 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
Observability guide: [docs/observability.md](./docs/observability.md)
## Documentation
Relay observability: [docs/relay-observability.md](./docs/relay-observability.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)
T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md)
## If you REALLY want to contribute still.... read this first
### Install `vp`
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
#### macOS / Linux
Before local development, prepare the environment and install dependencies:
```bash
curl -fsSL https://vite.plus | bash
# Optional: only needed if you use mise for dev tool management.
mise install
vp install
```
#### 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
```
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.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
File renamed without changes.
View File
File renamed without changes.
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.27",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -27,7 +27,8 @@
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"vite-plus": "catalog:"
"vite-plus": "catalog:",
"vitest": "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.orElseSucceed(() => Option.none<string>()),
Effect.catch(() => Effect.succeed(Option.none<string>())),
),
});
});
@@ -64,13 +64,6 @@ 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",
@@ -93,7 +86,6 @@ 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);
@@ -105,7 +97,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -124,23 +116,13 @@ 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,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -257,27 +239,6 @@ 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,7 +12,6 @@ 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";
@@ -23,11 +22,8 @@ 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";
@@ -416,18 +412,6 @@ 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));
@@ -532,20 +516,11 @@ 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,25 +104,6 @@ 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,11 +105,6 @@ 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[],
@@ -117,18 +112,15 @@ 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* readDnsName
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
)
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed(null)),
)
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
+43 -35
View File
@@ -1,35 +1,29 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vitest";
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")}`;
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 };
};
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
@@ -39,8 +33,16 @@ 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";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
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" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -53,25 +55,32 @@ describe("Desktop cloud auth IPC", () => {
body,
});
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(forwardedRequest !== null);
assert.equal(
new Headers(init.headers).get("content-type"),
forwardedRequest.headers["content-type"],
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
});
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");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -80,10 +89,9 @@ describe("Desktop cloud auth IPC", () => {
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
},
);
+43 -66
View File
@@ -8,11 +8,9 @@ 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 { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
@@ -54,68 +52,6 @@ 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,
@@ -172,6 +108,47 @@ export const fetchCloudAuth = makeIpcMethod({
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
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,
};
}),
});
@@ -209,7 +209,7 @@ function readSettings(
onSome: (raw) =>
decodeDesktopSettingsJson(raw).pipe(
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
Effect.orElseSucceed(() => defaultSettings),
Effect.catch(() => Effect.succeed(defaultSettings)),
),
}),
),
@@ -63,7 +63,7 @@ const readClientSettings = (
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
),
}),
),
@@ -185,7 +185,7 @@ function readRegistryDocument(
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
),
}),
),
@@ -196,7 +196,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
.pipe(
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.orElseSucceed(() => ""),
Effect.catch(() => Effect.succeed("")),
);
});
@@ -241,6 +241,7 @@ 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.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
);
}
@@ -165,7 +165,7 @@ describe("DesktopWindow", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
}),
);
assert.isFalse(
+1 -1
View File
@@ -16,7 +16,7 @@ This app has three variants:
Run commands from `apps/mobile`.
T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
-5
View File
@@ -161,11 +161,6 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
@@ -0,0 +1,256 @@
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",
},
],
});
});
});
@@ -0,0 +1,605 @@
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 "vite-plus/test";
import { beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
@@ -8,6 +8,7 @@ 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";
@@ -19,6 +20,10 @@ 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),
}));
@@ -51,7 +56,7 @@ describe("liveActivityPreferences", () => {
vi.clearAllMocks();
});
it("pushes disabled Live Activity preferences to relay registrations", async () => {
it("pushes disabled Live Activity preferences to local and relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
@@ -61,6 +66,7 @@ describe("liveActivityPreferences", () => {
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(endAllAgentLiveActivities).toHaveBeenCalledTimes(1);
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
@@ -68,7 +74,7 @@ describe("liveActivityPreferences", () => {
});
});
it("pushes enabled Live Activity preferences to relay registrations", async () => {
it("pushes enabled Live Activity preferences without ending active local activities", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
@@ -78,6 +84,7 @@ describe("liveActivityPreferences", () => {
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(endAllAgentLiveActivities).not.toHaveBeenCalled();
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
@@ -5,6 +5,7 @@ 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: {
@@ -18,6 +19,10 @@ 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 "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
extractAgentNotificationDeepLink,
@@ -2,7 +2,7 @@
import * as NodeCrypto from "node:crypto";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import Constants from "expo-constants";
import * as Effect from "effect/Effect";
@@ -18,7 +18,6 @@ import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
__resetAgentAwarenessRemoteRegistrationForTest,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
registerAgentAwarenessConnection,
@@ -30,9 +29,6 @@ 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: {
@@ -47,12 +43,6 @@ 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" })),
@@ -168,8 +158,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
secureStore.clear();
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
});
it("preserves disabled Live Activity preferences in relay registrations", () => {
@@ -274,25 +262,6 @@ 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,16 +17,14 @@ import {
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
} from "../../lib/storage";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import 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;
@@ -41,7 +39,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
}
function readRelayConfig(): { readonly url: string } | null {
const relayUrl = resolveCloudPublicConfig().relay.url;
const relayUrl = resolveCloudPublicConfig().relayUrl;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -75,18 +73,10 @@ 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;
}
@@ -320,10 +310,6 @@ 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 {
@@ -340,10 +326,6 @@ export function unregisterAllAgentAwarenessConnections(): void {
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
}
export function refreshAgentAwarenessRegistration(): Effect.Effect<
@@ -366,10 +348,6 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
pushToStartSubscription = null;
pushTokenSubscription?.remove();
pushTokenSubscription = null;
if (activeLiveActivityRegistrationRetry) {
clearTimeout(activeLiveActivityRegistrationRetry);
activeLiveActivityRegistrationRetry = null;
}
relayTokenProvider = null;
relayTokenProviderIdentity = null;
}
@@ -467,57 +445,3 @@ 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();
}
});
}
@@ -0,0 +1,59 @@
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,6 +9,7 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function CloudAuthBridge(props: { readonly children: ReactNode }) {
@@ -51,6 +52,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
readClerkToken: tokenProvider,
}),
);
if (!previous || previous.userId !== userId) {
void mobileRuntime
.runPromise(refreshActiveLiveActivityRemoteRegistration())
.catch(() => undefined);
}
}, [getToken, isLoaded, isSignedIn, userId]);
useEffect(
@@ -66,9 +72,7 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const config = resolveCloudPublicConfig();
const publishableKey = config.clerk.publishableKey;
const relayUrl = config.relay.url;
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
useEffect(() => {
if (!publishableKey || !relayUrl) {
+1 -1
View File
@@ -2,7 +2,7 @@
import * as NodeCrypto from "node:crypto";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
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 "vite-plus/test";
import { beforeEach, vi } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -572,7 +572,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
if (String(url).endsWith("/api/cloud/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(Response.json(validLinkResponse("env-other")));
@@ -631,7 +631,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
if (String(url).endsWith("/api/cloud/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -669,7 +669,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
if (String(url).endsWith("/api/cloud/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -713,7 +713,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
if (String(url).endsWith("/api/cloud/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
if (String(url).endsWith("/v1/client/environment-links")) {
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relay.url;
return resolveCloudPublicConfig().relayUrl;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -147,6 +147,10 @@ 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}).`;
}
@@ -301,7 +305,7 @@ export function linkEnvironmentToCloud(input: {
),
);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const proof = yield* environmentClient.connect
const proof = yield* environmentClient.cloud
.linkProof({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -336,7 +340,7 @@ export function linkEnvironmentToCloud(input: {
link,
});
yield* environmentClient.connect
yield* environmentClient.cloud
.relayConfig({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
@@ -8,13 +9,23 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
import { resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -13,18 +13,9 @@ vi.mock("expo-constants", () => ({
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerk: {
publishableKey: null,
jwtTemplate: null,
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
});
});
@@ -33,25 +24,11 @@ describe("resolveCloudPublicConfig", () => {
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
relay: { url: " https://relay.example.test/// " },
observability: {
tracesUrl: " https://api.axiom.co/v1/traces ",
tracesDataset: " mobile-traces ",
tracesToken: " public-ingest-token ",
},
}),
).toEqual({
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: "https://relay.example.test",
},
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
});
});
@@ -62,59 +39,9 @@ describe("resolveCloudPublicConfig", () => {
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
});
});
it("rejects an insecure traces URL", () => {
expect(
resolveCloudPublicConfig({
observability: {
tracesUrl: "http://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}).observability,
).toEqual({
tracesUrl: null,
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
});
});
it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
},
}),
),
).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}),
),
).toBe(true);
});
});
+17 -69
View File
@@ -2,92 +2,40 @@ import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerk: {
readonly publishableKey: string | null;
readonly jwtTemplate: string | null;
};
readonly relay: {
readonly url: string | null;
};
readonly observability: {
readonly tracesUrl: string | null;
readonly tracesDataset: string | null;
readonly tracesToken: string | null;
};
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
}
type UntrustedSection<T> = {
readonly [Key in keyof T]?: unknown;
};
type ExpoExtra =
| {
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
}
| undefined;
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function normalizeSecureUrl(value: unknown): string | null {
const raw = trimNonEmpty(value);
if (raw === null) {
return null;
}
try {
const url = new URL(raw);
return url.protocol === "https:" ? url.toString() : null;
} catch {
return null;
}
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
| undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
return {
clerk: {
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
},
relay: {
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
},
observability: {
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
},
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
}
type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>;
};
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>;
};
export function hasMobileTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig {
return Boolean(
config.observability.tracesUrl &&
config.observability.tracesDataset &&
config.observability.tracesToken,
);
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
}
export function resolveRelayClerkTokenOptions() {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(jwtTemplate);
return relayClerkTokenOptions(clerkJwtTemplate);
}
@@ -1,52 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { makeMobileTracingLayer } from "./mobileTracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeMobileTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
@@ -1,60 +0,0 @@
import Constants from "expo-constants";
import * as Layer from "effect/Layer";
import type { HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
export interface MobileTracingConfig {
readonly tracesUrl: string;
readonly tracesDataset: string;
readonly tracesToken: string;
}
export interface MobileTracingResource {
readonly serviceVersion?: string;
readonly appVariant: string;
}
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) {
return null;
}
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken };
}
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
): Layer.Layer<never, never, HttpClient.HttpClient> {
if (config === null) {
return Layer.empty;
}
return OtlpTracer.layer({
url: config.tracesUrl,
headers: {
Authorization: `Bearer ${config.tracesToken}`,
"X-Axiom-Dataset": config.tracesDataset,
},
resource: {
serviceName: "t3-mobile",
serviceVersion: resource.serviceVersion,
attributes: {
"service.runtime": "react-native",
"service.component": "mobile",
"deployment.environment.name": resource.appVariant,
},
},
}).pipe(Layer.provide(OtlpSerialization.layerJson));
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
serviceVersion: Constants.expoConfig?.version,
appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string"
? Constants.expoConfig.extra.appVariant
: "unknown",
});
@@ -10,7 +10,6 @@ import type {
import {
detectComposerTrigger,
replaceTextRange,
serializeComposerMentionPath,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
@@ -419,7 +418,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
let replacement = "";
if (item.type === "path") {
replacement = `@${serializeComposerMentionPath(item.path)} `;
replacement = `@${item.path} `;
} else if (item.type === "skill") {
replacement = `$${item.skill.name} `;
} else if (item.type === "slash-command") {
+7 -8
View File
@@ -6,20 +6,19 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
import { mobileTracingLayer } from "../features/observability/mobileTracing";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provideMerge(mobileCryptoLayer),
Layer.provideMerge(mobileHttpClientLayer),
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
),
);
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
+1 -1
View File
@@ -1,5 +1,5 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { beforeEach, describe, expect, it, vi } from "vitest";
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 "vite-plus/test";
import { beforeEach, vi } from "vitest";
const mocks = vi.hoisted(() => {
const environmentConnection = {
@@ -45,8 +45,8 @@ const mocks = vi.hoisted(() => {
getEnvironmentSession: vi.fn(() => null),
setEnvironmentSession: vi.fn(),
notifyEnvironmentConnectionListeners: vi.fn(),
unregisterAgentAwarenessConnection: vi.fn(),
registerAgentAwarenessConnection: vi.fn(),
stopAgentAwarenessForEnvironment: vi.fn(),
startAgentAwarenessForEnvironment: 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/remoteRegistration", () => ({
registerAgentAwarenessConnection: mocks.registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection: mocks.unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections: vi.fn(),
vi.mock("../features/agent-awareness/shellLiveActivitySync", () => ({
startAgentAwarenessForEnvironment: mocks.startAgentAwarenessForEnvironment,
stopAgentAwarenessForEnvironment: mocks.stopAgentAwarenessForEnvironment,
stopAllAgentAwareness: 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.registerAgentAwarenessConnection).toHaveBeenCalledWith(connection);
expect(mocks.startAgentAwarenessForEnvironment).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.registerAgentAwarenessConnection).not.toHaveBeenCalled();
expect(mocks.startAgentAwarenessForEnvironment).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.registerAgentAwarenessConnection).not.toHaveBeenCalled();
expect(mocks.startAgentAwarenessForEnvironment).not.toHaveBeenCalled();
expect(mocks.environmentRuntimePatch).toHaveBeenCalledWith(
{ environmentId: connection.environmentId },
expect.any(Function),
@@ -419,9 +419,7 @@ describe("mobile remote environment registry effects", () => {
yield* disconnectEnvironment(connection.environmentId, { removeSaved: true });
expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1);
expect(mocks.unregisterAgentAwarenessConnection).toHaveBeenCalledWith(
connection.environmentId,
);
expect(mocks.stopAgentAwarenessForEnvironment).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 {
registerAgentAwarenessConnection,
unregisterAgentAwarenessConnection,
unregisterAllAgentAwarenessConnections,
} from "../features/agent-awareness/remoteRegistration";
startAgentAwarenessForEnvironment,
stopAgentAwarenessForEnvironment,
stopAllAgentAwareness,
} from "../features/agent-awareness/shellLiveActivitySync";
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
import {
clearCachedShellSnapshotMetadata,
@@ -200,7 +200,7 @@ export function disconnectEnvironment(
}
terminalMetadataUnsubscribers.get(environmentId)?.();
terminalMetadataUnsubscribers.delete(environmentId);
unregisterAgentAwarenessConnection(environmentId);
stopAgentAwarenessForEnvironment(environmentId);
if (!options?.preserveShellSnapshot) {
shellSnapshotManager.invalidate({ environmentId });
}
@@ -454,7 +454,7 @@ export function connectSavedEnvironment(
terminalDebugLog("registry:terminal-metadata-subscribed", {
environmentId: connection.environmentId,
});
registerAgentAwarenessConnection(toStableSavedRemoteConnection(activeConnection));
startAgentAwarenessForEnvironment(toStableSavedRemoteConnection(activeConnection));
notifyEnvironmentConnectionListeners();
});
}
@@ -615,7 +615,7 @@ export function useRemoteEnvironmentBootstrap() {
}
terminalMetadataUnsubscribers.clear();
environmentConnectionAttempts.clear();
unregisterAllAgentAwarenessConnections();
stopAllAgentAwareness();
environmentRuntimeManager.invalidate();
shellSnapshotManager.invalidate();
resetSourceControlDiscoveryState();
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
vi.mock("@expo/ui/swift-ui", () => ({
HStack: "HStack",
@@ -35,7 +35,6 @@ import { ProjectionCheckpointRepository } from "../src/persistence/Services/Proj
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
@@ -162,7 +161,7 @@ class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<Orchestra
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect()),
cause: Schema.optional(Schema.Defect),
},
) {}
@@ -294,7 +293,6 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const providerRegistryLayer = makeProviderRegistryLayer();
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
@@ -377,7 +375,6 @@ export const makeOrchestrationIntegrationHarness = (
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.27",
"version": "0.0.24",
"license": "MIT",
"repository": {
"type": "git",
@@ -38,11 +38,12 @@
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "1.3.14",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"vite-plus": "catalog:"
"vite-plus": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
+3 -83
View File
@@ -18,15 +18,9 @@ const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
};
const sessionId = "mock-session-1";
let currentModeId = "ask";
@@ -243,21 +237,6 @@ function modeState(): AcpSchema.SessionModeState {
};
}
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
{ modelId: "grok-build", name: "Grok Build" },
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
];
function modelState(): AcpSchema.SessionModelState {
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
? currentModelId
: "grok-build";
return {
currentModelId: modelId,
availableModels: grokAcpModels,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
@@ -278,7 +257,6 @@ const program = Effect.gen(function* () {
Effect.succeed({
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
);
@@ -295,28 +273,11 @@ const program = Effect.gen(function* () {
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionModel((request) =>
Effect.gen(function* () {
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
return yield* AcpError.AcpRequestError.invalidParams(
`Unknown mock model id: ${request.modelId}`,
{
method: "session/set_model",
params: request,
},
);
}
currentModelId = request.modelId;
return {};
}),
);
yield* agent.handleSetSessionConfigOption((request) =>
Effect.gen(function* () {
if (exitOnSetConfigOption) {
@@ -458,13 +419,9 @@ const program = Effect.gen(function* () {
],
},
options: [
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
{
optionId: permissionOptionIds.allowAlways,
name: "Allow always",
kind: "allow_always",
},
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
],
});
@@ -557,43 +514,6 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitXAiAskUserQuestion) {
const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
method: "x.ai/ask_user_question",
params: {
sessionId: requestedSessionId,
toolCallId: "ask-user-question-tool-call-1",
questions: [
{
question: "Which scope should Grok use?",
multiSelect: null,
options: [
{ label: "Workspace", description: "Use the current workspace" },
{ label: "Session", description: "Only use this session" },
],
},
],
mode: "default",
},
});
if (typeof result !== "object" || result === null || !("outcome" in result)) {
throw new Error("Expected _x.ai/ask_user_question response outcome.");
}
if (result.outcome === "cancelled") {
return { stopReason: "end_turn" };
}
if (
result.outcome !== "accepted" ||
!("answers" in result) ||
typeof result.answers !== "object" ||
result.answers === null
) {
throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
}
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
+9 -31
View File
@@ -175,6 +175,8 @@ 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",
}),
);
@@ -195,31 +197,6 @@ 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",
{
@@ -285,16 +262,17 @@ const publishCmd = Command.make(
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: pnpm publish from the workspace root so pnpm-only workspace
// config, including override selectors, is interpreted correctly.
// Use: npm publish
() =>
Effect.gen(function* () {
const args = createVpPmPublishArgs(config);
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("vp", ["pm", ...args], {
cwd: repoRoot,
ChildProcess.make("npm", [...args], {
cwd: serverDir,
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 "vite-plus/test";
import { describe, expect, it } from "vitest";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "./ServerSecretStore.ts";
+24 -26
View File
@@ -38,11 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const connectCli = makeCli({ cloudEnabled: true });
const noConnectCli = makeCli({ cloudEnabled: false });
const cloudCli = makeCli({ cloudEnabled: true });
const noCloudCli = makeCli({ cloudEnabled: false });
const runCli = (args: ReadonlyArray<string>, command = cli) =>
Command.runWith(command, { version: "0.0.0" })(args);
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
const runCloudCli = (args: ReadonlyArray<string>) => runCli(args, cloudCli);
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
@@ -179,9 +179,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("rejects connect commands when public configuration is missing", () =>
it.effect("rejects cloud commands when public cloud configuration is missing", () =>
Effect.gen(function* () {
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
@@ -189,20 +189,20 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "connect"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
assert.deepEqual(error.commandPath, ["t3", "cloud"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration");
const output = (yield* TestConsole.errorLines).join("\n");
assert.include(output, "ERROR");
assert.include(output, "missing T3 Connect public configuration");
assert.include(output, "missing T3 Cloud public configuration");
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("reports fresh headless connect state without requiring local configuration", () =>
it.effect("reports fresh headless cloud state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const status = JSON.parse(output) as {
@@ -221,21 +221,21 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("reports actionable human-readable headless connect state", () =>
it.effect("reports actionable human-readable headless cloud state", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir]),
runCloudCli(["cloud", "status", "--base-dir", baseDir]),
);
assert.include(output, "T3 Connect\n Exposure: disabled");
assert.include(output, "T3 Cloud\n Exposure: disabled");
assert.include(output, " Authorization: missing");
assert.include(output, " Environment link: not provisioned");
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure.");
}),
);
it.effect("logs in to headless connect without enabling access", () =>
it.effect("logs in to headless cloud without enabling exposure", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -250,11 +250,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
const login = yield* captureStdout(
runConnectCli(["connect", "login", "--base-dir", baseDir]),
);
const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir]));
const status = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const decoded = JSON.parse(status.output) as {
@@ -262,24 +260,24 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
readonly authenticated: boolean;
};
assert.equal(login.output, "Signed in to T3 Connect.");
assert.equal(login.output, "Signed in to T3 Cloud.");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
);
it.effect("disables headless connect without a running server", () =>
it.effect("disables headless cloud exposure without a running server", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
const { output } = yield* captureStdout(
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
runCloudCli(["cloud", "unlink", "--base-dir", baseDir]),
);
assert.equal(output, "T3 Connect is disabled locally.");
assert.equal(output, "T3 Cloud exposure is disabled locally.");
}),
);
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
it.effect("logs out of headless cloud and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -288,10 +286,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
runCloudCli(["cloud", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Connect locally.");
assert.equal(output, "Signed out of T3 Cloud locally.");
assert.isFalse(existsSync(tokenPath));
}),
);
+10 -10
View File
@@ -8,7 +8,7 @@ import * as CliError from "effect/unstable/cli/CliError";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { cloudCommand } from "./cli/cloud.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
@@ -16,23 +16,23 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const connectPublicConfigMissingMessage =
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
const cloudPublicConfigMissingMessage =
"T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration.";
class ConnectPublicConfigMissingError extends CliError.UserError {
class CloudPublicConfigMissingError extends CliError.UserError {
override get message() {
return connectPublicConfigMissingMessage;
return cloudPublicConfigMissingMessage;
}
}
const connectUnavailableCommand = Command.make("connect").pipe(
Command.withDescription("T3 Connect is unavailable in builds without public configuration."),
const cloudUnavailableCommand = Command.make("cloud").pipe(
Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."),
Command.withHidden,
Command.withHandler(() =>
Effect.fail(
new CliError.ShowHelp({
commandPath: ["t3", "connect"],
errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],
commandPath: ["t3", "cloud"],
errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })],
}),
),
),
@@ -47,7 +47,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
serveCommand,
authCommand,
projectCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
cloudEnabled ? cloudCommand : cloudUnavailableCommand,
]),
);
+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.orElseSucceed(() => false),
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
@@ -3,7 +3,7 @@ import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { acquireRelayClientForLink } from "./connect.ts";
import { acquireRelayClientForLink } from "./cloud.ts";
const managedExecutable = {
status: "available",
@@ -89,15 +89,15 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
? "pending server startup"
: "not provisioned";
const nextStep = !status.authenticated
? "Run `t3 connect link` to authorize and enable T3 Connect."
? "Run `t3 cloud link` to authorize and enable cloud exposure."
: !status.desired
? "Run `t3 connect link` to enable T3 Connect."
? "Run `t3 cloud link` to enable cloud exposure."
: !status.linked
? "Start T3 to provision the environment link and launch its managed tunnel."
: undefined;
return [
"T3 Connect",
"T3 Cloud",
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
@@ -112,7 +112,7 @@ const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
const confirmRelayClientInstall = (version: string) =>
Prompt.run(
Prompt.confirm({
message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`,
initial: false,
}),
);
@@ -169,7 +169,7 @@ const withCloudCliSessionToken = <A, E, R>(
environmentAuth.issueSession({
scopes: [AuthRelayWriteScope],
subject: "cloud-cli",
label: "t3 connect cli",
label: "t3 cloud cli",
}),
(issued) => run(issued.token),
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
@@ -194,7 +194,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
baseUrl: runtimeState.value.origin,
}).pipe(
Effect.flatMap((client) =>
client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }),
),
Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
),
@@ -249,24 +249,24 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (liveResult.status === "failed") {
yield* Console.warn(
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
`T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
);
} else {
yield* Console.log("T3 Connect is disabled locally.");
yield* Console.log("T3 Cloud exposure is disabled locally.");
}
if (Exit.isFailure(relayResult)) {
yield* Console.warn(
options.clearAuthorization
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`,
);
} else if (relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Connect locally.");
yield* Console.log("Signed out of T3 Cloud locally.");
}
});
@@ -307,26 +307,26 @@ const runCloudCommand = <A, E>(
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const connectLoginCommand = Command.make("login", {
const cloudLoginCommand = Command.make("login", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Connect.");
yield* Console.log("Signed in to T3 Cloud.");
}),
),
),
);
const connectLinkCommand = Command.make("link", {
const cloudLinkCommand = Command.make("link", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize this environment for T3 Connect on next start."),
Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -338,7 +338,7 @@ const connectLinkCommand = Command.make("link", {
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
yield* Console.log("T3 Cloud link cancelled. The relay client was not installed.");
return;
}
yield* Console.log(
@@ -349,18 +349,18 @@ const connectLinkCommand = Command.make("link", {
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(true);
yield* Console.log(
"This T3 environment will be available through T3 Connect the next time T3 starts.",
"This T3 environment will be available over T3 Cloud the next time T3 starts.",
);
}),
),
),
);
const connectStatusCommand = Command.make("status", {
const cloudStatusCommand = Command.make("status", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("Show persisted T3 Connect and relay client state."),
Command.withDescription("Show persisted T3 Cloud and relay client state."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -395,31 +395,31 @@ const connectStatusCommand = Command.make("status", {
),
);
const connectUnlinkCommand = Command.make("unlink", {
const cloudUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
),
);
const connectLogoutCommand = Command.make("logout", {
const cloudLogoutCommand = Command.make("logout", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
),
);
export const connectCommand = Command.make("connect").pipe(
Command.withDescription("Manage headless T3 Connect access."),
export const cloudCommand = Command.make("cloud").pipe(
Command.withDescription("Manage headless T3 Cloud exposure."),
Command.withSubcommands([
connectLoginCommand,
connectLinkCommand,
connectStatusCommand,
connectUnlinkCommand,
connectLogoutCommand,
cloudLoginCommand,
cloudLinkCommand,
cloudStatusCommand,
cloudUnlinkCommand,
cloudLogoutCommand,
]),
);
+8 -8
View File
@@ -96,7 +96,7 @@ const make = Effect.gen(function* () {
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError("Could not remove the stored T3 Connect CLI credential."));
.pipe(wrapError("Could not remove the stored T3 Cloud CLI credential."));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -146,7 +146,7 @@ const make = Effect.gen(function* () {
const url = new URL(request.originalUrl, metadata.redirectUri);
const code = url.searchParams.get("code");
if (url.searchParams.get("state") !== state || !code) {
return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", {
status: 400,
});
}
@@ -154,7 +154,7 @@ const make = Effect.gen(function* () {
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Connect authorization complete</h1>
<h1>T3 Cloud authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
@@ -182,13 +182,13 @@ const make = Effect.gen(function* () {
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", () =>
Effect.fail(
new CloudCliTokenManagerError({
message: "Timed out waiting for T3 Connect authorization.",
message: "Timed out waiting for T3 Cloud authorization.",
}),
),
),
@@ -213,12 +213,12 @@ const make = Effect.gen(function* () {
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")),
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError("Could not read the stored T3 Connect CLI credential."),
wrapError("Could not read the stored T3 Cloud CLI credential."),
),
);
const get = semaphore.withPermits(1)(
@@ -227,7 +227,7 @@ const make = Effect.gen(function* () {
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError("Could not authorize the T3 Connect CLI.")),
}).pipe(wrapError("Could not authorize the T3 Cloud CLI.")),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
@@ -1,5 +1,5 @@
import { describe, expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -152,7 +152,9 @@ 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.orElseSucceed(() => false));
const isRunning = yield* active.child.isRunning.pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (isRunning) {
return {
status: "running",
+1 -1
View File
@@ -76,7 +76,7 @@ describe("reconcileDesiredCloudLink", () => {
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 connect link` to authorize this environment.",
message: "Run `t3 cloud link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
+6 -6
View File
@@ -509,7 +509,7 @@ const relayClientRequest = <A>(
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Connect relay request failed: ${String(cause)}`,
message: `T3 Cloud relay request failed: ${String(cause)}`,
}),
),
);
@@ -535,7 +535,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
onNone: () =>
Effect.fail(
new EnvironmentHttpUnauthorizedError({
message: "Run `t3 connect link` to authorize this environment.",
message: "Run `t3 cloud link` to authorize this environment.",
}),
),
onSome: Effect.succeed,
@@ -595,7 +595,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
CloudCliTokenManagerError: (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
"Could not persist desired T3 Cloud link state.",
),
}),
);
@@ -874,7 +874,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
ttl: Duration.minutes(2),
label: "T3 Connect connect",
label: "T3 Cloud connect",
proofKeyThumbprint: proof.clientProofKeyThumbprint,
});
const responsePayload = {
@@ -924,9 +924,9 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}),
);
export const connectHttpApiLayer = HttpApiBuilder.group(
export const cloudHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"connect",
"cloud",
Effect.fnUntraced(function* (handlers) {
const dependencies = yield* cloudHttpDependencies;
return handlers
@@ -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,6 +280,7 @@ 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,6 +59,7 @@ 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.orElseSucceed(() => value));
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(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.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed(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.orElseSucceed(() => null));
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(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.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
Effect.catch(() => Effect.succeed(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.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed(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.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed(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.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
)
: null;
+18 -8
View File
@@ -156,8 +156,8 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
otlpTracesUrl,
}),
),
Effect.orElseSucceed(() =>
HttpServerResponse.text("Trace export failed.", { status: 502 }),
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
),
);
}).pipe(
@@ -205,7 +205,9 @@ export const attachmentsRouteLayer = HttpRouter.add(
}
const fileSystem = yield* FileSystem.FileSystem;
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return HttpServerResponse.text("Not Found", { status: 404 });
}
@@ -216,7 +218,9 @@ export const attachmentsRouteLayer = HttpRouter.add(
"Cache-Control": "public, max-age=31536000, immutable",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
}).pipe(
Effect.catchTags({
@@ -261,7 +265,9 @@ export const projectFaviconRouteLayer = HttpRouter.add(
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
}).pipe(
Effect.catchTags({
@@ -331,12 +337,14 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
}
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.orElseSucceed(() => null));
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
@@ -347,7 +355,9 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}
@@ -1,4 +1,3 @@
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -19,7 +18,6 @@ export const ObservabilityLive = Layer.unwrap(
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
httpHeaderRedactionLayer,
);
const tracerLayer = Layer.unwrap(
+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.orElseSucceed(() => [] as Array<string>));
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
function* (threadSegment: string, entry: string) {
@@ -397,7 +397,9 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));
const fileInfo = yield* fileSystem
.stat(absolutePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return;
}
@@ -28,7 +28,6 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -41,7 +40,6 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -144,7 +142,6 @@ describe("ProviderCommandReactor", () => {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
readonly sessionModelSwitch?: "unsupported" | "in-session";
readonly requiresNewThreadForModelChange?: boolean;
}) {
const now = "2026-01-01T00:00:00.000Z";
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
@@ -283,14 +280,6 @@ describe("ProviderCommandReactor", () => {
}),
),
);
const providerSnapshots = [
{
instanceId: modelSelection.instanceId,
...(input?.requiresNewThreadForModelChange === true
? { requiresNewThreadForModelChange: true }
: {}),
},
];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -346,7 +335,6 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
Layer.provideMerge(
Layer.mock(GitWorkflowService)({
renameBranch,
@@ -891,80 +879,6 @@ describe("ProviderCommandReactor", () => {
});
});
effectIt.effect(
"rejects changing models after start when the provider requires a new thread",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() =>
createHarness({ requiresNewThreadForModelChange: true }),
);
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.1-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.make("thread-1"),
);
return (
thread?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining(
"cannot switch models after the conversation has started",
),
},
});
}),
);
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
@@ -31,7 +31,6 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
@@ -181,7 +180,6 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
@@ -307,38 +305,6 @@ const make = Effect.gen(function* () {
.pipe(Effect.map(Option.getOrUndefined));
});
const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly currentModelSelection: ModelSelection;
readonly requestedModelSelection: ModelSelection | undefined;
}) {
const requestedModelSelection = input.requestedModelSelection;
if (
requestedModelSelection === undefined ||
(input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&
input.currentModelSelection.model === requestedModelSelection.model)
) {
return;
}
const providers = yield* providerRegistry.getProviders;
const requiresNewThread =
providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)
?.requiresNewThreadForModelChange === true ||
providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)
?.requiresNewThreadForModelChange === true;
if (!requiresNewThread) {
return;
}
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(requestedModelSelection.instanceId),
modelSelectionInstanceId: String(input.currentModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,
});
});
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
threadId: ThreadId,
createdAt: string,
@@ -418,20 +384,6 @@ const make = Effect.gen(function* () {
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (thread.session !== null) {
yield* rejectStartedThreadModelChangeIfRequired({
threadId,
currentModelSelection:
activeSession?.model !== undefined
? {
...thread.modelSelection,
instanceId: currentInstanceId,
model: activeSession.model,
}
: thread.modelSelection,
requestedModelSelection,
});
}
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
@@ -344,26 +344,6 @@ 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 [
{
@@ -371,9 +351,7 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "info",
kind: "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),
summary: "Runtime warning",
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,7 +80,9 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
if (!isPathWithinProject(projectCwd, candidate)) {
continue;
}
const stats = yield* fileSystem.stat(candidate).pipe(Effect.orElseSucceed(() => null));
const stats = yield* fileSystem
.stat(candidate)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (stats?.type === "File") {
return candidate;
}
@@ -103,7 +105,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
const sourcePath = path.join(cwd, sourceFile);
const source = yield* fileSystem
.readFileString(sourcePath)
.pipe(Effect.orElseSucceed(() => null));
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!source) {
continue;
}
@@ -23,6 +23,7 @@ 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,6 +94,7 @@ 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) {
@@ -118,6 +119,7 @@ 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) {
@@ -1,153 +0,0 @@
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
import {
buildInitialGrokProviderSnapshot,
checkGrokProviderStatus,
enrichGrokSnapshot,
} from "../Layers/GrokProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import {
makeManualOnlyProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const DRIVER_KIND = ProviderDriverKind.make("grok");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeManualOnlyProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
}),
);
export type GrokDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Grok",
supportsMultipleInstances: true,
},
configSchema: GrokSettings,
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey: continuationIdentity.continuationKey,
});
const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
binaryPath: effectiveConfig.binaryPath,
env: processEnv,
});
const adapter = yield* makeGrokAdapter(effectiveConfig, {
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const snapshot = yield* makeManagedServerProvider<GrokSettings>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) =>
buildInitialGrokProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot: currentSnapshot, publishSnapshot }) =>
enrichGrokSnapshot({
snapshot: currentSnapshot,
maintenanceCapabilities,
publishSnapshot,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
+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 {
@@ -447,29 +447,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("preserves xhigh effort for Claude Fable 5", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-fable-5",
[{ id: "effort", value: "xhigh" }],
),
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "xhigh");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -972,52 +972,6 @@ 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;
@@ -2313,31 +2267,10 @@ 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,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
`Unhandled Claude system message subtype '${message.subtype}'.`,
message,
);
return;
@@ -2451,7 +2384,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
default:
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
`Unhandled Claude SDK message type '${message.type}'.`,
message,
);
return;
@@ -48,42 +48,50 @@ const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
} as const;
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const CLAUDE_EFFORT_OPTIONS = {
opus48: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus47: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus46: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
sonnet46: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus45: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
} as const;
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-fable-5",
name: "Claude Fable 5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
{
slug: "claude-opus-4-8",
name: "Claude Opus 4.8",
@@ -93,21 +101,9 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
options: CLAUDE_EFFORT_OPTIONS.opus48,
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
@@ -128,20 +124,9 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
options: CLAUDE_EFFORT_OPTIONS.opus47,
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
@@ -162,13 +147,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
options: CLAUDE_EFFORT_OPTIONS.opus46,
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
@@ -195,12 +174,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
options: CLAUDE_EFFORT_OPTIONS.opus45,
}),
buildBooleanOptionDescriptor({
id: "fastMode",
@@ -218,13 +192,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
options: CLAUDE_EFFORT_OPTIONS.sonnet46,
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
@@ -253,10 +221,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeFable5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
}
function supportsClaudeOpus48(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
}
@@ -269,9 +233,6 @@ function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
return BUILT_IN_MODELS.filter((model) => {
if (model.slug === "claude-fable-5") {
return supportsClaudeFable5(version);
}
if (model.slug === "claude-opus-4-8") {
return supportsClaudeOpus48(version);
}
@@ -282,11 +243,6 @@ function getBuiltInClaudeModelsForVersion(
});
}
function formatClaudeFable5UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
}
function formatClaudeOpus48UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;
@@ -338,7 +294,7 @@ export function normalizeClaudeCliEffort(
if (effort === "ultracode") {
return "xhigh";
}
if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") {
if (effort === "xhigh" && model !== "claude-opus-4-8") {
return "max";
}
if (effort === "max" && model === "claude-sonnet-4-6") {
@@ -732,13 +688,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
const versionUpgradeMessage = supportsClaudeOpus48(parsedVersion)
? undefined
: supportsClaudeOpus48(parsedVersion)
? formatClaudeFable5UpgradeMessage(parsedVersion)
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
@@ -1,377 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
ApprovalRequestId,
GrokSettings,
ProviderDriverKind,
ThreadId,
ProviderInstanceId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { makeGrokAdapter } from "./GrokAdapter.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const mockAgentCommand = process.execPath;
async function makeMockGrokWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "grok-acp-mock-"));
const wrapperPath = path.join(dir, "fake-grok.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
Effect.gen(function* () {
if (remainingAttempts <= 0) {
return yield* Effect.die(new Error(`Timed out waiting for file content at ${filePath}`));
}
const raw = yield* Effect.tryPromise(() => readFile(filePath, "utf8")).pipe(
Effect.orElseSucceed(() => ""),
);
if (raw.trim().length > 0) {
return raw;
}
yield* Effect.sleep("25 millis");
return yield* readAttempt(remainingAttempts - 1);
});
return readAttempt(attempts);
}
async function readJsonLines(filePath: string) {
const raw = await readFile(filePath, "utf8");
return raw
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as Record<string, unknown>);
}
const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-grok-adapter-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-mock-thread");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
const session = yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-mock-alt" },
});
assert.equal(session.provider, "grok");
assert.equal(session.model, "grok-mock-alt");
assert.deepStrictEqual(session.resumeCursor, {
schemaVersion: 1,
sessionId: "mock-session-1",
});
yield* adapter.sendTurn({
threadId,
input: "hello grok",
attachments: [],
});
yield* Deferred.await(turnCompleted);
yield* Fiber.interrupt(runtimeEventsFiber);
const types = runtimeEvents.map((e) => e.type);
assert.includeMembers(types, [
"session.started",
"session.state.changed",
"thread.started",
"turn.started",
"item.started",
"content.delta",
"turn.completed",
] as const);
const delta = runtimeEvents.find((e) => e.type === "content.delta");
assert.isDefined(delta);
if (delta?.type === "content.delta") {
assert.equal(delta.payload.delta, "hello from mock");
}
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-session-close");
const tempDir = yield* Effect.promise(() =>
mkdtemp(path.join(os.tmpdir(), "grok-adapter-exit-log-")),
);
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.stopSession(threadId);
const exitLog = yield* waitForFileContent(exitLogPath);
assert.include(exitLog, "SIGTERM");
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const threadId = ThreadId.make("grok-provider-mismatch");
const error = yield* Effect.flip(
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
}),
);
assert.equal(error._tag, "ProviderAdapterValidationError");
}),
);
it.effect("rejects sendTurn with empty input and no attachments", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-empty-turn");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: " ",
attachments: [],
}),
);
assert.equal(error._tag, "ProviderAdapterValidationError");
yield* adapter.stopSession(threadId);
}),
);
it.effect("responds to ACP approvals using provider-supplied option ids", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-custom-approval-option-id");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "grok-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_EMIT_TOOL_CALLS: "1",
T3_ACP_ALLOW_ONCE_OPTION_ID: "agent-defined-approval-id",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "request.opened"
? adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(event.requestId)),
"accept",
)
: Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "approval-required",
});
yield* adapter.sendTurn({ threadId, input: "approve this", attachments: [] });
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.isTrue(
requests.some(
(entry) =>
!("method" in entry) &&
typeof entry.result === "object" &&
entry.result !== null &&
"outcome" in entry.result &&
typeof entry.result.outcome === "object" &&
entry.result.outcome !== null &&
"optionId" in entry.result.outcome &&
entry.result.outcome.optionId === "agent-defined-approval-id",
),
);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("handles xAI ask_user_question extension requests", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-ask-user-question");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_ASK_USER_QUESTION: "1" }),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const requested =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.requested" }>>();
const resolved =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.resolved" }>>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) {
return Effect.void;
}
if (event.type === "user-input.requested") {
return Deferred.succeed(requested, event).pipe(Effect.ignore);
}
if (event.type === "user-input.resolved") {
return Deferred.succeed(resolved, event).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "ask before continuing", attachments: [] })
.pipe(Effect.forkChild);
const requestedEvent = yield* Deferred.await(requested);
assert.equal(requestedEvent.payload.questions.length, 1);
assert.equal(requestedEvent.payload.questions[0]?.id, "Which scope should Grok use?");
assert.equal(requestedEvent.payload.questions[0]?.question, "Which scope should Grok use?");
assert.equal(requestedEvent.raw?.method, "_x.ai/ask_user_question");
yield* adapter.respondToUserInput(
threadId,
ApprovalRequestId.make(String(requestedEvent.requestId)),
{
"Which scope should Grok use?": "Workspace",
},
);
const resolvedEvent = yield* Deferred.await(resolved);
assert.deepEqual(resolvedEvent.payload.answers, {
"Which scope should Grok use?": "Workspace",
});
yield* Fiber.join(sendTurnFiber);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("continues streaming events when native notification logging fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-native-log-failure");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath, {
nativeEventLogger: {
filePath: "memory://grok-native-events",
write: (record: unknown) =>
typeof record === "object" &&
record !== null &&
"event" in record &&
typeof record.event === "object" &&
record.event !== null &&
"kind" in record.event &&
record.event.kind === "notification"
? Effect.die(new Error("native log write failed"))
: Effect.void,
close: () => Effect.void,
},
});
const contentDelta = yield* Deferred.make<void>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({ threadId, input: "keep streaming", attachments: [] });
yield* Deferred.await(contentDelta);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
});
@@ -1,934 +0,0 @@
import {
ApprovalRequestId,
type GrokSettings,
EventId,
type ProviderApprovalDecision,
type ProviderRuntimeEvent,
type ProviderSession,
type ProviderUserInputAnswers,
ProviderDriverKind,
ProviderInstanceId,
RuntimeRequestId,
type ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
import {
makeAcpAssistantItemEvent,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
makeAcpRequestResolvedEvent,
makeAcpToolCallEvent,
} from "../acp/AcpCoreRuntimeEvents.ts";
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
import {
applyGrokAcpModelSelection,
currentGrokModelIdFromSessionSetup,
makeGrokAcpRuntime,
resolveGrokAcpBaseModelId,
} from "../acp/GrokAcpSupport.ts";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
XAiAskUserQuestionRequest,
} from "../acp/XAiAcpExtension.ts";
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("grok");
const GROK_RESUME_VERSION = 1 as const;
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export interface GrokAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
readonly instanceId?: ProviderInstanceId;
}
interface PendingApproval {
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
}
type PendingUserInputResolution =
| { readonly _tag: "answered"; readonly answers: ProviderUserInputAnswers }
| { readonly _tag: "cancelled" };
interface PendingUserInput {
readonly resolution: Deferred.Deferred<PendingUserInputResolution>;
}
interface GrokSessionContext {
readonly threadId: ThreadId;
readonly acpSessionId: string;
session: ProviderSession;
readonly scope: Scope.Closeable;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
currentModelId: string | undefined;
stopped: boolean;
}
function settlePendingApprovalsAsCancelled(
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
): Effect.Effect<void> {
return Effect.forEach(
Array.from(pendingApprovals.values()),
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
{ discard: true },
);
}
function settlePendingUserInputsAsCancelled(
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
): Effect.Effect<void> {
return Effect.forEach(
Array.from(pendingUserInputs.values()),
(pending) => Deferred.succeed(pending.resolution, { _tag: "cancelled" }).pipe(Effect.ignore),
{ discard: true },
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
if (!isRecord(raw)) return undefined;
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
return { sessionId: raw.sessionId.trim() };
}
function selectPermissionOptionId(
request: EffectAcpSchema.RequestPermissionRequest,
decision: Exclude<ProviderApprovalDecision, "cancel">,
): string | undefined {
const kind =
decision === "acceptForSession"
? "allow_always"
: decision === "accept"
? "allow_once"
: "reject_once";
const option = request.options.find((entry) => entry.kind === kind);
return option?.optionId.trim() || undefined;
}
function selectAutoApprovedPermissionOption(
request: EffectAcpSchema.RequestPermissionRequest,
): string | undefined {
return (
selectPermissionOptionId(request, "acceptForSession") ??
selectPermissionOptionId(request, "accept")
);
}
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, GrokSessionContext>();
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate Grok runtime identifier.",
cause,
}),
),
);
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const mapAcpCallbackFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: "Failed to process Grok ACP callback.",
cause,
}),
),
);
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
const getThreadSemaphore = (threadId: string) =>
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
current.get(threadId),
);
return Option.match(existing, {
onNone: () =>
Semaphore.make(1).pipe(
Effect.map((semaphore) => {
const next = new Map(current);
next.set(threadId, semaphore);
return [semaphore, next] as const;
}),
),
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
});
});
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
Effect.gen(function* () {
if (!nativeEventLogger) return;
const observedAt = yield* nowIso;
yield* nativeEventLogger.write(
{
observedAt,
event: {
id: yield* randomUUIDv4,
kind: "notification",
provider: PROVIDER,
createdAt: observedAt,
method,
threadId,
payload,
},
},
threadId,
);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to write native Grok notification log.", {
cause,
threadId,
method,
}),
),
);
const emitPlanUpdate = (
ctx: GrokSessionContext,
payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
},
rawPayload: unknown,
method: string,
) =>
Effect.gen(function* () {
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
ctx.lastPlanFingerprint = fingerprint;
yield* offerRuntimeEvent(
makeAcpPlanUpdatedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
payload,
source: "acp.jsonrpc",
method,
rawPayload,
}),
);
});
const requireSession = (
threadId: ThreadId,
): Effect.Effect<GrokSessionContext, ProviderAdapterSessionNotFoundError> => {
const ctx = sessions.get(threadId);
if (!ctx || ctx.stopped) {
return Effect.fail(
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
);
}
return Effect.succeed(ctx);
};
const stopSessionInternal = (ctx: GrokSessionContext) =>
Effect.gen(function* () {
if (ctx.stopped) return;
ctx.stopped = true;
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
if (ctx.notificationFiber) {
yield* Fiber.interrupt(ctx.notificationFiber);
}
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
sessions.delete(ctx.threadId);
yield* offerRuntimeEvent({
type: "session.exited",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: ctx.threadId,
payload: { exitKind: "graceful" },
});
});
const startSession: GrokAdapterShape["startSession"] = (input) =>
withThreadLock(
input.threadId,
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
const cwd = path.resolve(input.cwd.trim());
const grokModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
);
const resumeSessionId = parseGrokResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
provider: PROVIDER,
threadId: input.threadId,
});
const acp = yield* makeGrokAcpRuntime({
grokSettings,
...(options?.environment ? { environment: options.environment } : {}),
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const started = yield* Effect.gen(function* () {
yield* Effect.forEach(
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
(method) =>
acp.handleExtRequest(method, XAiAskUserQuestionRequest, (params) =>
mapAcpCallbackFailure(
Effect.gen(function* () {
yield* logNative(input.threadId, method, params);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const resolution = yield* Deferred.make<PendingUserInputResolution>();
pendingUserInputs.set(requestId, { resolution });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractXAiAskUserQuestions(params) },
raw: {
source: "acp.grok.extension",
method,
payload: params,
},
});
const resolved = yield* Deferred.await(resolution);
pendingUserInputs.delete(requestId);
const resolvedAnswers = resolved._tag === "answered" ? resolved.answers : {};
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolvedAnswers },
raw: {
source: "acp.grok.extension",
method,
payload: params,
},
});
switch (resolved._tag) {
case "answered":
return makeXAiAskUserQuestionResponse(params, resolved.answers);
case "cancelled":
return makeXAiAskUserQuestionCancelledResponse();
}
}),
),
),
{ discard: true },
);
yield* acp.handleRequestPermission((params) =>
mapAcpCallbackFailure(
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params);
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, { decision });
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
const selectedOptionId =
resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved);
return {
outcome: selectedOptionId
? {
outcome: "selected" as const,
optionId: selectedOptionId,
}
: ({ outcome: "cancelled" } as const),
};
}),
),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
const requestedStartModelId = grokModelSelection?.model
? resolveGrokAcpBaseModelId(grokModelSelection.model)
: undefined;
const boundModelId = yield* applyGrokAcpModelSelection({
runtime: acp,
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
requestedModelId: requestedStartModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
...(boundModelId ? { model: resolveGrokAcpBaseModelId(boundModelId) } : {}),
threadId: input.threadId,
resumeCursor: {
schemaVersion: GROK_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
const ctx: GrokSessionContext = {
threadId: input.threadId,
acpSessionId: started.sessionId,
session,
scope: sessionScope,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
currentModelId: boundModelId,
stopped: false,
};
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
);
return;
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
}
}),
),
).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to process Grok runtime notification.", { cause }),
),
Effect.forkChild,
);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
sessionScopeTransferred = true;
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Grok ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
return session;
}).pipe(Effect.scoped),
);
const sendTurn: GrokAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const prepared = yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}),
);
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
ctx.turns = [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
);
});
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
});
const respondToRequest: GrokAdapterShape["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
const pending = ctx.pendingApprovals.get(requestId);
if (!pending) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/request_permission",
detail: `Unknown pending approval request: ${requestId}`,
});
}
yield* Deferred.succeed(pending.decision, decision);
});
const respondToUserInput: GrokAdapterShape["respondToUserInput"] = (
threadId,
requestId,
answers,
) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
const pending = ctx.pendingUserInputs.get(requestId);
if (!pending) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/ask_user_question",
detail: `Unknown pending user-input request: ${requestId}`,
});
}
yield* Deferred.succeed(pending.resolution, { _tag: "answered", answers });
});
const readThread: GrokAdapterShape["readThread"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
return { threadId, turns: ctx.turns };
});
const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>
Effect.gen(function* () {
yield* requireSession(threadId);
if (!Number.isInteger(numTurns) || numTurns < 1) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
});
}
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "thread/rollback",
detail: "Grok ACP sessions do not support provider-side rollback yet.",
});
});
const stopSession: GrokAdapterShape["stopSession"] = (threadId) =>
withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
}),
);
const listSessions: GrokAdapterShape["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
const hasSession: GrokAdapterShape["hasSession"] = (threadId) =>
Effect.sync(() => {
const c = sessions.get(threadId);
return c !== undefined && !c.stopped;
});
const stopAll: GrokAdapterShape["stopAll"] = () =>
Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true });
yield* Effect.addFinalizer(() =>
Effect.ignore(stopAll()).pipe(
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
return {
provider: PROVIDER,
capabilities: { sessionModelSwitch: "in-session" },
startSession,
sendTurn,
interruptTurn,
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
stopAll,
streamEvents,
} satisfies GrokAdapterShape;
});
}
@@ -1,108 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { GrokSettings } from "@t3tools/contracts";
import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus } from "./GrokProvider.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
describe("buildInitialGrokProviderSnapshot", () => {
it.effect("returns a disabled snapshot when settings.enabled is false", () =>
Effect.gen(function* () {
const snapshot = yield* buildInitialGrokProviderSnapshot(
decodeGrokSettings({ enabled: false }),
);
expect(snapshot.enabled).toBe(false);
expect(snapshot.status).toBe("disabled");
expect(snapshot.installed).toBe(false);
expect(snapshot.message).toContain("disabled");
}),
);
it.effect("returns a pending snapshot by default", () =>
Effect.gen(function* () {
const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({}));
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(true);
expect(snapshot.status).toBe("warning");
expect(snapshot.version).toBeNull();
expect(snapshot.message).toContain("Checking Grok");
expect(snapshot.requiresNewThreadForModelChange).toBe(true);
}),
);
});
it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
it.effect("reports the binary as missing when the binary path does not resolve", () =>
Effect.gen(function* () {
const snapshot = yield* checkGrokProviderStatus(
decodeGrokSettings({
enabled: true,
binaryPath: "/definitely/not/installed/grok-binary",
}),
);
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(false);
expect(snapshot.status).toBe("error");
expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
}),
);
it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
Effect.gen(function* () {
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
const grokPath = path.join(dir, "grok");
yield* fs.writeFileString(
grokPath,
["#!/bin/sh", 'printf "%s\\n" "broken grok install" >&2', "exit 2", ""].join("\n"),
);
yield* fs.chmod(grokPath, 0o755);
return yield* checkGrokProviderStatus(
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
);
}),
);
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(true);
expect(snapshot.status).toBe("error");
expect(snapshot.message).toContain("broken grok install");
}),
);
it.effect("reports an error when ACP model discovery is unavailable", () =>
Effect.gen(function* () {
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-success-" });
const grokPath = path.join(dir, "grok");
yield* fs.writeFileString(
grokPath,
["#!/bin/sh", 'printf "grok-cli 0.0.99\\n"', "exit 0", ""].join("\n"),
);
yield* fs.chmod(grokPath, 0o755);
return yield* checkGrokProviderStatus(
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
);
}),
);
expect(snapshot.status).toBe("error");
expect(snapshot.installed).toBe(true);
expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
expect(snapshot.message).toContain("ACP startup failed");
}),
);
});
@@ -1,324 +0,0 @@
import {
type GrokSettings,
type ModelCapabilities,
ProviderDriverKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
buildServerProvider,
detailFromResult,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import {
enrichProviderSnapshotWithVersionAdvisory,
type ProviderMaintenanceCapabilities,
} from "../providerMaintenance.ts";
import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";
const GROK_PRESENTATION = {
displayName: "Grok",
badgeLabel: "Early Access",
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
} as const;
const PROVIDER = ProviderDriverKind.make("grok");
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const VERSION_PROBE_TIMEOUT_MS = 4_000;
const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "grok-build",
name: "Grok Build",
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
},
];
export function buildInitialGrokProviderSnapshot(
grokSettings: GrokSettings,
): Effect.Effect<ServerProviderDraft> {
return Effect.gen(function* () {
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const models = grokModelsFromSettings(grokSettings.customModels);
if (!grokSettings.enabled) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Grok is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Checking Grok CLI availability...",
},
});
});
}
function grokModelsFromSettings(
customModels: ReadonlyArray<string> | undefined,
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings(
builtInModels,
PROVIDER,
customModels ?? [],
EMPTY_CAPABILITIES,
);
}
function buildGrokDiscoveredModelsFromSessionModelState(
modelState: EffectAcpSchema.SessionModelState | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (!modelState || modelState.availableModels.length === 0) {
return [];
}
const seen = new Set<string>();
return modelState.availableModels
.map((model): ServerProviderModel | undefined => {
const slug = resolveGrokAcpBaseModelId(model.modelId);
if (!slug || seen.has(slug)) {
return undefined;
}
seen.add(slug);
return {
slug,
name: model.name.trim() || slug,
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
};
})
.filter((model): model is ServerProviderModel => model !== undefined);
}
const discoverGrokModelsViaAcp = (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const acp = yield* makeGrokAcpRuntime({
grokSettings,
environment,
childProcessSpawner,
cwd: process.cwd(),
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
});
const started = yield* acp.start();
return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
}).pipe(Effect.scoped);
const runGrokVersionCommand = (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) => {
const command = grokSettings.binaryPath || "grok";
return spawnAndCollect(
command,
ChildProcess.make(command, ["--version"], {
env: environment,
shell: process.platform === "win32",
}),
);
};
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
if (!grokSettings.enabled) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Grok is disabled in T3 Code settings.",
},
});
}
const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(
Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionResult)) {
const error = versionResult.failure;
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Grok CLI (`grok`) is not installed or not on PATH."
: `Failed to execute Grok CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionResult.success)) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Grok CLI is installed but timed out while running `grok --version`.",
},
});
}
const versionOutput = versionResult.success.value;
const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
if (versionOutput.code !== 0) {
const detail = detailFromResult(versionOutput);
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: detail
? `Grok CLI is installed but failed to run. ${detail}`
: "Grok CLI is installed but failed to run.",
},
});
}
const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
Effect.exit,
);
if (Exit.isFailure(discoveryExit)) {
const detail = Cause.pretty(discoveryExit.cause);
yield* Effect.logWarning("Grok ACP model discovery failed", { cause: detail });
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `Grok CLI is installed but ACP startup failed. ${detail}`,
},
});
}
if (Option.isNone(discoveryExit.value)) {
yield* Effect.logWarning(
`Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
);
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
},
});
}
const discoveredModels = discoveryExit.value.value;
const models =
discoveredModels.length > 0
? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
: fallbackModels;
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version,
status: "ready",
auth: { status: "unknown" },
},
});
});
export const enrichGrokSnapshot = (input: {
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly httpClient: HttpClient.HttpClient;
}): Effect.Effect<void> => {
const { snapshot, publishSnapshot } = input;
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
Effect.catchCause((cause) =>
Effect.logWarning("Grok version advisory enrichment failed", {
cause: Cause.pretty(cause),
}),
),
Effect.asVoid,
);
};
@@ -10,7 +10,7 @@
*
* 2. **Many drivers, one registry** — the "all drivers slice" describe
* block below configures one instance of every shipped driver
* (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
* (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single
* `ProviderInstanceConfigMap` and asserts the registry boots them all
* without cross-contamination. This proves the driver SPI is uniform
* across every provider — any driver plugs into the registry through
@@ -18,7 +18,7 @@
*
* Every instance in these tests is configured with `enabled: false` so the
* provider-status checks short-circuit to pending/disabled snapshots
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
* without trying to spawn real `codex` / `claude` / `agent` / `opencode`
* binaries. That keeps the assertions focused on registry routing
* behaviour rather than the runtime details of each provider.
*/
@@ -28,7 +28,6 @@ import {
type ClaudeSettings,
type CodexSettings,
type CursorSettings,
type GrokSettings,
type OpenCodeSettings,
ProviderDriverKind,
type ProviderInstanceConfigMap,
@@ -42,7 +41,6 @@ import { ServerConfig } from "../../config.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { GrokDriver } from "../Drivers/GrokDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
@@ -81,13 +79,6 @@ const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings =>
...overrides,
});
const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
enabled: false,
binaryPath: "grok",
customModels: [],
...overrides,
});
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
enabled: false,
binaryPath: "opencode",
@@ -227,7 +218,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
});
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
@@ -253,13 +244,11 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
const codexId = ProviderInstanceId.make("codex_default");
const claudeId = ProviderInstanceId.make("claude_default");
const cursorId = ProviderInstanceId.make("cursor_default");
const grokId = ProviderInstanceId.make("grok_default");
const openCodeId = ProviderInstanceId.make("opencode_default");
const codexDriverKind = ProviderDriverKind.make("codex");
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
const cursorDriverKind = ProviderDriverKind.make("cursor");
const grokDriverKind = ProviderDriverKind.make("grok");
const openCodeDriverKind = ProviderDriverKind.make("opencode");
const configMap: ProviderInstanceConfigMap = {
@@ -284,12 +273,6 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
enabled: false,
config: makeCursorConfig({}),
},
[grokId]: {
driver: grokDriverKind,
displayName: "Grok",
enabled: false,
config: makeGrokConfig({}),
},
[openCodeId]: {
driver: openCodeDriverKind,
displayName: "OpenCode",
@@ -299,7 +282,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],
configMap,
});
@@ -309,9 +292,9 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
expect(unavailable).toEqual([]);
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(5);
expect(instances).toHaveLength(4);
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
[codexId, claudeId, cursorId, openCodeId].toSorted(),
);
// Instance lookup by id resolves each instance to its own bundle —
@@ -320,17 +303,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
const codex = yield* registry.getInstance(codexId);
const claude = yield* registry.getInstance(claudeId);
const cursor = yield* registry.getInstance(cursorId);
const grok = yield* registry.getInstance(grokId);
const openCode = yield* registry.getInstance(openCodeId);
expect(codex?.driverKind).toBe(codexDriverKind);
expect(claude?.driverKind).toBe(claudeDriverKind);
expect(cursor?.driverKind).toBe(cursorDriverKind);
expect(grok?.driverKind).toBe(grokDriverKind);
expect(openCode?.driverKind).toBe(openCodeDriverKind);
expect(codex?.displayName).toBe("Codex");
expect(claude?.displayName).toBe("Claude");
expect(cursor?.displayName).toBe("Cursor");
expect(grok?.displayName).toBe("Grok");
expect(openCode?.displayName).toBe("OpenCode");
// Every instance owns its own set of closures — no sharing across
@@ -338,29 +318,16 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// distinct references even when two instances happen to share a
// trait (e.g. Cursor + others all use a stub-or-real
// `textGeneration`; they must still be different object values).
const adapters = [
codex!.adapter,
claude!.adapter,
cursor!.adapter,
grok!.adapter,
openCode!.adapter,
];
const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];
expect(new Set(adapters).size).toBe(adapters.length);
const textGenerations = [
codex!.textGeneration,
claude!.textGeneration,
cursor!.textGeneration,
grok!.textGeneration,
openCode!.textGeneration,
];
expect(new Set(textGenerations).size).toBe(textGenerations.length);
const snapshots = [
codex!.snapshot,
claude!.snapshot,
cursor!.snapshot,
grok!.snapshot,
openCode!.snapshot,
];
const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];
expect(new Set(snapshots).size).toBe(snapshots.length);
// Snapshots identify themselves by `instanceId` + `driver` so
@@ -389,12 +356,6 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
`${cursorDriverKind}:instance:${cursorId}`,
);
const grokSnapshot = yield* grok!.snapshot.getSnapshot;
expect(grokSnapshot.instanceId).toBe(grokId);
expect(grokSnapshot.driver).toBe(grokDriverKind);
expect(grokSnapshot.enabled).toBe(false);
expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
@@ -992,7 +992,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: false },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
// `providerInstances` keys are branded `ProviderInstanceId`;
@@ -1087,7 +1086,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
}),
@@ -1188,7 +1186,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: false },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
providerInstances: {
@@ -1248,9 +1245,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
cursor: {
enabled: false,
},
grok: {
enabled: false,
},
},
}),
),
@@ -1311,7 +1305,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
"claudeAgent",
"codex",
"cursor",
"grok",
"opencode",
]);
assert.strictEqual(cursorProvider?.enabled, false);
@@ -1367,62 +1360,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
),
);
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
const fable5 = status.models.find((model) => model.slug === "claude-fable-5");
assert.strictEqual(fable5?.name, "Claude Fable 5");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.169\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Fable 5 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
assert.strictEqual(
status.models.some((model) => model.slug === "claude-fable-5"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.168 is too old for Claude Fable 5. Upgrade to v2.1.169 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.168\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
() =>
@@ -1,16 +0,0 @@
/**
* GrokAdapter — shape type for the Grok provider adapter.
*
* The driver model ({@link ../Drivers/GrokDriver}) bundles one adapter per
* instance as a captured closure, so this module only retains the shape
* interface as a naming anchor for the driver bundle.
*
* @module GrokAdapter
*/
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* GrokAdapterShape — per-instance Grok adapter contract.
*/
export interface GrokAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
Loaded 100 of 328 files, more files were not shown because too many files have changed in this diff. Show more