Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbc057a209 | ||
|
|
c0f91ed832 | ||
|
|
762b2df9e3 | ||
|
|
0e4a43519f | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 | ||
|
|
b76f161d55 | ||
|
|
75257d64e9 | ||
|
|
e1ce9f8500 | ||
|
|
602148f8fe | ||
|
|
92be60e7c1 | ||
|
|
0d6e9e9add | ||
|
|
8ab58a0b26 | ||
|
|
6f42bd9c88 | ||
|
|
5b26bd408b | ||
|
|
c04d15d3be | ||
|
|
9da430c828 | ||
|
|
a084fbbc0a | ||
|
|
b870a6e349 | ||
|
|
e1cb19b55b | ||
|
|
94fc117561 | ||
|
|
113b9d84c7 | ||
|
|
f60def2054 | ||
|
|
eda163ca17 | ||
|
|
3579005114 | ||
|
|
af3dfd229e | ||
|
|
969e6d274c | ||
|
|
769bdd251d | ||
|
|
295b9db113 | ||
|
|
b5a62504d4 | ||
|
|
ec18938bf9 | ||
|
|
5ae77c0d63 |
No files matched your search
@@ -10,3 +10,8 @@
|
||||
|
||||
# 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-...
|
||||
@@ -8,6 +8,7 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: none
|
||||
statuses: write
|
||||
|
||||
concurrency:
|
||||
group: relay-production
|
||||
@@ -43,13 +44,11 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: vp install --frozen-lockfile
|
||||
run-install: true
|
||||
|
||||
- name: Deploy production relay stage
|
||||
run: vp run --filter t3code-relay deploy -- --stage prod --yes
|
||||
id: deploy
|
||||
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
|
||||
@@ -57,3 +56,25 @@ jobs:
|
||||
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
|
||||
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
|
||||
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
|
||||
|
||||
- name: Publish relay deploy commit status
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const result = "${{ steps.deploy.outputs.result }}";
|
||||
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
|
||||
const description = changed
|
||||
? "Relay production deploy applied infrastructure changes."
|
||||
: result === "noop"
|
||||
? "Relay production deploy was a no-op."
|
||||
: `Relay production deploy completed with result: ${result}.`;
|
||||
|
||||
await github.rest.repos.createCommitStatus({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
sha: context.sha,
|
||||
state: "success",
|
||||
context: "Relay deploy / production",
|
||||
description,
|
||||
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
[tools]
|
||||
node = "24.13.1"
|
||||
@@ -1 +0,0 @@
|
||||
vp staged
|
||||
@@ -1,23 +1,26 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
|
||||
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
||||
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
npx t3@latest
|
||||
```
|
||||
|
||||
Tip: Use `npx t3@latest --help` for the full CLI reference.
|
||||
|
||||
### Desktop app
|
||||
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
@@ -46,25 +49,41 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
|
||||
|
||||
Relay observability: [docs/relay-observability.md](./docs/relay-observability.md)
|
||||
## Documentation
|
||||
|
||||
T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md)
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
- [Reference](./docs/reference/encyclopedia.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
### Install `vp`
|
||||
|
||||
T3 Code uses Vite+ so you'll need to install the global `vp` command-line tool.
|
||||
|
||||
#### macOS / Linux
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
vp install
|
||||
curl -fsSL https://vite.plus | bash
|
||||
```
|
||||
|
||||
T3 Cloud is optional and disabled in a fresh clone. To enable it for web, desktop, and mobile source
|
||||
builds, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the canonical
|
||||
public configuration there.
|
||||
#### Windows
|
||||
|
||||
```bash
|
||||
irm https://vite.plus/ps1 | iex
|
||||
```
|
||||
|
||||
Checkout their getting started guide for more information: https://viteplus.dev/guide/
|
||||
|
||||
### Install dependencies
|
||||
|
||||
```bash
|
||||
vp i
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
|
||||
@@ -27,8 +27,7 @@
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"vite-plus": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -29,9 +29,7 @@ export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alph
|
||||
export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment
|
||||
? [`t3code-dev-${devBundleIdSuffix || "local"}`]
|
||||
: ["t3code"];
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 10;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
@@ -108,7 +106,6 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
["T3CODE_DESKTOP_PROTOCOL_SCHEME", APP_PROTOCOL_SCHEMES[0]],
|
||||
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
|
||||
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
@@ -119,7 +116,7 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
'for arg in "$@"; do',
|
||||
' case "$arg" in',
|
||||
` ${APP_PROTOCOL_SCHEMES[0]}://auth/callback*)`,
|
||||
" t3code-dev://auth/callback*)",
|
||||
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
|
||||
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
|
||||
" fi",
|
||||
|
||||
@@ -52,7 +52,7 @@ const make = Effect.gen(function* () {
|
||||
Effect.map((parsed) =>
|
||||
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none<string>())),
|
||||
Effect.orElseSucceed(() => Option.none<string>()),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,10 +52,6 @@ export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopC
|
||||
) {}
|
||||
|
||||
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
|
||||
if (input.isDevelopment) {
|
||||
const override = process.env.T3CODE_DESKTOP_PROTOCOL_SCHEME?.trim();
|
||||
if (override) return override;
|
||||
}
|
||||
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ function mockSpawnerLayer(statusJson = "{}") {
|
||||
);
|
||||
}
|
||||
|
||||
function dieOnSpawnLayer() {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
|
||||
);
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return makeDesktopEnvironmentLayer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -86,6 +93,7 @@ function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
@@ -97,7 +105,7 @@ function makeLayer(input: {
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(mockSpawnerLayer()),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
Layer.provideMerge(networkLayer),
|
||||
Layer.provideMerge(DesktopConfig.layerTest(env)),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
@@ -116,13 +124,23 @@ const withHarness = <A, E, R>(
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-server-exposure-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
|
||||
return yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
baseDir,
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopServerExposure", () => {
|
||||
@@ -239,6 +257,27 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
// mode stays at default "local-only", tailscaleServeEnabled stays false.
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
|
||||
// would have crashed the test if the gate was missing.
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["http://127.0.0.1:4173/"],
|
||||
);
|
||||
}),
|
||||
{},
|
||||
dieOnSpawnLayer(),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses ConfigProvider desktop exposure overrides", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -22,8 +23,11 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
|
||||
|
||||
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
@@ -412,6 +416,18 @@ const make = Effect.gen(function* () {
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
|
||||
// spawn re-triggers the "Other apps" TCC prompt.
|
||||
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
),
|
||||
TAILSCALE_STATUS_CACHE_TTL,
|
||||
);
|
||||
|
||||
const readNetworkInterfaces = networkInterfaces.read;
|
||||
|
||||
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
|
||||
@@ -516,11 +532,20 @@ const make = Effect.gen(function* () {
|
||||
exposure: toResolvedExposure(state),
|
||||
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
|
||||
});
|
||||
|
||||
// Don't spawn the Tailscale CLI when the user hasn't opted into any
|
||||
// network exposure. The spawn itself triggers a macOS "Other apps"
|
||||
// TCC prompt on Mac App Store Tailscale builds.
|
||||
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
|
||||
return coreEndpoints;
|
||||
}
|
||||
|
||||
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: state.port,
|
||||
serveEnabled: state.tailscaleServeEnabled,
|
||||
servePort: state.tailscaleServePort,
|
||||
networkInterfaces: currentNetworkInterfaces,
|
||||
readMagicDnsName: cachedReadMagicDnsName,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
|
||||
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
|
||||
Effect.gen(function* () {
|
||||
let readerCalls = 0;
|
||||
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
readMagicDnsName: Effect.sync(() => {
|
||||
readerCalls += 1;
|
||||
return "desktop.tail.ts.net";
|
||||
}),
|
||||
});
|
||||
assert.equal(readerCalls, 1);
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["https://desktop.tail.ts.net/"],
|
||||
);
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
|
||||
() =>
|
||||
|
||||
@@ -105,6 +105,11 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
>;
|
||||
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
|
||||
}): Effect.fn.Return<
|
||||
readonly AdvertisedEndpoint[],
|
||||
@@ -112,15 +117,18 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
|
||||
> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const readDnsName =
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed<string | null>(null)),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? yield* readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
? yield* readDnsName
|
||||
: input.statusJson
|
||||
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null;
|
||||
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
|
||||
|
||||
@@ -1,29 +1,35 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { afterEach } from "vitest";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
function makeHttpClientLayer(
|
||||
handler: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
|
||||
) {
|
||||
return Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => handler(request)),
|
||||
);
|
||||
}
|
||||
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
|
||||
|
||||
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
|
||||
const calls: Array<FetchCall> = [];
|
||||
let responseIndex = 0;
|
||||
const fetchFn = ((input, init) => {
|
||||
calls.push([input, init ?? {}]);
|
||||
const response = responses[responseIndex++];
|
||||
if (!response) {
|
||||
return Promise.reject(new Error("Unexpected fetch call"));
|
||||
}
|
||||
return Promise.resolve(response);
|
||||
}) satisfies typeof fetch;
|
||||
|
||||
return { fetchFn, calls };
|
||||
};
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
@@ -33,16 +39,8 @@ describe("Desktop cloud auth IPC", () => {
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "sign_in_attempt" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
@@ -55,32 +53,25 @@ describe("Desktop cloud auth IPC", () => {
|
||||
body,
|
||||
});
|
||||
|
||||
assert(forwardedRequest !== null);
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
const [url, init] = forwardedRequest;
|
||||
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
|
||||
assert.equal(init.method, "POST");
|
||||
assert.equal(
|
||||
forwardedRequest.headers["content-type"],
|
||||
new Headers(init.headers).get("content-type"),
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(forwardedRequest.body._tag, "Uint8Array");
|
||||
if (forwardedRequest.body._tag === "Uint8Array") {
|
||||
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "client" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
@@ -89,9 +80,10 @@ describe("Desktop cloud auth IPC", () => {
|
||||
headers: {},
|
||||
});
|
||||
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
|
||||
}).pipe(Effect.provide(layer));
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
@@ -52,6 +54,68 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
|
||||
return url;
|
||||
}
|
||||
|
||||
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
|
||||
return Effect.gen(function* () {
|
||||
const method = (input.method ?? "GET") as "GET" | "POST";
|
||||
const headers = new Headers(input.headers);
|
||||
const response = yield* HttpClientRequest.make(method)(url).pipe(
|
||||
HttpClientRequest.setHeaders(headers),
|
||||
input.body === undefined
|
||||
? identity
|
||||
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
|
||||
HttpClient.execute,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed to execute.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const electronNetFetchLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const electronFetch = yield* Effect.promise(async () => {
|
||||
const electron = (await import("electron")) as {
|
||||
readonly net?: { readonly fetch?: typeof globalThis.fetch };
|
||||
};
|
||||
return typeof electron.net?.fetch === "function"
|
||||
? electron.net.fetch.bind(electron.net)
|
||||
: null;
|
||||
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
|
||||
|
||||
if (!electronFetch) {
|
||||
yield* Effect.logWarning(
|
||||
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
|
||||
);
|
||||
}
|
||||
|
||||
return FetchHttpClient.layer.pipe(
|
||||
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const createCloudAuthRequest = makeIpcMethod({
|
||||
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
@@ -108,47 +172,6 @@ export const fetchCloudAuth = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
|
||||
url,
|
||||
{
|
||||
headers: input.headers,
|
||||
},
|
||||
);
|
||||
const request =
|
||||
input.body === undefined
|
||||
? requestWithoutBody
|
||||
: HttpClientRequest.bodyText(
|
||||
requestWithoutBody,
|
||||
input.body,
|
||||
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
|
||||
);
|
||||
|
||||
const response = yield* HttpClient.execute(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
|
||||
}),
|
||||
});
|
||||
@@ -209,7 +209,7 @@ function readSettings(
|
||||
onSome: (raw) =>
|
||||
decodeDesktopSettingsJson(raw).pipe(
|
||||
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
|
||||
Effect.catch(() => Effect.succeed(defaultSettings)),
|
||||
Effect.orElseSucceed(() => defaultSettings),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -63,7 +63,7 @@ const readClientSettings = (
|
||||
onSome: (raw) =>
|
||||
decodeClientSettingsJson(raw).pipe(
|
||||
Effect.map((settings) => Option.some(settings)),
|
||||
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
|
||||
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -185,7 +185,7 @@ function readRegistryDocument(
|
||||
onSome: (raw) =>
|
||||
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.map(normalizeSavedEnvironmentRegistryDocument),
|
||||
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
|
||||
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -196,7 +196,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
|
||||
.pipe(
|
||||
Effect.timeoutOption(input.timeout),
|
||||
Effect.map(Option.getOrElse(() => "")),
|
||||
Effect.catch(() => Effect.succeed("")),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
|
||||
|
||||
return decodeAppUpdateYmlConfig(entries).pipe(
|
||||
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
|
||||
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
|
||||
Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -161,6 +161,11 @@ 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",
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractAgentNotificationDeepLink,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import Constants from "expo-constants";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
|
||||
}
|
||||
|
||||
function readRelayConfig(): { readonly url: string } | null {
|
||||
const relayUrl = resolveCloudPublicConfig().relayUrl;
|
||||
const relayUrl = resolveCloudPublicConfig().relay.url;
|
||||
if (!relayUrl) {
|
||||
logRegistrationDebug("relay registration skipped; relay config missing");
|
||||
return null;
|
||||
|
||||
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
|
||||
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
|
||||
const config = resolveCloudPublicConfig();
|
||||
const publishableKey = config.clerk.publishableKey;
|
||||
const relayUrl = config.relay.url;
|
||||
|
||||
useEffect(() => {
|
||||
if (!publishableKey || !relayUrl) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { vi } from "vitest";
|
||||
import { vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
|
||||
}
|
||||
|
||||
function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relayUrl;
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
createManagedRelayQueryManager,
|
||||
ManagedRelayClient,
|
||||
managedRelaySessionAtom,
|
||||
readManagedRelaySnapshotState,
|
||||
} from "@t3tools/client-runtime";
|
||||
@@ -9,23 +8,13 @@ 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 { mobileRuntime } from "../../lib/runtime";
|
||||
import { mobileRuntimeContextLayer } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
|
||||
const managedRelayAtomRuntime = Atom.runtime(
|
||||
Layer.effect(
|
||||
ManagedRelayClient,
|
||||
mobileRuntime.contextEffect.pipe(
|
||||
Effect.map((context) => Context.get(context, ManagedRelayClient)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
|
||||
|
||||
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveCloudPublicConfig } from "./publicConfig";
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
|
||||
describe("resolveCloudPublicConfig", () => {
|
||||
it("returns no cloud configuration for an unconfigured build", () => {
|
||||
expect(resolveCloudPublicConfig({})).toEqual({
|
||||
clerkPublishableKey: null,
|
||||
clerkJwtTemplate: null,
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: null,
|
||||
jwtTemplate: null,
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,11 +33,25 @@ 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({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: "https://relay.example.test",
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
|
||||
relay: { url: "http://relay.example.test" },
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: "pk_test_example",
|
||||
jwtTemplate: "t3-relay",
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: 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);
|
||||
});
|
||||
});
|
||||
@@ -2,40 +2,92 @@ 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 clerkPublishableKey: string | null;
|
||||
readonly clerkJwtTemplate: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
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) {
|
||||
return {
|
||||
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
|
||||
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
|
||||
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
|
||||
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),
|
||||
},
|
||||
} satisfies CloudPublicConfig;
|
||||
}
|
||||
|
||||
export function hasCloudPublicConfig(): boolean {
|
||||
const config = resolveCloudPublicConfig();
|
||||
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveRelayClerkTokenOptions() {
|
||||
const { clerkJwtTemplate } = resolveCloudPublicConfig();
|
||||
if (!clerkJwtTemplate) {
|
||||
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
|
||||
if (!jwtTemplate) {
|
||||
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
|
||||
}
|
||||
return relayClerkTokenOptions(clerkJwtTemplate);
|
||||
return relayClerkTokenOptions(jwtTemplate);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
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");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
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",
|
||||
});
|
||||
@@ -6,19 +6,20 @@ 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().relayUrl ?? "http://relay.invalid";
|
||||
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
|
||||
}
|
||||
|
||||
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
|
||||
|
||||
export const mobileRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
mobileHttpClientLayer,
|
||||
mobileCryptoLayer,
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
|
||||
),
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provideMerge(mobileCryptoLayer),
|
||||
Layer.provideMerge(mobileHttpClientLayer),
|
||||
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
|
||||
@@ -1,5 +1,5 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const values = new Map<string, string>();
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
setManagedRelaySession,
|
||||
} from "@t3tools/client-runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const environmentConnection = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("@expo/ui/swift-ui", () => ({
|
||||
HStack: "HStack",
|
||||
|
||||
@@ -38,12 +38,11 @@
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/bun": "1.3.14",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"vite-plus": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
|
||||
@@ -195,6 +195,31 @@ const buildCmd = Command.make(
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface PublishCommandConfig {
|
||||
readonly access: string;
|
||||
readonly tag: string;
|
||||
readonly provenance: boolean;
|
||||
readonly dryRun: boolean;
|
||||
}
|
||||
|
||||
const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
|
||||
const args = [
|
||||
"publish",
|
||||
"--filter",
|
||||
"t3",
|
||||
"--access",
|
||||
config.access,
|
||||
"--tag",
|
||||
config.tag,
|
||||
"--no-git-checks",
|
||||
];
|
||||
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
return args;
|
||||
};
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
@@ -260,17 +285,16 @@ const publishCmd = Command.make(
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: npm publish
|
||||
// Use: pnpm publish from the workspace root so pnpm-only workspace
|
||||
// config, including override selectors, is interpreted correctly.
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
const args = createVpPmPublishArgs(config);
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
ChildProcess.make("vp", ["pm", ...args], {
|
||||
cwd: repoRoot,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -35,7 +35,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { vi } from "vitest";
|
||||
import { vi } from "vite-plus/test";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
|
||||
@@ -152,9 +152,7 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
const nextConfigKey = runtimeConfigKey(config);
|
||||
const active = yield* Ref.get(activeRef);
|
||||
if (active?.configKey === nextConfigKey) {
|
||||
const isRunning = yield* active.child.isRunning.pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
|
||||
if (isRunning) {
|
||||
return {
|
||||
status: "running",
|
||||
|
||||
@@ -702,7 +702,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
const canonicalizeExistingPath = (value: string) =>
|
||||
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
|
||||
fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
|
||||
const normalizeStatusCacheKey = canonicalizeExistingPath;
|
||||
const nonRepositoryStatusDetails = {
|
||||
isRepo: false,
|
||||
@@ -766,7 +766,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null;
|
||||
|
||||
@@ -788,7 +788,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
);
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
|
||||
cwd: string,
|
||||
@@ -972,7 +972,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
) {
|
||||
const terms = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
Effect.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
|
||||
);
|
||||
const summary = summarizeGitActionResult(result, terms);
|
||||
let latestOpenPr: PullRequestInfo | null = null;
|
||||
@@ -1016,7 +1016,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
upstreamRef: finalBranchContext.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.flatMap((headContext) => findOpenPr(cwd, headContext)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1080,7 +1080,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (defaultFromProvider) {
|
||||
return defaultFromProvider;
|
||||
@@ -1686,7 +1686,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const changeRequestTerms = wantsPr
|
||||
? yield* sourceControlProvider(input.cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
Effect.orElseSucceed(() => getChangeRequestTerminologyForKind("unknown")),
|
||||
)
|
||||
: null;
|
||||
|
||||
|
||||
+8
-18
@@ -156,8 +156,8 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
otlpTracesUrl,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
|
||||
Effect.orElseSucceed(() =>
|
||||
HttpServerResponse.text("Trace export failed.", { status: 502 }),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
@@ -205,9 +205,7 @@ export const attachmentsRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
@@ -218,9 +216,7 @@ export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
@@ -265,9 +261,7 @@ export const projectFaviconRouteLayer = HttpRouter.add(
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
@@ -337,14 +331,12 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!indexData) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
@@ -355,9 +347,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!data) {
|
||||
return HttpServerResponse.text("Internal Server Error", { status: 500 });
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
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";
|
||||
@@ -18,6 +19,7 @@ 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(
|
||||
|
||||
@@ -335,7 +335,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
|
||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
||||
const readAttachmentRootEntries = fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
||||
|
||||
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
|
||||
function* (threadSegment: string, entry: string) {
|
||||
@@ -397,9 +397,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
|
||||
}
|
||||
|
||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -344,6 +344,26 @@ function runtimeEventToActivities(
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.denied": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "error",
|
||||
kind: "tool.denied",
|
||||
summary: `Tool denied: ${event.payload.toolName}`,
|
||||
payload: {
|
||||
toolName: event.payload.toolName,
|
||||
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
|
||||
...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),
|
||||
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "runtime.warning": {
|
||||
return [
|
||||
{
|
||||
@@ -351,7 +371,9 @@ function runtimeEventToActivities(
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
// Use the adapter-supplied message as the row label so the work log
|
||||
// shows what the warning was about, not a generic "Runtime warning".
|
||||
summary: truncateDetail(event.payload.message, 120),
|
||||
payload: {
|
||||
message: truncateDetail(event.payload.message),
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
|
||||
@@ -80,9 +80,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
continue;
|
||||
}
|
||||
const stats = yield* fileSystem
|
||||
.stat(candidate)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const stats = yield* fileSystem.stat(candidate).pipe(Effect.orElseSucceed(() => null));
|
||||
if (stats?.type === "File") {
|
||||
return candidate;
|
||||
}
|
||||
@@ -105,7 +103,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const sourcePath = path.join(cwd, sourceFile);
|
||||
const source = yield* fileSystem
|
||||
.readFileString(sourcePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -972,6 +972,52 @@ function sdkNativeMethod(message: SDKMessage): string {
|
||||
return `claude/${message.type}`;
|
||||
}
|
||||
|
||||
// Discriminator/identity keys carry no human-readable content; everything else
|
||||
// on an unmodeled SDK message is potentially worth surfacing in the work log.
|
||||
const SDK_MESSAGE_NOISE_KEYS = new Set([
|
||||
"type",
|
||||
"subtype",
|
||||
"uuid",
|
||||
"parent_uuid",
|
||||
"session_id",
|
||||
"parent_tool_use_id",
|
||||
"request_id",
|
||||
]);
|
||||
|
||||
// Pull the salient scalar content out of a message the adapter doesn't model
|
||||
// yet, so the work-log row shows what actually arrived (e.g. a notification's
|
||||
// text) instead of an opaque "unhandled subtype" placeholder. Nested structures
|
||||
// are left to the full payload retained in the event's `detail`.
|
||||
function previewUnknownSdkContent(message: unknown): string | undefined {
|
||||
if (!message || typeof message !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const parts: string[] = [];
|
||||
for (const [key, value] of Object.entries(message as Record<string, unknown>)) {
|
||||
if (SDK_MESSAGE_NOISE_KEYS.has(key)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(`${key}: ${trimmed}`);
|
||||
}
|
||||
} else if (typeof value === "number" || typeof value === "boolean") {
|
||||
parts.push(`${key}: ${String(value)}`);
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const joined = parts.join(" · ");
|
||||
return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;
|
||||
}
|
||||
|
||||
function describeUnknownSdkMessage(kind: string, message: unknown): string {
|
||||
const preview = previewUnknownSdkContent(message);
|
||||
return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;
|
||||
}
|
||||
|
||||
function sdkNativeItemId(message: SDKMessage): string | undefined {
|
||||
if (message.type === "assistant") {
|
||||
const maybeId = (message.message as { id?: unknown }).id;
|
||||
@@ -2267,10 +2313,31 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "thinking_tokens":
|
||||
return;
|
||||
case "permission_denied":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.denied",
|
||||
payload: {
|
||||
toolName: message.tool_name,
|
||||
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
|
||||
...(message.decision_reason ? { reason: message.decision_reason } : {}),
|
||||
...(message.agent_id ? { agentId: message.agent_id } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mirror_error":
|
||||
yield* emitRuntimeError(
|
||||
context,
|
||||
`Claude workspace mirror error: ${message.error}`,
|
||||
message,
|
||||
);
|
||||
return;
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
`Unhandled Claude system message subtype '${message.subtype}'.`,
|
||||
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
@@ -2384,7 +2451,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
`Unhandled Claude SDK message type '${message.type}'.`,
|
||||
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -347,7 +347,7 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
|
||||
.pipe(Effect.orElseSucceed(() => resolvedCommandPath));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
realCommandPath,
|
||||
@@ -406,7 +406,7 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
|
||||
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
@@ -417,7 +417,7 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
|
||||
}
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
return payload ? nonEmptyString(payload.version) : null;
|
||||
});
|
||||
|
||||
@@ -35,9 +35,7 @@ export const make = Effect.fn("makeReviewService")(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const canonicalizePath = (value: string) =>
|
||||
fileSystem
|
||||
.realPath(path.resolve(value))
|
||||
.pipe(Effect.catch(() => Effect.succeed(path.resolve(value))));
|
||||
fileSystem.realPath(path.resolve(value)).pipe(Effect.orElseSucceed(() => path.resolve(value)));
|
||||
|
||||
const isWithinRoot = (candidate: string, root: string) => {
|
||||
const relative = path.relative(root, candidate);
|
||||
|
||||
@@ -359,7 +359,7 @@ function responseError(
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.catch(() => Effect.succeed("")),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketApiError({
|
||||
@@ -524,7 +524,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
);
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
git.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
|
||||
readonly cwd: string;
|
||||
@@ -544,7 +544,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
if (!input.isCrossRepository) {
|
||||
const remoteName = yield* git
|
||||
.resolvePrimaryRemoteName(input.cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (remoteName) return remoteName;
|
||||
}
|
||||
|
||||
@@ -575,7 +575,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.none<string>(),
|
||||
})),
|
||||
Effect.catch(() => Effect.succeed(authFromConfig(config))),
|
||||
Effect.orElseSucceed(() => authFromConfig(config)),
|
||||
),
|
||||
listPullRequests: (input) =>
|
||||
resolveRepository(input).pipe(
|
||||
@@ -685,8 +685,8 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
{
|
||||
repository: getRepositoryFromLocator(locator),
|
||||
branchingModel: getBranchingModelFromLocator(locator).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
|
||||
Effect.orElseSucceed(
|
||||
(): typeof RawBitbucketBranchingModelSchema.Type | null => null,
|
||||
),
|
||||
),
|
||||
},
|
||||
|
||||
@@ -299,7 +299,7 @@ export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvide
|
||||
auth,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
),
|
||||
);
|
||||
const provider = providers.find((candidate) => candidate !== null);
|
||||
|
||||
@@ -277,12 +277,10 @@ export const make = Effect.fn("makeSourceControlRepositoryService")(function* ()
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (!hasCommits) {
|
||||
const details = yield* git
|
||||
.statusDetails(input.cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
|
||||
return {
|
||||
repository: toRepositoryInfo(providerKind, urls),
|
||||
remoteName,
|
||||
|
||||
@@ -62,7 +62,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
|
||||
const payload = yield* request.json.pipe(
|
||||
Effect.map((body) => body as RecordedBatchRequest["body"]),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
capturedRequests.push({ path: request.url, body: payload });
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="bun" />
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { PtyAdapter } from "../Services/PTY.ts";
|
||||
|
||||
@@ -1289,7 +1289,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
const threadPrefix = `${toSafeThreadId(threadId)}_`;
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(logsDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
||||
yield* Effect.forEach(
|
||||
entries.filter(
|
||||
(name) =>
|
||||
|
||||
@@ -140,9 +140,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -403,7 +403,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
"GitVcsDriver.detectRepository.commonDir",
|
||||
cwd,
|
||||
["rev-parse", "--git-common-dir"],
|
||||
).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
return {
|
||||
kind: "git" as const,
|
||||
|
||||
@@ -885,7 +885,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
const remoteNames = yield* runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe(
|
||||
Effect.map(parseRemoteNames),
|
||||
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
|
||||
Effect.orElseSucceed((): ReadonlyArray<string> => []),
|
||||
);
|
||||
return (
|
||||
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
|
||||
@@ -996,7 +996,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
cwd: string,
|
||||
branchName: string,
|
||||
) {
|
||||
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.catch(() => Effect.succeed([])));
|
||||
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => []));
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);
|
||||
return parsedRemoteRef?.branchName ?? branchName;
|
||||
});
|
||||
@@ -1042,7 +1042,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return pushDefaultRemote;
|
||||
}
|
||||
|
||||
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null));
|
||||
});
|
||||
|
||||
const ensureRemote: GitVcsDriver.GitVcsDriverShape["ensureRemote"] = Effect.fn("ensureRemote")(
|
||||
@@ -1090,7 +1090,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const defaultBranch =
|
||||
primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);
|
||||
@@ -1231,7 +1231,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
|
||||
originRemoteExists(cwd).pipe(Effect.orElseSucceed(() => false)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
@@ -1276,9 +1276,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
|
||||
const fallbackAheadCount =
|
||||
!upstreamRef && refName
|
||||
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
)
|
||||
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0))
|
||||
: null;
|
||||
|
||||
if (fallbackAheadCount !== null) {
|
||||
@@ -1294,9 +1292,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
aheadOfDefaultCount =
|
||||
fallbackAheadCount !== null
|
||||
? fallbackAheadCount
|
||||
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0));
|
||||
}
|
||||
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
@@ -1494,11 +1490,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
|
||||
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (comparableBaseBranch) {
|
||||
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (!publishRemoteName) {
|
||||
return {
|
||||
@@ -1508,7 +1504,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
|
||||
const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (hasRemoteBranch) {
|
||||
return {
|
||||
@@ -1545,7 +1541,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
|
||||
const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (currentUpstream) {
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, [
|
||||
@@ -1716,7 +1712,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
input.baseRef ??
|
||||
(branch
|
||||
? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null);
|
||||
|
||||
@@ -1729,18 +1725,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
);
|
||||
const dirtyUntracked = yield* readUntrackedReviewDiffs(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed({ diff: "", truncated: false })),
|
||||
Effect.orElseSucceed(() => ({ diff: "", truncated: false })),
|
||||
);
|
||||
const dirtyDiff = [dirtyTrackedResult.stdout.trimEnd(), dirtyUntracked.diff.trimEnd()]
|
||||
.filter((diff) => diff.length > 0)
|
||||
@@ -1757,15 +1751,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
)
|
||||
: null;
|
||||
const baseDiff = baseResult?.stdout ?? "";
|
||||
@@ -1827,7 +1819,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const listRefs: GitVcsDriver.GitVcsDriverShape["listRefs"] = Effect.fn("listRefs")(
|
||||
function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
Effect.orElseSucceed(() => new Map<string, number>()),
|
||||
);
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitVcsDriver.listRefs.branchNoColor",
|
||||
@@ -1970,7 +1962,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
const exists = yield* fileSystem.stat(candidatePath).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
currentPath = exists ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
|
||||
@@ -392,5 +392,20 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty listing when the OS denies directory access", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
|
||||
|
||||
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
|
||||
vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(denied);
|
||||
|
||||
const result = yield* workspaceEntries.browse({
|
||||
partialPath: appendSeparator(cwd),
|
||||
});
|
||||
expect(result).toEqual({ parentPath: cwd, entries: [] });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -188,7 +188,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const isInsideVcsWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
vcsRegistry.detect({ cwd }).pipe(
|
||||
Effect.map((handle) => handle !== null),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const filterVcsIgnoredPaths = (
|
||||
@@ -200,23 +200,23 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
handle
|
||||
? handle.driver.filterIgnoredPaths(cwd, relativePaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
Effect.orElseSucceed(() => relativePaths),
|
||||
)
|
||||
: Effect.succeed(relativePaths),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
Effect.orElseSucceed(() => relativePaths),
|
||||
);
|
||||
|
||||
const buildWorkspaceIndexFromVcs = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromVcs")(
|
||||
function* (cwd: string) {
|
||||
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!vcs) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = yield* vcs.driver
|
||||
.listWorkspaceFiles(cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
if (!listedFiles) {
|
||||
return null;
|
||||
@@ -431,7 +431,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")(
|
||||
function* (cwd) {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(cwd)),
|
||||
Effect.orElseSucceed(() => cwd),
|
||||
);
|
||||
yield* Cache.invalidate(workspaceIndexCache, cwd);
|
||||
if (normalizedCwd !== cwd) {
|
||||
@@ -457,7 +457,18 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}).pipe(
|
||||
// The user can deny macOS TCC prompts for the target dir (Documents,
|
||||
// Downloads, Music, etc.); surface an empty listing instead of an
|
||||
// error so the caller doesn't retry-loop the prompt.
|
||||
Effect.catchIf(
|
||||
(error) => {
|
||||
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === "EACCES" || code === "EPERM";
|
||||
},
|
||||
() => Effect.succeed<Dirent[]>([]),
|
||||
),
|
||||
);
|
||||
|
||||
const showHidden = endsWithSeparator || prefix.startsWith(".");
|
||||
const lowerPrefix = prefix.toLowerCase();
|
||||
|
||||
@@ -132,7 +132,7 @@ it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
|
||||
const escapedPath = path.resolve(cwd, "..", "escape.md");
|
||||
const escapedStat = yield* fileSystem
|
||||
.stat(escapedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
expect(escapedStat).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -37,7 +37,7 @@ export const makeWorkspacePaths = Effect.gen(function* () {
|
||||
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
|
||||
let workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!workspaceStat && options?.createIfMissing) {
|
||||
yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -50,7 +50,7 @@ export const makeWorkspacePaths = Effect.gen(function* () {
|
||||
);
|
||||
workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
}
|
||||
if (!workspaceStat) {
|
||||
return yield* new WorkspaceRootNotExistsError({
|
||||
|
||||
@@ -436,7 +436,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
repositoryIdentity,
|
||||
},
|
||||
} satisfies OrchestrationEvent;
|
||||
}).pipe(Effect.catch(() => Effect.succeed(event)));
|
||||
}).pipe(Effect.orElseSucceed(() => event));
|
||||
default:
|
||||
return Effect.succeed(event);
|
||||
}
|
||||
@@ -459,7 +459,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
project: nextProject,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
case "project.deleted":
|
||||
return Effect.succeed(
|
||||
@@ -487,7 +487,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
thread: nextThread,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
default:
|
||||
if (event.aggregateKind !== "thread") {
|
||||
@@ -503,7 +503,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
thread: nextThread,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -777,7 +777,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
thread.session !== null && thread.session.status !== "stopped",
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
)
|
||||
: false;
|
||||
const result = yield* dispatchNormalizedCommand(normalizedCommand);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node", "bun"],
|
||||
"types": ["node"],
|
||||
"lib": ["ESNext", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||
|
||||
@@ -62,7 +62,6 @@
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite": "catalog:",
|
||||
"vite-plus": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveDesktopCloudAuthOAuthOptions } from "./desktopAuth";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeDesktopClerkExternalAccountAdapter,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayWebClientId } from "@t3tools/contracts/relay";
|
||||
import { afterEach, beforeEach, vi } from "vitest";
|
||||
import { afterEach, beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { hasCloudPublicConfig } from "./publicConfig.ts";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
completeRelayClientInstallDialogClose,
|
||||
|
||||
@@ -562,11 +562,7 @@ function OpenCommandPaletteDialog() {
|
||||
!relativePathNeedsActiveProject,
|
||||
});
|
||||
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
|
||||
const {
|
||||
filteredEntries: filteredBrowseEntries,
|
||||
highlightedEntry: highlightedBrowseEntry,
|
||||
exactEntry: exactBrowseEntry,
|
||||
} = useMemo(
|
||||
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
|
||||
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
|
||||
[browseEntries, browseFilterQuery, highlightedItemValue],
|
||||
);
|
||||
@@ -587,27 +583,17 @@ function OpenCommandPaletteDialog() {
|
||||
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
|
||||
);
|
||||
|
||||
// Prefetch the parent and the most likely next child so browse navigation
|
||||
// stays warm without scanning every child directory in large trees.
|
||||
// Prefetch only the parent (for back-navigation). Prefetching the
|
||||
// highlighted child on every arrow-key press triggers a macOS TCC prompt
|
||||
// whenever the highlighted entry is a permission-gated home dir (Music,
|
||||
// Documents, Downloads, Desktop, etc.), so we wait for explicit navigation.
|
||||
useEffect(() => {
|
||||
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
|
||||
|
||||
if (canNavigateUp(query)) {
|
||||
prefetchBrowsePath(getBrowseParentPath(query)!);
|
||||
}
|
||||
|
||||
const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
|
||||
if (nextChild) {
|
||||
prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
|
||||
}
|
||||
}, [
|
||||
exactBrowseEntry,
|
||||
filteredBrowseEntries.length,
|
||||
highlightedBrowseEntry,
|
||||
isBrowsing,
|
||||
prefetchBrowsePath,
|
||||
query,
|
||||
]);
|
||||
}, [filteredBrowseEntries.length, isBrowsing, prefetchBrowsePath, query]);
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { page, userEvent } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { page, userEvent } from "vite-plus/test/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import type { DesktopCloudAuthOAuthOption } from "../../cloud/desktopAuth";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { page } from "vite-plus/test/browser";
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import {
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
import {
|
||||
PrimaryEnvironmentHttpClient,
|
||||
primaryEnvironmentHttpClientLive,
|
||||
@@ -28,6 +29,7 @@ const primaryHttpRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
|
||||
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
|
||||
httpHeaderRedactionLayer,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
"verbatimModuleSyntax": false,
|
||||
"jsx": "react-jsx",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"types": ["vite/client"],
|
||||
"paths": {
|
||||
"~/*": ["./src/*"]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Documentation
|
||||
|
||||
- [Getting started](./getting-started/quick-start.md)
|
||||
- [Architecture](./architecture/overview.md)
|
||||
- [Cloud](./cloud/t3-cloud-clerk.md)
|
||||
- [Integrations](./integrations/source-control-providers.md)
|
||||
- [Mobile](./mobile/app.md)
|
||||
- [Operations](./operations/ci.md)
|
||||
- [Providers](./providers/codex.md)
|
||||
- [Reference](./reference/encyclopedia.md)
|
||||
- [User guides](./user/keybindings.md)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -124,15 +124,11 @@ In **Clerk Dashboard > Native applications**, enable native application support
|
||||
entries under the mobile SSO redirect allowlist:
|
||||
|
||||
```text
|
||||
t3code-dev-<suffix>://auth/callback
|
||||
t3code-dev://auth/callback
|
||||
t3code://auth/callback
|
||||
```
|
||||
|
||||
The first entry is for local desktop development. The `<suffix>` is the lowercased alphanumeric
|
||||
form of the repository root directory name (e.g. `t3code-dev-t3code` for a checkout named
|
||||
`t3-code`). Each worktree gets a unique scheme so multiple simultaneous dev instances do not steal
|
||||
OAuth callbacks from each other. Add each worktree's scheme to the allowlist. The second entry is
|
||||
for packaged desktop builds.
|
||||
The first entry is for local desktop development. The second is for packaged desktop builds.
|
||||
The app also adds a request-scoped `t3_state` query parameter and validates it on callback. Initial
|
||||
sign-in and linked-account OAuth flows both return through this bridge. The desktop provider keeps
|
||||
Clerk's stock profile component, replaces its renderer-page callback with the custom-scheme callback,
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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 `docs/release.md` for full release/signing setup checklist.
|
||||
- See [Release Checklist](./release.md) for the 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.
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user