Compare commits

..
Author SHA1 Message Date
Julius Marminge 412962ec46 fix desktop context menu zoom positioning 2026-06-16 11:15:50 -07:00
772 changed files with 58326 additions and 50291 deletions

No files matched your search

-7
View File
@@ -8,13 +8,6 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
# returns a different RP ID or when multiple domains must be entitled.
# T3CODE_APPLE_TEAM_ID=ABC1234567
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
+46 -1
View File
@@ -38,7 +38,6 @@ jobs:
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
test:
name: Test
@@ -61,6 +60,52 @@ jobs:
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
-15
View File
@@ -425,9 +425,6 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -455,21 +452,9 @@ jobs:
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
exit 1
fi
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
security cms -D -i "$profile_path" >/dev/null
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
echo "macOS signing enabled."
args+=(--signed)
else
-3
View File
@@ -12,8 +12,6 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -22,7 +20,6 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
+21 -1
View File
@@ -31,12 +31,20 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const LAUNCHER_VERSION = 11;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
return configuredPort + 1;
}
return 13774;
}
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
@@ -92,6 +100,7 @@ function shellSingleQuote(value) {
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
@@ -100,12 +109,23 @@ 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_REGISTRATION_MANAGED", "1"],
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
'for arg in "$@"; do',
' case "$arg" in',
" 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",
" ;;",
" esac",
"done",
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
+5 -13
View File
@@ -11,7 +11,7 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -163,16 +163,6 @@ const bootstrap = Effect.gen(function* () {
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const rendererTarget = environment.isDevelopment
? Option.getOrThrow(environment.devServerUrl)
: backendConfig.httpBaseUrl;
yield* electronProtocol.registerDesktopProtocol({
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
targetOrigin: rendererTarget,
backendOrigin: backendConfig.httpBaseUrl,
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
});
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
@@ -199,8 +189,9 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const clerk = yield* DesktopClerk.DesktopClerk;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -218,7 +209,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* clerk.configure;
yield* cloudAuth.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -227,6 +218,7 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
-95
View File
@@ -1,95 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
storageAdapter: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
storageMock: vi.fn(),
}));
vi.mock("@clerk/electron", () => ({
createClerkBridge: createClerkBridgeMock,
}));
vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import {
createDesktopClerkBridge,
resolveDesktopClerkFrontendApiHostname,
} from "./DesktopClerk.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
describe("DesktopClerk", () => {
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
assert.equal(resolveDesktopClerkFrontendApiHostname(publishableKey), "clerk.t3.codes");
assert.equal(resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment: true,
} as unknown as DesktopEnvironment.DesktopEnvironmentShape);
return Effect.gen(function* () {
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme: "t3code-dev", host: "app" },
},
],
]);
assert.equal(cleanup.mock.calls.length, 1);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
assert.equal(createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme, host: "app" },
},
],
]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
-92
View File
@@ -1,92 +0,0 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export interface DesktopClerkShape {
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopClerk extends Context.Service<DesktopClerk, DesktopClerkShape>()(
"@t3tools/desktop/app/DesktopClerk",
) {}
export function resolveDesktopClerkFrontendApiHostname(
publishableKey: string | undefined,
): string | undefined {
const normalizedKey = publishableKey?.trim();
if (!normalizedKey) return undefined;
try {
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
} catch {
return undefined;
}
}
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
passkeys: true,
renderer: {
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
host: ElectronProtocol.DESKTOP_HOST,
},
});
}
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
);
return DesktopClerk.of({
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
yield* electronApp.on("second-instance", () => {
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
});
}).pipe(Effect.withSpan("desktop.clerk.configure")),
});
});
export const layer = Layer.effect(DesktopClerk, make);
@@ -0,0 +1,302 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthHarness {
readonly app: ElectronApp.ElectronAppShape;
readonly window: ElectronWindow.ElectronWindowShape;
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
readonly protocolRegistrations: {
readonly protocol: string;
readonly path?: string;
readonly args?: readonly string[];
}[];
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
readonly reveals: unknown[];
readonly layer: Layer.Layer<
| DesktopCloudAuth.DesktopCloudAuth
| DesktopEnvironment.DesktopEnvironment
| ElectronApp.ElectronApp
| ElectronWindow.ElectronWindow
>;
}
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
const sends: CloudAuthHarness["sends"] = [];
const reveals: unknown[] = [];
const mainWindow = { id: "main-window" };
const app = ElectronApp.ElectronApp.of({
metadata: Effect.succeed({
appVersion: "0.0.0-test",
appPath: "/tmp/t3-code-test",
isPackaged: !input.isDevelopment,
resourcesPath: "/tmp/t3-code-test/resources",
runningUnderArm64Translation: false,
}),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
protocolRegistrations.push({
protocol,
...(path === undefined ? {} : { path }),
...(args === undefined ? {} : { args }),
});
return true;
}),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: (eventName, listener) =>
Effect.sync(() => {
const erasedListener = listener as (...args: readonly unknown[]) => void;
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
}),
});
const window = ElectronWindow.ElectronWindow.of({
create: () => Effect.die("not used"),
main: Effect.succeed(Option.some(mainWindow as never)),
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: (target) =>
Effect.sync(() => {
reveals.push(target);
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
sends.push({ channel, args });
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
});
const environment = DesktopEnvironment.DesktopEnvironment.of({
isDevelopment: input.isDevelopment,
} as DesktopEnvironment.DesktopEnvironmentShape);
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
return {
app,
window,
listeners,
protocolRegistrations,
sends,
reveals,
layer: Layer.mergeAll(
DesktopCloudAuth.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provide(NodeServices.layer),
),
Layer.succeed(ElectronApp.ElectronApp, app),
Layer.succeed(ElectronWindow.ElectronWindow, window),
),
};
}
function emitAppEvent(
harness: CloudAuthHarness,
eventName: string,
...args: readonly unknown[]
): void {
for (const listener of harness.listeners.get(eventName) ?? []) {
listener(...args);
}
}
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
describe("DesktopCloudAuth", () => {
it("uses separate callback schemes for packaged and development builds", () => {
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
"t3code",
);
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
"t3code-dev",
);
});
it("builds a native callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code",
state: "state-1",
}),
"t3code://auth/callback?t3_state=state-1",
);
});
it("accepts only the expected scheme, host, path, and state", () => {
assert.isNotNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
});
it("builds a native development callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code-dev",
state: "state-1",
}),
"t3code-dev://auth/callback?t3_state=state-1",
);
});
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
let prevented = false;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => (prevented = true) },
callbackUrl.toString(),
);
yield* flushCloudAuthDispatch;
assert.isTrue(prevented);
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code-dev"],
);
assert.isString(harness.protocolRegistrations[0]?.path);
assert.isArray(harness.protocolRegistrations[0]?.args);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.lengthOf(harness.reveals, 1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
const harness = makeHarness({ isDevelopment: false });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const validCallback = new URL(redirectUrl);
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
const invalidCallback = new URL(validCallback);
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
invalidCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, []);
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code"],
);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [validCallback.toString()],
},
]);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect(
"routes second-instance callbacks and reveals the window for non-callback launches",
() => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
yield* flushCloudAuthDispatch;
const revealCountAfterCallback = harness.reveals.length;
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.equal(revealCountAfterCallback, 1);
assert.equal(harness.reveals.length, 2);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
},
);
});
+330
View File
@@ -0,0 +1,330 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import type * as Electron from "electron";
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
"DesktopCloudAuthCallbackServerError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to start the desktop cloud auth callback server.";
}
}
interface PendingCloudAuthRequest {
readonly state: string;
readonly redirectUrl: string;
readonly close: () => void;
}
export interface DesktopCloudAuthShape {
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
"@t3tools/desktop/app/DesktopCloudAuth",
) {}
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
}
export function buildCloudAuthCallbackUrl(input: {
readonly scheme: string;
readonly state: string;
}): string {
const url = new URL(
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
);
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
return url.toString();
}
export function parseCloudAuthCallbackUrl(input: {
readonly rawUrl: unknown;
readonly scheme: string;
readonly state: string;
}): URL | null {
if (typeof input.rawUrl !== "string") {
return null;
}
try {
const url = new URL(input.rawUrl);
if (url.protocol !== `${input.scheme}:`) return null;
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
return url;
} catch {
return null;
}
}
export function findCloudAuthCallbackUrl(input: {
readonly values: readonly unknown[];
readonly scheme: string;
readonly state: string;
}): URL | null {
for (const value of input.values) {
const url = parseCloudAuthCallbackUrl({
rawUrl: value,
scheme: input.scheme,
state: input.state,
});
if (url) return url;
}
return null;
}
export function resolveProtocolClientLaunchArgs(input: {
readonly argv: readonly string[];
}): readonly string[] {
return input.argv.slice(1);
}
function resolveConfiguredProtocolClient(): {
readonly path: string;
readonly args: readonly string[];
} | null {
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
if (!path) return null;
return {
path,
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
.split("\n")
.map((arg) => arg.trim())
.filter((arg) => arg.length > 0),
};
}
function isProtocolRegistrationManagedExternally(): boolean {
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
}
function resolveProtocolCallbackForwardUrl(): URL | null {
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
if (!rawUrl) return null;
try {
const url = new URL(rawUrl);
if (url.protocol !== "http:") return null;
if (url.hostname !== "127.0.0.1") return null;
if (url.pathname !== "/auth/callback") return null;
if (!url.port) return null;
return url;
} catch {
return null;
}
}
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
request?.close();
return null;
};
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
}
function ignoreCloudAuthCallback(_rawUrl: string) {}
function startProtocolCallbackForwardServer(
callbackUrl: URL,
dispatch: (rawUrl: string) => void,
): Effect.Effect<void, never, Scope.Scope> {
const port = Number.parseInt(callbackUrl.port, 10);
const routesLayer = HttpRouter.add(
"POST",
"/auth/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const rawUrl = yield* request.text;
yield* Effect.sync(() => {
dispatch(rawUrl);
});
return HttpServerResponse.empty({ status: 204 });
}),
);
return Effect.gen(function* () {
const NodeHttp = yield* Effect.promise(() => import("node:http"));
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
host: callbackUrl.hostname,
port,
});
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
Effect.forkScoped,
);
});
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
const makeCloudAuthRequestState = Effect.gen(function* () {
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
return `${left}${right}`.replaceAll("-", "");
});
return DesktopCloudAuth.of({
createRequest: Effect.gen(function* () {
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
const state = yield* makeCloudAuthRequestState.pipe(
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
);
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
const timeout = createCloudAuthRequestTimeout(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
});
pendingAuthRequest = {
state,
redirectUrl,
close: () => clearTimeout(timeout),
};
return redirectUrl;
}),
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const scope = yield* Scope.Scope;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
}),
);
if (isProtocolRegistrationManagedExternally()) {
// Development macOS launchers set the default URL handler before the stock Electron
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
} else if (environment.isDevelopment) {
const configuredClient = resolveConfiguredProtocolClient();
if (configuredClient) {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
configuredClient.path,
configuredClient.args,
);
} else {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
process.execPath,
resolveProtocolClientLaunchArgs({ argv: process.argv }),
);
}
} else {
yield* electronApp.setAsDefaultProtocolClient(scheme);
}
dispatchCloudAuthCallback = (rawUrl: string) => {
const pending = pendingAuthRequest;
const callbackUrl = pending
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
: null;
if (!callbackUrl) {
return;
}
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
void runPromise(
Effect.gen(function* () {
yield* electronWindow.sendAll(
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
callbackUrl.toString(),
);
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
};
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
if (environment.isDevelopment && protocolCallbackForwardUrl) {
yield* startProtocolCallbackForwardServer(
protocolCallbackForwardUrl,
dispatchCloudAuthCallback,
);
}
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
if (!hasInstanceLock) {
return yield* electronApp.quit;
}
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
event.preventDefault?.();
dispatchCloudAuthCallback(rawUrl);
});
yield* electronApp.on<[Electron.Event, readonly string[]]>(
"second-instance",
(_event, argv) => {
const values = resolveProtocolClientLaunchArgs({ argv });
const pending = pendingAuthRequest;
const callbackUrl = pending
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
: null;
if (callbackUrl) {
dispatchCloudAuthCallback(callbackUrl.toString());
return;
}
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
},
);
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
});
});
export const layer = Layer.effect(DesktopCloudAuth, make);
@@ -0,0 +1,96 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
function makeSafeStorageLayer(input: { readonly available: boolean }) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(input.available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
decryptString: (value) => {
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted token"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopCloudAuthTokenStore.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
Layer.provideMerge(NodeServices.layer),
);
}
const withTokenStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
input?: { readonly encryptionAvailable?: boolean },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-cloud-auth-token-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopCloudAuthTokenStore", () => {
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
yield* tokenStore.clear;
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
),
);
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
{ encryptionAvailable: false },
),
);
});
@@ -0,0 +1,155 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthTokenDocument {
readonly version: number;
readonly encryptedClientJwt: string;
}
const CloudAuthTokenDocumentSchema = Schema.Struct({
version: Schema.Number,
encryptedClientJwt: Schema.String,
});
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
}
}
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop cloud auth token.";
}
}
export interface DesktopCloudAuthTokenStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopCloudAuthTokenStoreDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
token: string,
) => Effect.Effect<
boolean,
| DesktopCloudAuthTokenStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopCloudAuthTokenStore extends Context.Service<
DesktopCloudAuthTokenStore,
DesktopCloudAuthTokenStoreShape
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
tokenPath: string,
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
fileSystem.readFileString(tokenPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
}),
),
);
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly tokenPath: string;
readonly document: CloudAuthTokenDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.tokenPath);
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.tokenPath);
});
export const layer = Layer.effect(
DesktopCloudAuthTokenStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
return DesktopCloudAuthTokenStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, tokenPath);
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
tokenPath,
document: { version: 1, encryptedClientJwt },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
return true;
}),
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
Effect.catch(() => Effect.void),
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
),
});
}),
);
@@ -1,297 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.cause, permissionError);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -1,328 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
"DesktopConnectionCatalogStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
"DesktopConnectionCatalogStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode the desktop connection catalog.";
}
}
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
"DesktopConnectionCatalogStoreReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
"DesktopConnectionCatalogStoreMigrationError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to migrate legacy desktop saved environments.";
}
}
export interface DesktopConnectionCatalogStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
DesktopConnectionCatalogStoreShape
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
PlatformError.PlatformError | Schema.SchemaError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.catalogPath);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const layer = Layer.effect(
DesktopConnectionCatalogStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry;
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
yield* writeCatalog(encoded);
return Option.some(encoded);
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
}),
);
@@ -1,82 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: {},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "desktop-bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
),
),
);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
});
@@ -1,77 +0,0 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
import { HttpClient } from "effect/unstable/http";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
export interface DesktopLocalEnvironmentAuthShape {
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
}
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
"DesktopLocalEnvironmentAuthError",
)<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
DesktopLocalEnvironmentAuthShape
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const layer = Layer.effect(
DesktopLocalEnvironmentAuth,
Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
const getBearerToken = mutex
.withPermits(1)(
Effect.gen(function* () {
const cached = yield* Ref.get(tokenRef);
if (Option.isSome(cached)) {
return cached.value;
}
const configOption = yield* backendManager.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthError({
message: "Local backend is not configured.",
});
}
const config = configOption.value;
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential: config.bootstrap.desktopBootstrapToken,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
},
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.mapError(
(cause) =>
new DesktopLocalEnvironmentAuthError({
message: "Failed to create the local desktop bearer session.",
cause,
}),
),
);
yield* Ref.set(tokenRef, Option.some(session.access_token));
return session.access_token;
}),
)
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
}),
);
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vite-plus/test";
import { scaleContextMenuPositionForElectron } from "./contextMenuPosition.ts";
describe("scaleContextMenuPositionForElectron", () => {
it("scales CSS pixel positions by the renderer zoom factor", () => {
expect(scaleContextMenuPositionForElectron({ x: 120, y: 80 }, 0.8)).toEqual({
x: 96,
y: 64,
});
expect(scaleContextMenuPositionForElectron({ x: 120, y: 80 }, 1.25)).toEqual({
x: 150,
y: 100,
});
});
it("leaves missing positions missing", () => {
expect(scaleContextMenuPositionForElectron(undefined, 0.8)).toBeUndefined();
});
it("falls back to unscaled coordinates for invalid zoom factors", () => {
expect(scaleContextMenuPositionForElectron({ x: 120, y: 80 }, 0)).toEqual({
x: 120,
y: 80,
});
expect(scaleContextMenuPositionForElectron({ x: 120, y: 80 }, Number.NaN)).toEqual({
x: 120,
y: 80,
});
});
});
+19
View File
@@ -0,0 +1,19 @@
export interface ContextMenuPosition {
readonly x: number;
readonly y: number;
}
export function scaleContextMenuPositionForElectron(
position: ContextMenuPosition | undefined,
zoomFactor: number,
): ContextMenuPosition | undefined {
if (position === undefined) {
return undefined;
}
const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
return {
x: position.x * normalizedZoomFactor,
y: position.y * normalizedZoomFactor,
};
}
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vite-plus/test";
import { normalizeDesktopZoomFactor, resolveDesktopZoomCssVariables } from "./desktopZoom.ts";
describe("desktopZoom", () => {
it("gradually reduces zoomed-out titlebar leading spacing", () => {
expect(resolveDesktopZoomCssVariables(0.8)).toEqual({
titlebarHeight: "65px",
titlebarLeadingOffset: "106.5px",
});
expect(resolveDesktopZoomCssVariables(0.6)).toEqual({
titlebarHeight: "86.66666666666667px",
titlebarLeadingOffset: "136.66666666666669px",
});
});
it("keeps a minimum leading offset clear of the traffic lights", () => {
expect(resolveDesktopZoomCssVariables(0.4)).toEqual({
titlebarHeight: "130px",
titlebarLeadingOffset: "205px",
});
});
it("compensates titlebar spacing when zoomed in", () => {
expect(resolveDesktopZoomCssVariables(1.25)).toEqual({
titlebarHeight: "41.6px",
titlebarLeadingOffset: "72px",
});
});
it("normalizes invalid zoom factors", () => {
expect(normalizeDesktopZoomFactor(0)).toBe(1);
expect(normalizeDesktopZoomFactor(Number.NaN)).toBe(1);
expect(resolveDesktopZoomCssVariables(0)).toEqual({
titlebarHeight: "52px",
titlebarLeadingOffset: "90px",
});
});
});
+30
View File
@@ -0,0 +1,30 @@
export interface DesktopZoomCssVariables {
readonly titlebarHeight: string;
readonly titlebarLeadingOffset: string;
}
export const DESKTOP_TITLEBAR_HEIGHT_PX = 52;
export const DESKTOP_TITLEBAR_LEADING_OFFSET_PX = 90;
export const DESKTOP_TITLEBAR_MIN_SCREEN_LEADING_OFFSET_PX = 82;
export const DESKTOP_TITLEBAR_ZOOM_OUT_SCREEN_OFFSET_STEP_PX = 24;
export function normalizeDesktopZoomFactor(zoomFactor: number): number {
return Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
}
export function resolveDesktopZoomCssVariables(zoomFactor: number): DesktopZoomCssVariables {
const normalizedZoomFactor = normalizeDesktopZoomFactor(zoomFactor);
const screenLeadingOffset =
normalizedZoomFactor >= 1
? DESKTOP_TITLEBAR_LEADING_OFFSET_PX
: Math.max(
DESKTOP_TITLEBAR_MIN_SCREEN_LEADING_OFFSET_PX,
DESKTOP_TITLEBAR_LEADING_OFFSET_PX -
(1 - normalizedZoomFactor) * DESKTOP_TITLEBAR_ZOOM_OUT_SCREEN_OFFSET_STEP_PX,
);
return {
titlebarHeight: `${DESKTOP_TITLEBAR_HEIGHT_PX / normalizedZoomFactor}px`,
titlebarLeadingOffset: `${screenLeadingOffset / normalizedZoomFactor}px`,
};
}
@@ -99,7 +99,6 @@ export const layer = Layer.effect(
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
@@ -1,132 +1,105 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
netFetchMock: vi.fn(),
unhandleMock: vi.fn(),
}));
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
vi.mock("electron", () => ({
net: { fetch: netFetchMock },
protocol: { handle: handleMock, unhandle: unhandleMock },
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
handleMock.mockReset();
netFetchMock.mockReset();
unhandleMock.mockReset();
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
});
it.effect("proxies the stable renderer origin to the current app server", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock.mockResolvedValue(new Response("ok"));
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"img-src 'self' t3code-dev: blob: data: http: https:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"font-src 'self' t3code-dev: data:",
);
}),
);
assert.deepEqual(
handleMock.mock.calls.map((call) => call[0]),
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
),
),
);
it.effect("rejects custom protocol requests for another host", () =>
it.effect("scopes registered file protocols", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
const directives = Object.fromEntries(
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
"blob:",
"data:",
"http:",
"https:",
]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
+218 -92
View File
@@ -1,27 +1,18 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export const DESKTOP_HOST = "app";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export function getDesktopScheme(isDevelopment: boolean): string {
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export function getDesktopOrigin(isDevelopment: boolean): string {
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export const DESKTOP_SCHEME = "t3";
export class ElectronProtocolRegistrationError extends Data.TaggedError(
"ElectronProtocolRegistrationError",
@@ -30,117 +21,252 @@ export class ElectronProtocolRegistrationError extends Data.TaggedError(
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: protocol.`;
return `Failed to register ${this.scheme}: file protocol.`;
}
}
export interface DesktopProtocolRegistrationInput {
readonly scheme: string;
readonly targetOrigin: URL;
readonly backendOrigin: URL;
readonly clerkFrontendApiHostname: string | undefined;
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
}
export interface ElectronProtocolShape {
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
readonly registerFileProtocol: <E, R>(input: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
? `https://${input.clerkFrontendApiHostname}`
: undefined;
const scriptSources = [
"'self'",
"'unsafe-inline'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
];
// The renderer connects directly to user-configured environments in addition to
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
"form-action 'self'",
].join("; ");
}
function withContentSecurityPolicy(response: Response, policy: string): Response {
const headers = new Headers(response.headers);
headers.set("Content-Security-Policy", policy);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
async function proxyRequest(
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
for (const candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const init: RequestInit = {
method: request.method,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
function* (input: DesktopProtocolRegistrationInput) {
if (yield* Ref.get(registered)) return;
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
Electron.protocol.handle(input.scheme, (request) =>
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
const registered = Electron.protocol.registerFileProtocol(
scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
);
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
},
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
() =>
Effect.sync(() => {
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
}),
),
),
);
},
);
return ElectronProtocol.of({ registerDesktopProtocol });
const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
});
export const layer = Layer.effect(ElectronProtocol, make);
@@ -1,9 +1,9 @@
import * as Electron from "electron";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
+23 -9
View File
@@ -1,12 +1,21 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -33,7 +42,6 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
@@ -48,13 +56,14 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
@@ -75,6 +84,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(createCloudAuthRequest);
yield* ipc.handle(getCloudAuthToken);
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
+12 -5
View File
@@ -3,7 +3,14 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const ZOOM_FACTOR_CHANGED_CHANNEL = "desktop:zoom-factor-changed";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
@@ -12,13 +19,13 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
@@ -0,0 +1,97 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
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")}`;
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 {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
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");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
+177
View File
@@ -0,0 +1,177 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
});
}
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,
result: Schema.String,
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
return yield* cloudAuth.createRequest;
}),
});
export const getCloudAuthToken = makeIpcMethod({
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return Option.getOrNull(yield* tokenStore.get);
}),
});
export const setCloudAuthToken = makeIpcMethod({
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return yield* tokenStore.set(token);
}),
});
export const clearCloudAuthToken = makeIpcMethod({
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
yield* tokenStore.clear;
}),
});
export const fetchCloudAuth = makeIpcMethod({
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
payload: DesktopCloudAuthFetchInputSchema,
result: DesktopCloudAuthFetchResultSchema,
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
const url = yield* Effect.try({
try: () => validateClerkFrontendApiUrl(input.url),
catch: (cause) =>
cause instanceof DesktopCloudAuthFetchError
? cause
: new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch received an invalid URL.",
cause,
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getConnectionCatalog = makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -1,11 +1,11 @@
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
-11
View File
@@ -10,7 +10,6 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
@@ -65,16 +64,6 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
}),
});
export const getLocalEnvironmentBearerToken = makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* localAuth.getBearerToken;
}),
});
export const pickFolder = makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
+8 -21
View File
@@ -27,13 +27,12 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
@@ -118,7 +117,8 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -148,30 +148,17 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(desktopWindowLayer),
);
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(desktopEnvironmentLayer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ElectronApp.layer),
);
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
Layer.flatMap(() =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
+78 -10
View File
@@ -4,12 +4,57 @@ import type {
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import { contextBridge, ipcRenderer, webFrame } from "electron";
import { normalizeDesktopZoomFactor, resolveDesktopZoomCssVariables } from "./desktopZoom.ts";
import * as IpcChannels from "./ipc/channels.ts";
import { scaleContextMenuPositionForElectron } from "./contextMenuPosition.ts";
exposeClerkBridge({ passkeys: true });
let lastAppliedDesktopZoomFactor: number | undefined;
let pendingDesktopZoomSyncFrame: number | null = null;
function applyDesktopZoomCssVariables(zoomFactor: number) {
const normalizedZoomFactor = normalizeDesktopZoomFactor(zoomFactor);
if (lastAppliedDesktopZoomFactor === normalizedZoomFactor) {
return;
}
lastAppliedDesktopZoomFactor = normalizedZoomFactor;
const variables = resolveDesktopZoomCssVariables(normalizedZoomFactor);
document.documentElement.style.setProperty("--desktop-zoom-factor", String(normalizedZoomFactor));
document.documentElement.style.setProperty("--desktop-titlebar-height", variables.titlebarHeight);
document.documentElement.style.setProperty(
"--desktop-titlebar-leading-offset",
variables.titlebarLeadingOffset,
);
}
function syncDesktopZoomCssVariables() {
applyDesktopZoomCssVariables(webFrame.getZoomFactor());
}
function scheduleDesktopZoomCssVariableSync() {
if (pendingDesktopZoomSyncFrame !== null) {
return;
}
pendingDesktopZoomSyncFrame = window.requestAnimationFrame(() => {
pendingDesktopZoomSyncFrame = null;
syncDesktopZoomCssVariables();
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", syncDesktopZoomCssVariables, { once: true });
} else {
syncDesktopZoomCssVariables();
}
window.addEventListener("resize", scheduleDesktopZoomCssVariableSync);
window.visualViewport?.addEventListener("resize", scheduleDesktopZoomCssVariableSync);
ipcRenderer.on(IpcChannels.ZOOM_FACTOR_CHANGED_CHANNEL, (_event, zoomFactor: unknown) => {
if (typeof zoomFactor !== "number") return;
applyDesktopZoomCssVariables(zoomFactor);
});
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
@@ -42,15 +87,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
setConnectionCatalog: (catalog) =>
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
getSavedEnvironmentRegistry: () =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
@@ -97,9 +146,28 @@ contextBridge.exposeInMainWorld("desktopBridge", {
showContextMenu: (items, position) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
items,
...(position === undefined ? {} : { position }),
...(position === undefined
? {}
: { position: scaleContextMenuPositionForElectron(position, webFrame.getZoomFactor()) }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
setCloudAuthToken: (token: string) =>
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
onCloudAuthCallback: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
if (typeof rawUrl !== "string") return;
listener(rawUrl);
};
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
};
},
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
-52
View File
@@ -128,58 +128,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
const loadURL = vi.fn(async () => undefined);
const listeners = new Map<string, (...args: never[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "about:blank",
getTitle: () => "",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.navigate("tab_pending", "localhost:3200");
expect(yield* manager.automationStatus("tab_pending")).toEqual({
available: false,
visible: true,
tabId: "tab_pending",
url: "http://localhost:3200/",
title: "",
loading: true,
});
yield* manager.registerWebview("tab_pending", 42);
yield* Effect.yieldNow;
expect(loadURL).toHaveBeenCalledOnce();
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
+12 -89
View File
@@ -1195,103 +1195,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) {
return [
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
tabs,
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const next: PreviewTabState = {
...current,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
updatedAt: registeredAt,
};
return [
Option.some({
state: next,
pendingUrl,
}),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
Effect.ignore,
);
}
yield* update(tabId, {
webContentsId,
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor: tab.zoomFactor,
});
if (Option.isNone(registration)) {
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt("registerWebview.sendTheme", () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
if (
pendingUrl &&
latestNavStatus?.kind === "Loading" &&
latestNavStatus.url === pendingUrl &&
wc.getURL() !== pendingUrl
) {
runFork(
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
Effect.ignore,
),
);
}
});
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
const wc = yield* requireWebContents(tabId);
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
const updatedAt = yield* currentIso;
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
const next: PreviewTabState = {
tabId,
webContentsId: current?.webContentsId ?? null,
navStatus: {
kind: "Loading",
url,
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
},
canGoBack: current?.canGoBack ?? false,
canGoForward: current?.canGoForward ?? false,
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
controller: current?.controller ?? "none",
updatedAt,
};
return [
next,
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
yield* attempt("navigate.reload", () => wc.reload());
return;
@@ -15,7 +15,6 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
defaultRuntimeMode: "full-access",
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
@@ -272,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -309,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("surfaces malformed saved environment documents", () =>
it.effect("treats malformed saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -318,15 +298,10 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
const secretError = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
}),
),
);
@@ -82,16 +82,6 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
}
}
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
)<{
@@ -103,7 +93,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
}
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
@@ -114,16 +103,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly removeEnvironment: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
@@ -193,20 +176,18 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
): Effect.Effect<SavedEnvironmentRegistryDocument> {
return fileSystem.readFileString(registryPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed({ version: 1, records: [] }),
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
),
}),
),
);
}
@@ -286,39 +267,21 @@ export const layer = Layer.effect(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!document.records.some((record) => record.environmentId === environmentId)) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.filter((record) => record.environmentId !== environmentId),
});
},
),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
);
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
@@ -336,7 +299,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
@@ -368,7 +331,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (
!document.records.some(
(record) =>
@@ -405,18 +368,6 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records),
removeEnvironment: (environmentId) =>
Ref.update(recordsRef, (records) =>
records.filter((record) => record.environmentId !== environmentId),
).pipe(
Effect.andThen(
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
),
),
getSecret: (environmentId) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
@@ -55,6 +55,7 @@ function makeFakeBrowserWindow() {
openDevTools: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
getZoomFactor: vi.fn(() => 1),
setWindowOpenHandler: vi.fn(),
};
@@ -191,19 +192,19 @@ describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
navigationUrl: "t3code://app/settings/connections",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "https://accounts.microsoft.com/oauth",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "t3code://app/",
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "not a url",
}),
);
@@ -231,7 +232,7 @@ describe("DesktopWindow", () => {
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
+40 -7
View File
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -15,8 +16,8 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
@@ -31,6 +32,7 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopServerExposure.DesktopServerExposure
| DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
@@ -38,7 +40,16 @@ type DesktopWindowRuntimeServices =
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
)<{}> {
override get message() {
return "VITE_DEV_SERVER_URL is required in desktop development.";
}
}
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
@@ -60,6 +71,15 @@ export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowS
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
DesktopObservability.makeComponentLogger("desktop-window");
function resolveDesktopDevServerUrl(
environment: DesktopEnvironment.DesktopEnvironmentShape,
): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
return Option.match(environment.devServerUrl, {
onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
onSome: (url) => Effect.succeed(url.href),
});
}
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
platform: NodeJS.Platform,
@@ -151,16 +171,18 @@ const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
> {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
yield* previewManager.getBrowserSession();
const applicationUrl = getDesktopUrl(environment.isDevelopment);
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
@@ -252,6 +274,16 @@ const make = Effect.gen(function* () {
void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
});
const syncZoomCssVariables = () => {
if (window.isDestroyed()) return;
window.webContents.send(
IpcChannels.ZOOM_FACTOR_CHANGED_CHANNEL,
window.webContents.getZoomFactor(),
);
};
window.webContents.on("zoom-changed", syncZoomCssVariables);
window.webContents.on("did-finish-load", syncZoomCssVariables);
window.webContents.setWindowOpenHandler(({ url }) => {
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url));
@@ -328,7 +360,8 @@ const make = Effect.gen(function* () {
});
const createMain = Effect.gen(function* () {
const window = yield* createWindow();
const backendConfig = yield* serverExposure.backendConfig;
const window = yield* createWindow(backendConfig.httpBaseUrl);
yield* electronWindow.setMain(window);
yield* logWindowInfo("main window created");
return window;
-6
View File
@@ -56,12 +56,6 @@ export default defineConfig({
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
deps: {
// Sandboxed Electron preloads cannot reliably resolve package imports
// from inside the packaged ASAR. Bundle Clerk's preload bridge into the
// preload artifact instead of leaving a runtime require() behind.
alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),
},
},
{
format: "cjs",
+15 -43
View File
@@ -1,6 +1,4 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
@@ -38,17 +36,17 @@ const {
</a>
<div class="nav-right">
<a
class="nav-stars"
href={GITHUB_REPOSITORY_URL}
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
@@ -64,7 +62,7 @@ const {
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
@@ -331,36 +329,23 @@ const {
gap: 8px;
}
.nav-stars {
.nav-gh {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.02);
border-radius: 8px;
color: var(--fg-muted);
font-size: 13px;
letter-spacing: -0.01em;
white-space: nowrap;
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-stars:hover {
.nav-gh:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.04);
}
.nav-stars strong {
color: var(--fg);
font-weight: 600;
}
.nav-stars svg {
color: var(--warn);
flex-shrink: 0;
border-color: var(--border-strong);
}
.main {
@@ -422,17 +407,4 @@ const {
padding-right: 20px;
}
}
@media (max-width: 420px) {
.nav-inner {
gap: 12px;
}
.nav-stars {
height: 34px;
gap: 6px;
padding: 0 12px;
font-size: 12px;
}
}
</style>
-6
View File
@@ -1,6 +0,0 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
users: "100,000",
} as const;
+66 -181
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -56,12 +55,11 @@ const mobileEndorsementRows = [
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="download-label">Download for macOS</span>
</a>
<a class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
Star on GitHub
</a>
</div>
@@ -84,8 +82,8 @@ const mobileEndorsementRows = [
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
<div class="container">
<div class="endorsements-head">
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
<p>Some of them even tweeted about it.</p>
<h2 id="endorsements-title">Developers love T3 Code</h2>
<p>Real reactions from people building with T3 Code today.</p>
</div>
</div>
@@ -284,6 +282,10 @@ const mobileEndorsementRows = [
<div class="section-head open-head">
<div class="eyebrow">Open source</div>
<h2>If you don't like something, fork it.</h2>
<p>
T3 Code is as open as they come. We built this app to be modifiable,
customizable, and forkable. Go nuts - that's the whole point.
</p>
</div>
<div class="open-grid">
@@ -303,44 +305,43 @@ const mobileEndorsementRows = [
</div>
</div>
<div class="tile open-pitch">
<div class="open-pitch-copy">
<ul class="open-pitch-list">
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
</li>
</ul>
<div class="open-stats">
<div class="tile open-stat">
<div class="open-stat-val">MIT</div>
<div class="open-stat-lbl">License · commercial-friendly</div>
</div>
<div class="open-pitch-footer">
<div class="open-pitch-meta">
<span>MIT licensed</span>
<span aria-hidden="true">·</span>
<span>{MARKETING_STATS.githubStars} stars</span>
</div>
<div class="open-pitch-actions">
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork on GitHub
</a>
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
Browse source
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
<div class="tile open-stat">
<div class="open-stat-val">TypeScript</div>
<div class="open-stat-lbl">End-to-end, strictly typed</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">1 monorepo</div>
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">No telemetry</div>
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
</div>
</div>
</div>
<div class="open-ctas">
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
Star on GitHub
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork the repo
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
Read CONTRIBUTING.md
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
</div>
</section>
@@ -514,7 +515,7 @@ const mobileEndorsementRows = [
.hero-title {
font-size: clamp(38px, 5.6vw, 76px);
margin: 48px auto 22px;
margin: 28px auto 22px;
max-width: 20ch;
text-wrap: balance;
}
@@ -530,42 +531,12 @@ const mobileEndorsementRows = [
.hero-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
margin-bottom: 56px;
}
.hero-source-link {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--fg-muted);
font-size: 14px;
font-weight: 500;
letter-spacing: -0.01em;
transition: color 0.18s ease;
}
.hero-source-link:hover {
color: var(--fg);
}
.hero-source-mark {
flex-shrink: 0;
}
.hero-source-arrow {
flex-shrink: 0;
opacity: 0.6;
transition: transform 0.18s ease, opacity 0.18s ease;
}
.hero-source-link:hover .hero-source-arrow {
transform: translate(2px, -2px);
opacity: 1;
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
@@ -685,30 +656,6 @@ const mobileEndorsementRows = [
}
}
@media (max-width: 340px) {
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode {
left: 0;
}
.hero-float-mark.hf-cursor {
right: 0;
}
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
height: 30px;
}
}
.hero-preview {
max-width: 1180px;
margin: 0 auto;
@@ -812,11 +759,6 @@ const mobileEndorsementRows = [
margin-bottom: 18px;
}
.endorsements-count {
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.endorsements-head p {
color: var(--fg-muted);
font-size: 18px;
@@ -1020,11 +962,12 @@ const mobileEndorsementRows = [
text-align: center;
margin: 0 auto 56px;
}
.open-head p { margin: 0 auto; }
.open-grid {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 20px;
gap: 20px; margin-bottom: 32px;
}
.open-term { padding: 0; overflow: hidden; }
@@ -1066,85 +1009,27 @@ const mobileEndorsementRows = [
animation: blink 1s steps(2) infinite;
}
.open-pitch {
padding: 32px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 32px;
background:
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
}
.open-pitch-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 16px;
}
.open-pitch-list li {
display: flex;
align-items: flex-start;
gap: 12px;
font-size: 15px;
line-height: 1.5;
color: var(--fg-muted);
}
.open-pitch-list strong {
color: var(--fg);
font-weight: 600;
}
.open-pitch-mark {
flex: none;
.open-stats {
display: grid;
place-items: center;
width: 22px;
height: 22px;
margin-top: 1px;
border-radius: 7px;
color: var(--accent);
background: var(--accent-dim);
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.open-stat {
padding: 22px;
display: flex; flex-direction: column; gap: 6px;
}
.open-stat-val {
font-size: 22px; font-weight: 500;
letter-spacing: -0.015em;
}
.open-stat-lbl {
font-family: var(--font-mono); font-size: 10.5px;
color: var(--fg-dim); letter-spacing: 0.04em;
}
.open-pitch-footer {
display: flex;
flex-direction: column;
gap: 18px;
}
.open-pitch-meta {
display: flex;
align-items: center;
gap: 8px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 11px;
}
.open-pitch-actions {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.open-source-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-muted);
font-size: 13px;
font-weight: 500;
transition: color 0.18s ease;
}
.open-source-link:hover {
color: var(--fg);
.open-ctas {
display: flex; gap: 10px;
justify-content: center; flex-wrap: wrap;
}
/* ── Final CTA ────────────────────────────────────────── */
-5
View File
@@ -131,11 +131,6 @@ const config: ExpoConfig = {
{
ios: {
deploymentTarget: "18.0",
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
extraPods: [
{ name: "GoogleUtilities", modular_headers: true },
{ name: "RecaptchaInterop", modular_headers: true },
],
},
},
],
+1 -2
View File
@@ -1,8 +1,7 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote",
"promptToConfigurePushNotifications": false
"appVersionSource": "remote"
},
"build": {
"development": {
@@ -70,12 +70,7 @@ static void T3MarkdownTextApplyAttachments(
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -85,6 +80,104 @@ static void T3MarkdownTextApplyAttachments(
}
}
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextChipRange> &chipRanges)
{
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
for (const auto &chipRange : chipRanges) {
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
continue;
}
const NSRange range = NSMakeRange(
chipRange.location,
MIN(chipRange.length, attributedString.length - chipRange.location));
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
if (color == nil) {
continue;
}
[backgrounds addObject:@{
@"range": [NSValue valueWithRange:range],
@"color": color,
@"strokeColor": [foregroundColor
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
}];
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
return backgrounds;
}
@interface T3MarkdownTextBackingView : UITextView
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
@end
@implementation T3MarkdownTextBackingView
- (void)drawRect:(CGRect)rect
{
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
CGContextRef context = UIGraphicsGetCurrentContext();
if (context != nil) {
CGContextSaveGState(context);
CGContextResetClip(context);
CGContextClipToRect(context, self.bounds);
}
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
const NSRange characterRange = [background[@"range"] rangeValue];
UIColor *color = background[@"color"];
UIColor *strokeColor = background[@"strokeColor"];
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
continue;
}
const NSRange glyphRange =
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
[color setFill];
[self.layoutManager
enumerateEnclosingRectsForGlyphRange:glyphRange
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
inTextContainer:self.textContainer
usingBlock:^(CGRect glyphRect, BOOL *stop) {
const CGFloat chipHeight = 22;
CGRect chipRect = CGRectMake(
glyphRect.origin.x - 4,
CGRectGetMidY(glyphRect) - chipHeight / 2,
glyphRect.size.width + 8,
chipHeight);
chipRect.origin.x += self.textContainerInset.left;
chipRect.origin.y += self.textContainerInset.top;
const CGFloat minimumX = self.textContainerInset.left + 0.5;
const CGFloat maximumX =
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
if (chipRect.origin.x < minimumX) {
chipRect.size.width -= minimumX - chipRect.origin.x;
chipRect.origin.x = minimumX;
}
if (CGRectGetMaxX(chipRect) > maximumX) {
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
}
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
[path fill];
[strokeColor setStroke];
path.lineWidth = 1;
[path stroke];
}];
}
if (context != nil) {
CGContextRestoreGState(context);
}
[super drawRect:rect];
}
@end
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@@ -192,7 +285,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
@implementation T3MarkdownText {
UIView * _view;
UITextView * _textView;
T3MarkdownTextBackingView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
@@ -215,7 +308,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
self.contentView = _view;
self.clipsToBounds = true;
_textView = [[UITextView alloc] init];
_textView = [[T3MarkdownTextBackingView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
@@ -312,6 +405,9 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
convertedAttrString,
_state->getData().chipRanges);
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
@@ -28,20 +28,18 @@ struct T3MarkdownTextAttachmentRange {
std::string imageUri;
};
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
return 14;
}
inline Float T3MarkdownTextAttachmentBaselineOffset(
const T3MarkdownTextAttachmentRange &) {
return -2;
}
struct T3MarkdownTextChipRange {
size_t location;
size_t length;
bool isSkill;
};
class T3MarkdownTextStateReal final {
public:
AttributedString attributedString;
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
std::vector<T3MarkdownTextChipRange> chipRanges;
};
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
@@ -74,5 +72,6 @@ private:
mutable AttributedString _attributedString;
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
};
} // namespace facebook::React
@@ -9,8 +9,9 @@
namespace facebook::react {
static constexpr Float ParagraphStyleEncodingOffset = 1000;
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
static void applyParagraphStyles(
NSMutableAttributedString *attributedString,
@@ -57,12 +58,7 @@ static void applyAttachments(
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -95,6 +91,7 @@ Size T3MarkdownTextShadowNode::measureContent(
auto baseAttributedString = AttributedString{};
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
size_t utf16Offset = 0;
const auto &children = getChildren();
for (size_t i = 0; i < children.size(); i++) {
@@ -187,19 +184,25 @@ Size T3MarkdownTextShadowNode::measureContent(
props.shadowRadius - ParagraphStyleEncodingOffset,
});
}
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
chipRanges.push_back(T3MarkdownTextChipRange{
utf16Offset,
fragmentLength,
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
});
}
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset + 1,
1,
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
});
} else if (
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset,
utf16Offset + 1,
1,
props.nativeId.substr(
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
});
}
utf16Offset += fragmentLength;
@@ -210,6 +213,7 @@ Size T3MarkdownTextShadowNode::measureContent(
_attributedString = baseAttributedString;
_paragraphStyleRanges = paragraphStyleRanges;
_attachmentRanges = attachmentRanges;
_chipRanges = chipRanges;
NSMutableAttributedString *convertedAttributedString =
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
@@ -259,6 +263,7 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
_attributedString,
_paragraphStyleRanges,
_attachmentRanges,
_chipRanges,
});
}
}
@@ -40,13 +40,11 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
@@ -314,7 +312,6 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const rows = collectTableRows(props.node);
return (
@@ -354,7 +351,6 @@ function NativeTable(props: {
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
))}
@@ -368,17 +364,10 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const href = props.node.href;
if (!href) {
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
}
return (
@@ -437,7 +426,6 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<View style={{ gap: 8 }}>
@@ -447,15 +435,9 @@ function NativeMixedParagraph(props: {
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
),
)}
</View>
@@ -466,7 +448,6 @@ function NativeList(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth: number;
}) {
const ordered = props.node.ordered ?? false;
@@ -527,7 +508,6 @@ function NativeList(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={props.depth + 1}
compact
/>
@@ -544,7 +524,6 @@ export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth?: number;
readonly compact?: boolean;
}) {
@@ -559,7 +538,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
))}
@@ -575,21 +553,9 @@ export function NativeMarkdownBlock(props: {
/>
);
case "table":
return (
<NativeTable
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <NativeTable node={props.node} textStyle={props.textStyle} />;
case "image":
return (
<NativeMarkdownImage
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
case "horizontal_rule":
return (
<View
@@ -617,7 +583,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -630,23 +595,14 @@ export function NativeMarkdownBlock(props: {
node={props.node}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
);
case "paragraph":
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
) : (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode node={props.node} textStyle={props.textStyle} />
);
case "html_block":
case "math_block":
@@ -662,11 +618,7 @@ export function NativeMarkdownBlock(props: {
: "transparent",
}}
>
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
<SelectableNode node={props.node} textStyle={props.textStyle} />
</View>
);
case "table_head":
@@ -683,7 +635,6 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -691,12 +642,6 @@ export function NativeMarkdownBlock(props: {
</View>
);
default:
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
}
}
@@ -1,15 +1,61 @@
import { useEffect, useMemo, useState } from "react";
import { Asset } from "expo-asset";
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource } from "./markdownFileIcons";
import type { MarkdownFileIcon } from "./markdownLinks";
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
const EXTERNAL_LINK_PREFIX = "◉ ";
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
const CHIP_SUFFIX = "\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
const iconSignature = JSON.stringify(
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
);
const icons = useMemo(
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
[iconSignature],
);
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
useEffect(() => {
let cancelled = false;
void Promise.all(
icons.map(async (icon) => {
const source = markdownFileIconSource(icon);
const fallbackUri = Image.resolveAssetSource(source).uri;
if (typeof source !== "number" && typeof source !== "string") {
return [icon, fallbackUri] as const;
}
try {
const asset = Asset.fromModule(source);
await asset.downloadAsync();
return [icon, asset.localUri ?? fallbackUri] as const;
} catch {
return [icon, fallbackUri] as const;
}
}),
).then((entries) => {
if (!cancelled) {
setUris(new Map(entries));
}
});
return () => {
cancelled = true;
};
}, [icons]);
return uris;
}
function runKeySignature(run: NativeMarkdownTextRun): string {
return [
run.text,
@@ -35,16 +81,13 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const isChip = isFile || isSkill;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
const textDecorationLine = run.strikethrough
? "line-through"
: run.href && !isFile
? "underline"
: "none";
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
return {
color: isFile
@@ -63,23 +106,20 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? textStyle.mutedColor
: run.role === "list-marker"
? textStyle.mutedColor
: isCodeBlock
: run.code || isFile
? textStyle.codeColor
: run.code
? textStyle.inlineCodeColor
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily:
isFile || isSkill
? textStyle.boldFontFamily
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily: isChip
? "DMSans_500Medium"
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
fontSize:
run.role === "spacer"
? (run.spacing ?? 10)
@@ -89,7 +129,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? headingFontSize
: run.role === "code-language"
? 11
: run.code || isCodeBlock
: run.code || isChip || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
lineHeight:
@@ -103,9 +143,17 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? 18
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
textDecorationLine,
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
backgroundColor: isCodeBlock
? textStyle.codeBlockBackgroundColor
: isSkill
? textStyle.skillBackgroundColor
: run.code
? textStyle.codeBackgroundColor
: isFile
? textStyle.fileBackgroundColor
: undefined,
...(hasParagraphStyle
? {
shadowColor: "transparent",
@@ -122,9 +170,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
export function NativeMarkdownSelectableText(props: {
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const colorScheme = useColorScheme();
const fileIconUris = useFileIconUris(props.runs);
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
const keyedRuns = props.runs.map((run) => {
@@ -134,9 +182,9 @@ export function NativeMarkdownSelectableText(props: {
let text = run.text;
if (run.fileIcon) {
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
} else if (run.skillName && run.skillLabel) {
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
prefixedExternalLinks.add(run.href);
text = `${EXTERNAL_LINK_PREFIX}${text}`;
@@ -152,11 +200,12 @@ export function NativeMarkdownSelectableText(props: {
props.textStyle.strongColor,
props.textStyle.mutedColor,
props.textStyle.linkColor,
props.textStyle.inlineCodeColor,
props.textStyle.codeColor,
props.textStyle.codeBackgroundColor,
props.textStyle.codeBlockBackgroundColor,
props.textStyle.fileBackgroundColor,
props.textStyle.fileTextColor,
props.textStyle.skillBackgroundColor,
props.textStyle.skillTextColor,
props.textStyle.quoteMarkerColor,
props.textStyle.dividerColor,
@@ -168,8 +217,7 @@ export function NativeMarkdownSelectableText(props: {
uiTextView
selectable
style={{
flexShrink: 1,
minWidth: 0,
width: "100%",
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
@@ -183,20 +231,19 @@ export function NativeMarkdownSelectableText(props: {
key={key}
nativeID={
run.fileIcon
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
? `t3-chip-file:${
fileIconUris.get(run.fileIcon) ??
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
}`
: run.skillName
? "t3-skill:sf:cube"
? "t3-chip-skill:sf:cube"
: undefined
}
style={runStyle(run, props.textStyle)}
onPress={
href
? () => {
if (props.onLinkPress) {
props.onLinkPress(href);
} else {
void Linking.openURL(href);
}
void Linking.openURL(href);
}
: undefined
}
@@ -6,7 +6,6 @@ import {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownWithPreservedSoftBreaks,
} from "./nativeMarkdownText";
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
@@ -34,20 +33,15 @@ export function SelectableMarkdownText({
skills = EMPTY_SKILLS,
textStyle,
highlightCode,
preserveSoftBreaks = false,
onLinkPress,
marginTop = 0,
marginBottom = 0,
}: SelectableMarkdownTextProps) {
const chunks = useMemo(() => {
const parsedDocument = parseMarkdownWithOptions(markdown, {
const document = parseMarkdownWithOptions(markdown, {
gfm: true,
html: true,
math: false,
});
const document = preserveSoftBreaks
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
: parsedDocument;
return nativeMarkdownDocumentChunks(document).map((chunk) =>
chunk.kind === "selectable"
? {
@@ -56,14 +50,10 @@ export function SelectableMarkdownText({
}
: chunk,
);
}, [markdown, preserveSoftBreaks, skills]);
}, [markdown, skills]);
return (
// A percentage width here creates a cyclic intrinsic measurement inside
// shrink-to-fit containers such as user-message bubbles. Yoga then gives
// the native text node an unbounded second pass and the parent only clips
// the resulting single-line width instead of reflowing it.
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
<View style={{ width: "100%", marginTop, marginBottom }}>
{chunks.map((chunk, index) => {
const content =
chunk.kind === "rich" ? (
@@ -71,14 +61,9 @@ export function SelectableMarkdownText({
node={chunk.node}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
/>
) : (
<NativeMarkdownSelectableText
runs={chunk.runs}
textStyle={textStyle}
onLinkPress={onLinkPress}
/>
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
);
return (
@@ -3,11 +3,12 @@ export interface NativeMarkdownTextStyle {
readonly strongColor: string;
readonly mutedColor: string;
readonly linkColor: string;
readonly inlineCodeColor: string;
readonly codeColor: string;
readonly codeBackgroundColor: string;
readonly codeBlockBackgroundColor: string;
readonly fileBackgroundColor: string;
readonly fileTextColor: string;
readonly skillBackgroundColor: string;
readonly skillTextColor: string;
readonly quoteMarkerColor: string;
readonly dividerColor: string;
@@ -40,8 +41,6 @@ export interface SelectableMarkdownTextProps {
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly preserveSoftBreaks?: boolean;
readonly onLinkPress?: (href: string) => void;
readonly marginTop?: number;
readonly marginBottom?: number;
}
@@ -27,12 +27,8 @@ export type MarkdownLinkPresentation =
}
| {
readonly kind: "file";
readonly href: string;
readonly icon: MarkdownFileIcon;
readonly label: string;
readonly path: string;
readonly line?: number;
readonly column?: number;
}
| {
readonly kind: "link";
@@ -251,7 +247,7 @@ function normalizeDestination(value: string): string {
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
}
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
function fileUrlPath(href: string): string | null {
try {
const parsed = new URL(href);
if (parsed.protocol.toLowerCase() !== "file:") {
@@ -260,44 +256,15 @@ function fileUrlTarget(href: string): { readonly path: string; readonly hash: st
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
? parsed.pathname.slice(1)
: parsed.pathname;
return { path, hash: parsed.hash };
const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
return `${safeDecode(path)}${
lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
}`;
} catch {
return null;
}
}
function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
const hashIndex = value.indexOf("#");
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
const queryIndex = pathWithSearch.indexOf("?");
return {
path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
hash,
};
}
function splitFilePosition(
path: string,
hash: string,
): { readonly path: string; readonly line?: number; readonly column?: number } {
const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
const match = suffixMatch ?? hashMatch;
if (!match?.[1]) {
return { path };
}
const line = Number.parseInt(match[1], 10);
const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
return {
path: pathWithoutPosition,
...(line > 0 ? { line } : {}),
...(column !== undefined && column > 0 ? { column } : {}),
};
}
function looksLikePosixFilesystemPath(path: string): boolean {
if (!path.startsWith("/")) {
return false;
@@ -364,31 +331,14 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
// Relative paths and non-URL link destinations are handled below.
}
const source = normalized.toLowerCase().startsWith("file:")
? fileUrlTarget(normalized)
: stripSearchAndHash(normalized);
const decodedSource = source
? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
: null;
const fileTarget = decodedSource
? splitFilePosition(decodedSource.path, decodedSource.hash)
: null;
const targetWithPosition = fileTarget
? `${fileTarget.path}${
fileTarget.line
? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
: ""
}`
: null;
if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
const fileTarget = normalized.toLowerCase().startsWith("file:")
? fileUrlPath(normalized)
: safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
if (fileTarget && looksLikeFilePath(fileTarget)) {
return {
kind: "file",
href: normalized,
icon: resolveMarkdownFileIcon(fileTarget.path),
label: fileLabel(targetWithPosition),
path: fileTarget.path,
...(fileTarget.line ? { line: fileTarget.line } : {}),
...(fileTarget.column ? { column: fileTarget.column } : {}),
icon: resolveMarkdownFileIcon(fileTarget),
label: fileLabel(fileTarget),
};
}
@@ -293,7 +293,6 @@ function appendNode(
if (presentation.kind === "file") {
return appendRun(runs, presentation.label, {
...context,
href: presentation.href,
fileIcon: presentation.icon,
});
}
@@ -320,15 +319,6 @@ export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<Native
return appendChildren([], node, EMPTY_CONTEXT);
}
export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
return {
...node,
...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
...(children ? { children } : {}),
};
}
function appendBlockTerminator(
runs: NativeMarkdownTextRun[],
context: RunContext,
@@ -57,10 +57,6 @@ public class T3ReviewDiffModule: Module {
view.setContentWidth(CGFloat(contentWidth))
}
Prop("initialRowIndex") { (view: T3ReviewDiffView, initialRowIndex: Double) in
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
}
}
@@ -205,7 +205,7 @@ private struct ReviewDiffNativeStyle {
ReviewDiffNativeStyle(
rowHeight: metric(payload?.rowHeight, fallback: 24),
contentWidth: metric(payload?.contentWidth, fallback: 2800),
changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
changeBarWidth: metric(payload?.changeBarWidth, fallback: 4),
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
codePadding: metric(payload?.codePadding, fallback: 8),
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
@@ -243,13 +243,6 @@ private struct ReviewDiffNativeStyle {
return CGFloat(value)
}
private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
guard let value, value.isFinite, value >= 0 else {
return fallback
}
return CGFloat(value)
}
private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
switch value?.lowercased() {
case "ultralight", "ultra-light":
@@ -323,8 +316,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
private var initialRowIndex: Int?
private var hasAppliedInitialRowIndex = false
let onDebug = EventDispatcher()
let onToggleFile = EventDispatcher()
@@ -403,7 +394,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
do {
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
contentView.rows = rows
hasAppliedInitialRowIndex = false
emitDebug("rows-decoded", [
"rows": rows.count,
"firstKind": rows.first?.kind ?? "none",
@@ -412,7 +402,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
} catch {
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
@@ -572,7 +561,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
applyInitialRowIndexIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -657,19 +645,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyStyle()
}
func setInitialRowIndex(_ initialRowIndex: Double) {
let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
? Int(initialRowIndex.rounded(.down))
: nil
guard nextIndex != self.initialRowIndex else {
return
}
self.initialRowIndex = nextIndex
hasAppliedInitialRowIndex = false
applyInitialRowIndexIfNeeded()
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -687,22 +662,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
}
private func applyInitialRowIndexIfNeeded() {
guard !hasAppliedInitialRowIndex,
let initialRowIndex,
bounds.height > 0,
let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
return
}
let targetScreenY = max(0, (bounds.height - rowFrame.height) * 0.3)
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
let targetOffset = min(max(rowFrame.minY - targetScreenY, 0), maxOffset)
hasAppliedInitialRowIndex = true
scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
updateViewportFrame()
}
}
private enum ReviewDiffHorizontalPanKind {
@@ -861,19 +820,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return style.rowHeight
}
func frameForRow(at index: Int) -> CGRect? {
guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
return nil
}
return CGRect(
x: 0,
y: rowOffsets[index],
width: max(viewportWidth, 1),
height: height(for: rows[index])
)
}
private func rebuildRowLayout() {
var nextOffsets: [CGFloat] = []
var nextFileHeaderRowIndices: [Int] = []
+7 -9
View File
@@ -40,7 +40,7 @@
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@clerk/expo": "catalog:",
"@clerk/expo": "^3.4.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
@@ -49,10 +49,10 @@
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.2.0",
"@shikijs/langs": "4.2.0",
"@shikijs/themes": "4.2.0",
"@shikijs/core": "3.23.0",
"@shikijs/engine-javascript": "3.23.0",
"@shikijs/langs": "3.23.0",
"@shikijs/themes": "3.23.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/mobile-markdown-text": "file:./modules/t3-markdown-text",
@@ -77,7 +77,6 @@
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14",
"expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7",
@@ -99,11 +98,10 @@
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.12",
"react-native-shiki-engine": "^0.3.9",
"react-native-svg": "15.15.4",
"react-native-webview": "^13.16.1",
"react-native-worklets": "0.8.3",
"shiki": "4.2.0",
"shiki": "3.23.0",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2"
},
+10 -8
View File
@@ -16,8 +16,10 @@ import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import { useWorkspaceState } from "../state/workspace";
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
@@ -30,24 +32,22 @@ import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
const expandedSettingsRouteIsActive =
pathname === "/settings/archive" || pathname === "/settings/auth";
const clerkRouteIsActive = pathname === "/settings/auth";
return (
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
}
function AppNavigatorContent() {
const { state } = useWorkspaceState();
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
@@ -81,7 +81,7 @@ function AppNavigatorContent() {
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
};
if (state.isLoadingConnections) {
if (isLoadingSavedConnection) {
return <LoadingScreen message="Loading remote workspace…" />;
}
@@ -129,6 +129,8 @@ export default function RootLayout() {
DMSans_500Medium,
DMSans_700Bold,
});
useRemoteEnvironmentBootstrap();
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
+5 -6
View File
@@ -1,6 +1,5 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -112,12 +111,12 @@ export default function ConnectionsNewRouteScreen() {
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} else {
} catch {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
+89 -96
View File
@@ -1,119 +1,112 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View } from "react-native";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { HomeHeader } from "../features/home/HomeHeader";
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
import { useThreadListActions } from "../features/home/useThreadListActions";
interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
import { useThemeColor } from "../lib/useThemeColor";
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const [listOptions, setListOptions] = useState<HomeListOptions>({
selectedEnvironmentId: null,
projectSortOrder:
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
});
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
),
[savedConnectionsById],
);
const selectedEnvironmentId = environments.some(
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
)
? listOptions.selectedEnvironmentId
: null;
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
}, []);
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
setListOptions((current) => ({ ...current, projectSortOrder }));
}, []);
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
setListOptions((current) => ({ ...current, threadSortOrder }));
}, []);
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
setListOptions((current) => ({ ...current, projectGroupingMode }));
}, []);
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
return (
<>
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => router.push("/settings")}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => router.push("/new")}
onThreadSortOrderChange={setThreadSortOrder}
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
allowToolbarIntegration: true,
},
}}
/>
{/* Header left: plain text, no Liquid Glass button chrome */}
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: mutedColor,
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="gearshape"
onPress={() => router.push("/settings")}
separateBackground
/>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
icon="square.and.pencil"
onPress={() => router.push("/new")}
separateBackground
/>
</Stack.Toolbar>
<HomeScreen
projects={projects}
threads={threads}
catalogState={catalogState}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
@@ -1,5 +1,5 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
+14 -16
View File
@@ -8,17 +8,16 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects, useThreadShells } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
function deriveProjectEmptyState(catalogState: WorkspaceState): {
function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
readonly title: string;
readonly detail: string;
readonly loading: boolean;
} {
if (catalogState.isLoadingConnections) {
if (catalogState.isLoadingSavedConnections) {
return {
title: "Loading environments",
detail: "Checking saved environments on this device.",
@@ -26,7 +25,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
};
}
if (!catalogState.hasConnections) {
if (!catalogState.hasSavedConnections) {
return {
title: "No environments connected",
detail: "Add an environment before creating a task.",
@@ -34,12 +33,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
};
}
if (
(catalogState.connectionState === "available" ||
catalogState.connectionState === "offline" ||
catalogState.connectionState === "error") &&
!catalogState.hasLoadedShellSnapshot
) {
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
return {
title: "Environment unavailable",
detail:
@@ -69,9 +63,8 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
}
export default function NewTaskRoute() {
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
@@ -190,10 +183,15 @@ export default function NewTaskRoute() {
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={item.environmentId}
size={20}
projectTitle={item.title}
httpBaseUrl={
savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null
}
workspaceRoot={item.workspaceRoot}
bearerToken={
savedConnectionsById[item.environmentId]?.bearerToken ?? null
}
/>
</View>
<View className="flex-1">
+2 -7
View File
@@ -14,7 +14,7 @@ export default function SettingsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
const handleExpandedRouteTransitionEnd = useCallback(
const handleClerkRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
@@ -47,14 +47,9 @@ export default function SettingsLayout() {
name="waitlist"
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
<Stack.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
listeners={{ transitionEnd: handleClerkRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
-3
View File
@@ -1,3 +0,0 @@
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
export default ArchivedThreadsRouteScreen;
+110 -287
View File
@@ -1,38 +1,32 @@
import { useAuth } from "@clerk/expo";
import { Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
import {
type RelayEnvironmentView,
useConnectionController,
} from "../../features/connection/useConnectionController";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation";
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import {
useManagedRelayEnvironments,
useManagedRelayEnvironmentStatus,
} from "../../features/cloud/managedRelayState";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../../features/connection/environmentSections";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { mobileRuntime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import {
connectSavedEnvironment,
useRemoteConnections,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
export default function SettingsEnvironmentsRouteScreen() {
const {
@@ -43,11 +37,7 @@ export default function SettingsEnvironmentsRouteScreen() {
} = useRemoteConnections();
const router = useRouter();
const insets = useSafeAreaInsets();
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
const hasLocalEnvironments = localEnvironments.length > 0;
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const accentColor = useThemeColor("--color-icon-muted");
@@ -79,9 +69,9 @@ export default function SettingsEnvironmentsRouteScreen() {
paddingTop: 16,
}}
>
{hasLocalEnvironments ? (
{hasEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{localEnvironments.map((environment, index) => (
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
@@ -118,43 +108,54 @@ export default function SettingsEnvironmentsRouteScreen() {
</View>
)}
{hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
) : null}
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null}
</ScrollView>
</View>
);
}
function ConfiguredCloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
function ConfiguredCloudEnvironmentRows() {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { savedConnectionsById } = useRemoteEnvironmentState();
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
null,
);
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const availableCloudEnvironments = useMemo(
() =>
(cloudEnvironmentsState.data ?? []).filter(
(environment) => savedConnectionsById[environment.environmentId] === undefined,
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
async (environment: RelayClientEnvironmentRecord) => {
setConnectingCloudEnvironmentId(environment.environmentId);
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
throw new Error("Sign in to T3 Cloud before connecting.");
}
await mobileRuntime.runPromise(
connectCloudEnvironment({
clerkToken: token,
environment,
}).pipe(Effect.flatMap(connectSavedEnvironment)),
);
} catch (error) {
Alert.alert(
"Connect failed",
error instanceof Error ? error.message : "Could not connect to this environment.",
);
} finally {
setConnectingCloudEnvironmentId(null);
}
},
[getToken],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
@@ -163,13 +164,11 @@ function ConfiguredCloudEnvironmentRows(props: {
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
{cloudEnvironmentsState.isPending ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
@@ -177,48 +176,33 @@ function ConfiguredCloudEnvironmentRows(props: {
</Pressable>
</View>
{hasCloudRows ? (
{availableCloudEnvironments.length > 0 ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
) : cloudEnvironmentsState.data === null ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? (
) : cloudEnvironmentsState.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{controller.relayDiscovery.error}
{cloudEnvironmentsState.error}
</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
@@ -231,124 +215,23 @@ function ConfiguredCloudEnvironmentRows(props: {
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly environment: RelayClientEnvironmentRecord;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly isConnecting: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const mutedColor = useThemeColor("--color-icon-muted");
const statusState = useManagedRelayEnvironmentStatus(props.environment);
const status = statusState.data;
const disabled = props.isConnecting;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
status === null
? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable"))
: status.status === "online"
? "Online"
: (status.error ?? "Offline");
return (
<View
collapsable={false}
@@ -357,96 +240,36 @@ function CloudEnvironmentRowShell(props: {
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-[16px] font-t3-bold leading-[21px] text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-[12px] leading-[16px]", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-[12px] leading-[16px]", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-[12px] leading-[16px] underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId);
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
<View className="h-9 w-9 items-center justify-center rounded-[14px] bg-subtle">
<SymbolView
name="cloud"
size={17}
tintColor={mutedColor}
type="monochrome"
weight="semibold"
/>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
{props.environment.label}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.endpoint.httpBaseUrl}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusText}
</Text>
</View>
<Pressable
accessibilityRole="button"
disabled={disabled}
onPress={props.onConnect}
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50"
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
{props.isConnecting ? "Connecting" : "Connect"}
</Text>
</Pressable>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId);
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-[12px] font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
+83 -152
View File
@@ -8,13 +8,6 @@ import type { ComponentProps, ReactNode } from "react";
import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
isAtomCommandInterrupted,
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
@@ -25,10 +18,10 @@ import {
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import { runtime } from "../../lib/runtime";
import { mobileRuntime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -39,7 +32,7 @@ export default function SettingsRouteScreen() {
function LocalSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { savedConnectionsById } = useSavedRemoteConnections();
const { savedConnectionsById } = useRemoteEnvironmentState();
const environmentCount = Object.keys(savedConnectionsById).length;
return (
@@ -65,8 +58,6 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -79,7 +70,7 @@ function ConfiguredSettingsRouteScreen() {
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useSavedRemoteConnections();
const { savedConnectionsById } = useRemoteEnvironmentState();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -96,13 +87,8 @@ function ConfiguredSettingsRouteScreen() {
setNotificationStatus("unsupported");
return;
}
const result = await settlePromise(() => Notifications.getPermissionsAsync());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "notification permission refresh" });
setNotificationStatus("disabled");
return;
}
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
const permission = await Notifications.getPermissionsAsync();
setNotificationStatus(permission.granted ? "enabled" : "disabled");
}, []);
useEffect(() => {
@@ -118,66 +104,60 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out");
return;
}
void (async () => {
const result = await settlePromise(() => loadPreferences());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "live activity preference load" });
void loadPreferences().then(
(preferences) => {
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled");
},
() => {
setLiveActivityStatus("enabled");
return;
}
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
},
);
}, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => {
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(
try {
const result = await mobileRuntime.runPromise(
requestAgentNotificationPermission.pipe(
Effect.tap((permission) =>
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
),
),
),
);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
);
if (result.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
return;
}
if (result.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert(
"Notifications unavailable",
error instanceof Error ? error.message : "Could not request notification permission.",
"Live Activity notifications are only available on iOS.",
);
return;
}
setNotificationStatus("disabled");
if (result.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
return;
}
if (result.value.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
return;
}
if (result.value.type === "unsupported") {
setNotificationStatus("unsupported");
} catch (error) {
Alert.alert(
"Notifications unavailable",
"Live Activity notifications are only available on iOS.",
error instanceof Error ? error.message : "Could not request notification permission.",
);
return;
}
setNotificationStatus("disabled");
if (result.value.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
}, []);
const promptSignIn = useCallback(() => {
@@ -198,51 +178,36 @@ function ConfiguredSettingsRouteScreen() {
}
setLiveActivityStatus("linking");
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
await mobileRuntime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
} catch (error) {
setLiveActivityStatus("disabled");
const error = squashAtomCommandFailure(tokenResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
return;
}
if (!tokenResult.value) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: tokenResult.value,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
setLiveActivityStatus("disabled");
if (!isAtomCommandInterrupted(updateResult)) {
const error = squashAtomCommandFailure(updateResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
}
return;
}
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback(
@@ -269,36 +234,19 @@ function ConfiguredSettingsRouteScreen() {
if (!enabled) {
setLiveActivityStatus("disabled");
void (async () => {
let token: string | null = null;
if (isSignedIn) {
const tokenResult = await settlePromise(() =>
getToken(resolveRelayClerkTokenOptions()),
);
if (tokenResult._tag === "Failure") {
reportAtomCommandResult(tokenResult, {
label: "live activity disable token lookup",
});
return;
}
token = tokenResult.value;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
try {
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null;
await mobileRuntime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: token,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
);
refreshManagedRelayEnvironments();
} catch {
// The switch is optimistic; a future refresh reconciles relay state.
}
refreshManagedRelayEnvironments();
})();
return;
}
@@ -376,8 +324,6 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -420,20 +366,12 @@ function AppSettingsSection() {
);
}
function ArchivedThreadsSettingsSection() {
return (
<SettingsSection title="Threads">
<SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
</SettingsSection>
);
}
function SettingsRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly value?: string;
readonly href?: "/settings/archive" | "/settings/environments";
readonly href?: "/settings/environments";
readonly onPress?: () => void;
}) {
const icon = useThemeColor("--color-icon");
@@ -444,20 +382,15 @@ function SettingsRow(props: {
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="shrink-0 text-[17px] text-foreground" numberOfLines={1}>
{props.label}
</Text>
<View className="min-w-0 flex-1 items-end">
{props.value ? (
<Text
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{props.value}
</Text>
) : null}
</View>
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
{props.value ? (
<Text
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
numberOfLines={1}
>
{props.value}
</Text>
) : null}
<SymbolView
name="chevron.right"
size={16}
@@ -471,9 +404,7 @@ function SettingsRow(props: {
if (props.href) {
return (
<Link href={props.href} asChild>
<Pressable accessibilityLabel={props.label} accessibilityRole="button">
{content}
</Pressable>
<Pressable>{content}</Pressable>
</Link>
);
}
@@ -55,32 +55,6 @@ export default function ThreadLayout() {
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/index"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/[...path]"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
@@ -1,5 +0,0 @@
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFileRoute() {
return <ThreadFileScreen />;
}
@@ -1,5 +0,0 @@
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFilesIndexRoute() {
return <ThreadFilesTreeScreen />;
}
@@ -1,93 +0,0 @@
import { useEffect, useState } from "react";
import { View } from "react-native";
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withRepeat,
withTiming,
} from "react-native-reanimated";
const INDICATOR_WIDTH_FRACTION = 0.3;
const MIN_INDICATOR_WIDTH = 48;
function LoadingStripFrame(props: {
readonly children: React.ReactNode;
readonly onLayout?: (width: number) => void;
}) {
return (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden"
onLayout={
props.onLayout
? (event) => {
props.onLayout?.(event.nativeEvent.layout.width);
}
: undefined
}
>
{props.children}
</View>
);
}
function IndeterminateLoadingStrip() {
const [containerWidth, setContainerWidth] = useState(0);
const travelProgress = useSharedValue(0);
const indicatorWidth = Math.max(MIN_INDICATOR_WIDTH, containerWidth * INDICATOR_WIDTH_FRACTION);
useEffect(() => {
travelProgress.value = 0;
travelProgress.value = withRepeat(
withTiming(1, {
duration: 1100,
easing: Easing.inOut(Easing.quad),
}),
-1,
false,
);
return () => {
cancelAnimation(travelProgress);
};
}, [travelProgress]);
const indicatorStyle = useAnimatedStyle(
() => ({
transform: [
{
translateX: (containerWidth + indicatorWidth) * travelProgress.value - indicatorWidth,
},
],
width: indicatorWidth,
}),
[containerWidth, indicatorWidth],
);
return (
<LoadingStripFrame onLayout={setContainerWidth}>
<Animated.View className="h-full rounded-full bg-primary" style={indicatorStyle} />
</LoadingStripFrame>
);
}
export function LoadingStrip(props: { readonly progress?: number }) {
if (props.progress === undefined) {
return <IndeterminateLoadingStrip />;
}
const clampedProgress = Math.min(1, Math.max(0, props.progress));
return (
<LoadingStripFrame>
<View
className="h-full rounded-r-full bg-primary"
style={{ width: `${clampedProgress * 100}%` }}
/>
</LoadingStripFrame>
);
}
+21 -42
View File
@@ -1,86 +1,65 @@
import { SymbolView } from "expo-symbols";
import { useState } from "react";
import { Image, View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>();
/* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: {
readonly environmentId: EnvironmentId;
readonly size?: number;
readonly projectTitle: string;
readonly httpBaseUrl?: string | null;
readonly workspaceRoot?: string | null;
readonly bearerToken?: string | null;
}) {
const size = props.size ?? 42;
const faviconUrl = useAssetUrl(
props.environmentId,
props.workspaceRoot === null || props.workspaceRoot === undefined
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
return (
<ProjectFaviconImage
key={faviconUrl}
faviconUrl={faviconUrl}
projectTitle={props.projectTitle}
size={size}
/>
);
}
function ProjectFaviconImage(props: {
readonly faviconUrl: string | null;
readonly projectTitle: string;
readonly size: number;
}) {
const iconMuted = useThemeColor("--color-icon-subtle");
const faviconUrl =
props.httpBaseUrl && props.workspaceRoot
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
: null;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
);
const showImage = props.faviconUrl !== null && status === "loaded";
const showImage = faviconUrl && status === "loaded";
return (
<View
style={{
width: props.size,
height: props.size,
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
}}
>
{/* Folder icon fallback (matches web's FolderIcon) */}
{!showImage ? (
<SymbolView
name="folder.fill"
size={props.size * 0.78}
tintColor={iconMuted}
type="monochrome"
/>
<SymbolView name="folder.fill" size={size * 0.78} tintColor={iconMuted} type="monochrome" />
) : null}
{/* Favicon image (hidden until loaded) */}
{props.faviconUrl ? (
{faviconUrl ? (
<Image
source={{
uri: props.faviconUrl,
uri: faviconUrl,
...(props.bearerToken
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
: {}),
}}
accessibilityLabel={`${props.projectTitle} favicon`}
style={{
width: props.size,
height: props.size,
borderRadius: props.size * 0.16,
width: size,
height: size,
borderRadius: size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
resizeMode="contain"
onLoad={() => {
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
setStatus("loaded");
}}
onError={() => setStatus("error")}
-122
View File
@@ -1,122 +0,0 @@
import {
ConnectionCatalogDocument,
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
} from "@t3tools/client-runtime/platform";
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
});
interface CatalogStore {
readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
readonly update: (
transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
) => Effect.Effect<void, ConnectionTransientError>;
}
export interface SecureCatalogStorage {
readonly getItem: (key: string) => Effect.Effect<string | null, ConnectionTransientError>;
readonly setItem: (key: string, value: string) => Effect.Effect<void, ConnectionTransientError>;
readonly deleteItem: (key: string) => Effect.Effect<void, ConnectionTransientError>;
}
export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* (
storage: SecureCatalogStorage,
) {
const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
const lock = yield* Semaphore.make(1);
const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () {
const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
const catalog =
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
Effect.mapError((cause) => catalogError("migrate", cause)),
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
),
),
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);
}
return catalog;
});
const loadUnlocked = Effect.fn("mobile.connectionStorage.loadCatalog")(function* () {
const cached = yield* Ref.get(state);
if (Option.isSome(cached)) {
return cached.value;
}
const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
);
} else {
catalog = yield* loadLegacyCatalog();
}
yield* Ref.set(state, Option.some(catalog));
return catalog;
});
const read = lock.withPermits(1)(loadUnlocked());
const update: CatalogStore["update"] = Effect.fn("mobile.connectionStorage.updateCatalog")(
function* (transform) {
yield* lock.withPermits(1)(
Effect.gen(function* () {
const next = transform(yield* loadUnlocked());
const encoded = yield* encodeCatalog(next);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* Ref.set(state, Option.some(next));
}),
);
},
);
return { read, update } satisfies CatalogStore;
});
-5
View File
@@ -1,5 +0,0 @@
import { createEnvironmentCatalogAtoms } from "@t3tools/client-runtime/state/connections";
import { connectionAtomRuntime } from "./runtime";
export const environmentCatalog = createEnvironmentCatalogAtoms(connectionAtomRuntime);
@@ -1,78 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { migrateLegacyConnectionCatalog } from "./migration";
describe("migrateLegacyConnectionCatalog", () => {
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
Effect.gen(function* () {
const bearerEnvironmentId = EnvironmentId.make("bearer-environment");
const relayEnvironmentId = EnvironmentId.make("relay-environment");
const catalog = yield* migrateLegacyConnectionCatalog(
JSON.stringify({
connections: [
{
environmentId: bearerEnvironmentId,
environmentLabel: "Local Mac",
pairingUrl: "https://local.example.test/pair",
displayUrl: "https://local.example.test",
httpBaseUrl: "https://local.example.test",
wsBaseUrl: "wss://local.example.test",
bearerToken: "bearer-token",
authenticationMethod: "bearer",
},
{
environmentId: relayEnvironmentId,
environmentLabel: "Cloud Mac",
pairingUrl: "https://relay.example.test",
displayUrl: "https://relay.example.test",
httpBaseUrl: "https://relay.example.test",
wsBaseUrl: "wss://relay.example.test",
bearerToken: null,
authenticationMethod: "dpop",
relayManaged: true,
},
],
}),
);
expect(catalog.targets).toHaveLength(2);
expect(
catalog.targets.find((target) => target.environmentId === bearerEnvironmentId)?._tag,
).toBe("BearerConnectionTarget");
expect(
catalog.targets.find((target) => target.environmentId === relayEnvironmentId)?._tag,
).toBe("RelayConnectionTarget");
expect(catalog.profiles).toHaveLength(1);
expect(catalog.credentials).toHaveLength(1);
expect(catalog.credentials[0]?.credential).toMatchObject({
_tag: "BearerConnectionCredential",
token: "bearer-token",
});
}),
);
it.effect("drops invalid legacy bearer entries without credentials", () =>
Effect.gen(function* () {
const catalog = yield* migrateLegacyConnectionCatalog(
JSON.stringify({
connections: [
{
environmentId: EnvironmentId.make("invalid-bearer"),
environmentLabel: "Invalid",
pairingUrl: "https://invalid.example.test/pair",
displayUrl: "https://invalid.example.test",
httpBaseUrl: "https://invalid.example.test",
wsBaseUrl: "wss://invalid.example.test",
bearerToken: null,
authenticationMethod: "bearer",
},
],
}),
);
expect(catalog.targets).toEqual([]);
}),
);
});
-110
View File
@@ -1,110 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionRegistration,
RelayConnectionRegistration,
RelayConnectionTarget,
BearerConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
type ConnectionCatalogDocument,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
registerConnectionInCatalog,
} from "@t3tools/client-runtime/platform";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const LegacySavedRemoteConnection = Schema.Struct({
environmentId: EnvironmentId,
environmentLabel: Schema.String,
pairingUrl: Schema.String,
displayUrl: Schema.String,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
bearerToken: Schema.NullOr(Schema.String),
authenticationMethod: Schema.optionalKey(Schema.Literals(["bearer", "dpop"])),
dpopAccessToken: Schema.optionalKey(Schema.String),
relayManaged: Schema.optionalKey(Schema.Literal(true)),
});
const LegacyConnectionDocument = Schema.Struct({
connections: Schema.optionalKey(Schema.Array(LegacySavedRemoteConnection)),
});
const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnectionDocument);
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
"LegacyConnectionMigrationError",
{
message: Schema.String,
},
) {}
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
}
function migrateConnection(
document: ConnectionCatalogDocument,
connection: typeof LegacySavedRemoteConnection.Type,
): ConnectionCatalogDocument {
if (isRelayManaged(connection)) {
return registerConnectionInCatalog(
document,
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: connection.environmentId,
label: connection.environmentLabel,
}),
}),
);
}
if (connection.bearerToken === null || connection.bearerToken.trim() === "") {
return document;
}
const connectionId = `bearer:${connection.environmentId}`;
return registerConnectionInCatalog(
document,
new BearerConnectionRegistration({
target: new BearerConnectionTarget({
environmentId: connection.environmentId,
label: connection.environmentLabel,
connectionId,
}),
profile: new BearerConnectionProfile({
connectionId,
environmentId: connection.environmentId,
label: connection.environmentLabel,
httpBaseUrl: connection.httpBaseUrl,
wsBaseUrl: connection.wsBaseUrl,
}),
credential: new BearerConnectionCredential({
token: connection.bearerToken,
}),
}),
);
}
export const migrateLegacyConnectionCatalog = Effect.fn(
"mobile.connectionMigration.migrateCatalog",
)(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
new LegacyConnectionMigrationError({
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
}),
});
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
Effect.mapError(
(cause) =>
new LegacyConnectionMigrationError({
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
}),
),
);
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
});
-35
View File
@@ -1,35 +0,0 @@
import { ConnectionOnboarding } from "@t3tools/client-runtime/connection";
import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { connectionAtomRuntime } from "./runtime";
const onboardingScheduler = createAtomCommandScheduler();
export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {
label: "mobile:connection:connect-pairing-url",
scheduler: onboardingScheduler,
concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },
execute: (pairingUrl: string) =>
ConnectionOnboarding.pipe(
Effect.flatMap((onboarding) => onboarding.registerPairing({ pairingUrl })),
),
});
export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime, {
label: "mobile:connection:update-bearer",
scheduler: onboardingScheduler,
concurrency: {
mode: "serial",
key: (input: { readonly environmentId: EnvironmentId }) => input.environmentId,
},
execute: (input: {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly httpBaseUrl: string;
}) => ConnectionOnboarding.pipe(Effect.flatMap((onboarding) => onboarding.updateBearer(input))),
});
-205
View File
@@ -1,205 +0,0 @@
import {
ClientPresentation,
CloudSession,
EnvironmentOwnedDataCleanup,
PlatformConnectionSource,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
ConnectionWakeups,
Connectivity,
} from "@t3tools/client-runtime/connection";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { AuthStandardClientScopes } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as Network from "expo-network";
import { AppState } from "react-native";
import { authClientMetadata } from "../lib/authClientMetadata";
import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
if (state.isConnected === false || state.isInternetReachable === false) {
return "offline";
}
if (state.isConnected === true) {
return "online";
}
return "unknown";
}
const connectivityLayer = Layer.succeed(
Connectivity,
Connectivity.of({
status: Effect.tryPromise({
try: () => Network.getNetworkStateAsync(),
catch: () => undefined,
}).pipe(
Effect.match({
onFailure: () => "unknown" as const,
onSuccess: networkStatus,
}),
),
changes: Stream.callback((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
Network.addNetworkStateListener((state) => {
Queue.offerUnsafe(queue, networkStatus(state));
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
}),
);
const wakeupsLayer = Layer.succeed(
ConnectionWakeups,
ConnectionWakeups.of({
changes: Stream.merge(
Stream.callback<"application-active">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
AppState.addEventListener("change", (state) => {
if (state === "active") {
Queue.offerUnsafe(queue, "application-active");
}
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
managedRelayAccountChanges(appAtomRegistry).pipe(
Stream.map(() => "credentials-changed" as const),
),
),
}),
);
const capabilitiesLayer = Layer.succeedContext(
Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
message: "Sign in to T3 Cloud to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
message: error.message,
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
message: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not load the mobile device identity: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.some)),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
message: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
message: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
),
);
const platformConnectionSourceLayer = Layer.succeed(
PlatformConnectionSource,
PlatformConnectionSource.of({
registrations: Stream.empty,
}),
);
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
EnvironmentOwnedDataCleanup.of({
clear: (environmentId) =>
Effect.all(
[
Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
],
{ concurrency: "unbounded", discard: true },
).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not clear mobile environment-owned data.", {
environmentId,
cause,
}),
),
),
}),
);
export const connectionPlatformLayer = Layer.mergeAll(
connectionStorageLayer,
connectivityLayer,
wakeupsLayer,
capabilitiesLayer,
platformConnectionSourceLayer,
environmentOwnedDataCleanupLayer,
);
-16
View File
@@ -1,16 +0,0 @@
import { connectionLayer as clientConnectionLayer } from "@t3tools/client-runtime/connection";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
import { runtimeContextLayer } from "../lib/runtime";
import { connectionPlatformLayer } from "./platform";
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
export const connectionLayer = clientConnectionLayer.pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
export const connectionAtomRuntime = Atom.runtime(connectionLayer);
@@ -1,84 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import {
CONNECTION_CATALOG_KEY,
LEGACY_CONNECTIONS_KEY,
makeCatalogStore,
type SecureCatalogStorage,
} from "./catalog-store";
function makeStorage(initial: Readonly<Record<string, string>>) {
const values = new Map(Object.entries(initial));
const deleted: Array<string> = [];
const storage: SecureCatalogStorage = {
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
setItem: (key, value) =>
Effect.sync(() => {
values.set(key, value);
}),
deleteItem: (key) =>
Effect.sync(() => {
deleted.push(key);
values.delete(key);
}),
};
return { deleted, storage, values };
}
describe("mobile connection catalog storage", () => {
it.effect("recovers from a corrupt current catalog", () =>
Effect.gen(function* () {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]);
}),
);
it.effect("replaces and removes a corrupt legacy catalog", () =>
Effect.gen(function* () {
const memory = makeStorage({
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }),
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]);
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
}),
);
it.effect("falls back to valid legacy data when the current catalog is corrupt", () =>
Effect.gen(function* () {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({
connections: [
{
environmentId: "legacy-environment",
environmentLabel: "Legacy",
pairingUrl: "https://legacy.example.test/pair",
displayUrl: "https://legacy.example.test",
httpBaseUrl: "https://legacy.example.test",
wsBaseUrl: "wss://legacy.example.test",
bearerToken: "legacy-token",
authenticationMethod: "bearer",
},
],
}),
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toHaveLength(1);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]);
yield* catalog.update((document) => document);
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
expect(memory.values.has(LEGACY_CONNECTIONS_KEY)).toBe(false);
}),
);
});
-432
View File
@@ -1,432 +0,0 @@
import {
ConnectionPersistenceError,
ConnectionRegistrationStore,
ConnectionTargetStore,
EnvironmentCacheStore,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
replaceCatalogValue,
} from "@t3tools/client-runtime/platform";
import { RemoteDpopAccessTokenStore } from "@t3tools/client-runtime/authorization";
import {
ConnectionCredentialStore,
ConnectionProfileStore,
ConnectionTransientError,
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
THREAD_SNAPSHOT_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
environmentId: EnvironmentId,
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => catalogError("load", cause),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => catalogError("save", cause),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => catalogError("delete", cause),
}),
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, directoryName);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const shellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
const legacyShellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const catalog = yield* makeCatalogStore(secureCatalogStorage);
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
});
const profileStore = ConnectionProfileStore.of({
get: (connectionId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.profiles.find((candidate) => candidate.connectionId === connectionId),
),
),
),
put: (profile) =>
catalog.update((document) => ({
...document,
profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
})),
remove: (connectionId) =>
catalog.update((document) => ({
...document,
profiles: removeCatalogValue(
document.profiles,
(value) => value.connectionId,
connectionId,
),
})),
});
const credentialStore = ConnectionCredentialStore.of({
get: (connectionId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
),
),
),
put: (connectionId, credential) =>
catalog.update((document) => ({
...document,
credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
connectionId,
credential,
}),
})),
remove: (connectionId) =>
catalog.update((document) => ({
...document,
credentials: removeCatalogValue(
document.credentials,
(value) => value.connectionId,
connectionId,
),
})),
});
const remoteTokenStore = RemoteDpopAccessTokenStore.of({
get: (environmentId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
),
),
),
put: (token) =>
catalog.update((document) => ({
...document,
remoteDpopTokens: replaceCatalogValue(
document.remoteDpopTokens,
(value) => value.environmentId,
token,
),
})),
remove: (environmentId) =>
catalog.update((document) => ({
...document,
remoteDpopTokens: removeCatalogValue(
document.remoteDpopTokens,
(value) => value.environmentId,
environmentId,
),
})),
});
const cacheStore = EnvironmentCacheStore.of({
loadShell: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "load-shell");
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
if (!legacyFile.exists) {
return Option.none();
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
}),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "save-shell");
const stored = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
}),
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
file.delete();
}
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
);
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
Context.add(ConnectionRegistrationStore, registrationStore),
Context.add(ConnectionProfileStore, profileStore),
Context.add(ConnectionCredentialStore, credentialStore),
Context.add(RemoteDpopAccessTokenStore, remoteTokenStore),
Context.add(EnvironmentCacheStore, cacheStore),
);
}),
);
@@ -2,8 +2,7 @@ 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";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import * as Layer from "effect/Layer";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
@@ -34,85 +33,90 @@ const connection: SavedRemoteConnection = {
bearerToken: "local-bearer",
};
const testLayer = Layer.mergeAll(
Layer.succeed(ManagedRelayClient, null as never),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
);
const runWithHttpClient = <A, E>(
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>,
): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provideService(ManagedRelayClient, null as never),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
),
);
describe("liveActivityPreferences", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it.effect("pushes disabled Live Activity preferences to relay registrations", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
it("pushes disabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: "clerk-token",
connections: [connection],
});
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer)),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
it.effect("pushes enabled Live Activity preferences to relay registrations", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
it("pushes enabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection],
});
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer)),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
it.effect("keeps local preferences refreshable when signed out", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
it("keeps local preferences refreshable when signed out", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: null,
connections: [connection],
});
}),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
}).pipe(Effect.provide(testLayer)),
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
});
it.effect("does not try to re-link managed relay connections without bearer credentials", () => {
it("does not try to re-link managed relay connections without bearer credentials", async () => {
const managedConnection: SavedRemoteConnection = {
...connection,
bearerToken: null,
};
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
});
}),
);
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer));
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
});
@@ -1,6 +1,6 @@
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
@@ -1,6 +1,6 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { Preferences } from "../../lib/storage";
import type { MobilePreferences } from "../../lib/storage";
export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string;
@@ -10,7 +10,7 @@ export function makeRelayDeviceRegistrationRequest(input: {
readonly pushToken?: string;
readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean;
readonly preferences: Preferences;
readonly preferences: MobilePreferences;
}): RelayDeviceRegistrationRequest {
const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false;
return {
@@ -6,16 +6,15 @@ 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";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { type ManagedRelayClient } from "@t3tools/client-runtime/relay";
import type { ManagedRelayClient } from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { mobileCryptoLayer } from "../cloud/dpop";
import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
__resetAgentAwarenessRemoteRegistrationForTest,
@@ -34,12 +33,6 @@ const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []),
}));
const backgroundRuntime = vi.hoisted(() => ({
pending: [] as Array<{
readonly operation: unknown;
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
}>,
}));
vi.mock("expo-constants", () => ({
default: {
@@ -102,11 +95,17 @@ vi.mock("react-native", () => ({
}));
vi.mock("../../lib/runtime", () => ({
runtime: {
runPromiseExit: (operation: unknown) =>
new Promise((resolve) => {
backgroundRuntime.pending.push({ operation, resolve });
}),
mobileRuntime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) =>
Effect.runPromise(
operation.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
),
},
}));
@@ -139,40 +138,34 @@ function savedConnection(): SavedRemoteConnection {
};
}
const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
);
const runRegistrationEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
);
const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
function* () {
let idlePasses = 0;
for (;;) {
yield* Effect.promise(() => Promise.resolve());
const pending = backgroundRuntime.pending.shift();
if (!pending) {
idlePasses++;
if (idlePasses >= 3) {
return;
}
continue;
}
idlePasses = 0;
const exit = yield* Effect.exit(
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
);
yield* Effect.sync(() => {
pending.resolve(exit);
});
async function waitForFetchCalls(
fetchMock: ReturnType<typeof vi.fn>,
count: number,
): Promise<void> {
for (let attempt = 0; attempt < 20; attempt += 1) {
if (fetchMock.mock.calls.length >= count) {
return;
}
},
);
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
describe("makeRelayDeviceRegistrationRequest", () => {
beforeEach(() => {
vi.unstubAllGlobals();
vi.stubGlobal("__DEV__", false);
secureStore.clear();
backgroundRuntime.pending.length = 0;
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
widgetMocks.getInstances.mockReset();
@@ -250,7 +243,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
});
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
it("registers at most one listener while a Live Activity push token is pending", async () => {
registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn();
const activity = {
@@ -258,64 +251,56 @@ describe("makeRelayDeviceRegistrationRequest", () => {
addPushTokenListener,
};
return Effect.gen(function* () {
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
});
it.effect(
"reports Live Activity token registration as skipped when relay auth is unavailable",
() => {
registerAgentAwarenessConnection(savedConnection());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
}).pipe(Effect.provide(relayTestLayer));
},
);
it.effect(
"registers APNS-started Live Activities for relay updates without mutating them locally",
() => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
start: vi.fn(),
update: vi.fn(),
end: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshActiveLiveActivityRemoteRegistration();
expect(activity.getPushToken).toHaveBeenCalled();
expect(activity.start).not.toHaveBeenCalled();
expect(activity.update).not.toHaveBeenCalled();
expect(activity.end).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
},
);
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
it("reports Live Activity token registration as skipped when relay auth is unavailable", async () => {
registerAgentAwarenessConnection(savedConnection());
return Effect.gen(function* () {
yield* runBackgroundOperations();
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
yield* refreshAgentAwarenessRegistration();
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
});
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
it("registers APNS-started Live Activities for relay updates without mutating them locally", async () => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
start: vi.fn(),
update: vi.fn(),
end: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
await runRegistrationEffect(refreshActiveLiveActivityRemoteRegistration());
expect(activity.getPushToken).toHaveBeenCalled();
expect(activity.start).not.toHaveBeenCalled();
expect(activity.update).not.toHaveBeenCalled();
expect(activity.end).not.toHaveBeenCalled();
});
it("refreshes APNs registration for connected environments after settings changes", async () => {
registerAgentAwarenessConnection(savedConnection());
await new Promise((resolve) => setTimeout(resolve, 0));
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
await runRegistrationEffect(refreshAgentAwarenessRegistration());
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
});
it.effect("registers the APNs device when cloud auth becomes available", () => {
@@ -345,7 +330,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
expect(fetchMock).toHaveBeenCalledTimes(2);
const [request, init] = fetchMock.mock.calls[1] as unknown as [
@@ -372,65 +357,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
nowEpochSeconds: proofIat(dpop),
}),
).toMatchObject({ ok: true });
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("coalesces simultaneous sign-in and environment connection registrations", () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
vi.mocked(Notifications.getPermissionsAsync).mockClear();
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
registerAgentAwarenessConnection(savedConnection());
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(Notifications.getPermissionsAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("continues queued device registration after a failed auth lookup", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
const tokenProvider = vi
.fn<() => Promise<string | null>>()
.mockRejectedValueOnce(new Error("auth unavailable"))
.mockResolvedValue("clerk-token-user-a");
setAgentAwarenessRelayTokenProvider(tokenProvider);
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(backgroundRuntime.pending).toHaveLength(0);
expect(tokenProvider).toHaveBeenCalledTimes(2);
}).pipe(Effect.provide(relayTestLayer));
});
it("only registers again when the authenticated identity changes", () => {
@@ -440,7 +367,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);
});
it.effect("registers rotated APNs tokens without rereading the native token", () => {
it("registers rotated APNs tokens without rereading the native token", async () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
@@ -471,10 +398,9 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
});
it.effect(
@@ -506,13 +432,13 @@ describe("makeRelayDeviceRegistrationRequest", () => {
registerAgentAwarenessConnection(savedConnection());
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* runBackgroundOperations();
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
fetchMock.mockClear();
unregisterAgentAwarenessConnection(savedConnection().environmentId);
expect(fetchMock).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
});
},
);
});
@@ -8,16 +8,10 @@ import {
type RelayDeviceRegistrationRequest,
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import {
isAtomCommandInterrupted,
settleAsyncResult,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import { mobileRuntime } from "../../lib/runtime";
import {
loadAgentAwarenessDeviceId,
loadOrCreateAgentAwarenessDeviceId,
@@ -35,20 +29,6 @@ let pushTokenSubscription: { remove: () => void } | null = null;
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
let deviceRegistrationGeneration = 0;
let activeDeviceRegistration: {
readonly input: DeviceRegistrationInput;
operation: Promise<void>;
} | null = null;
let pendingDeviceRegistration: {
readonly input: DeviceRegistrationInput;
readonly context: string;
} | null = null;
interface DeviceRegistrationInput {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}
export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined,
@@ -88,11 +68,6 @@ export function setAgentAwarenessRelayTokenProvider(
const isExistingIdentity =
provider !== null &&
!shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
if (!isExistingIdentity) {
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
}
relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) {
@@ -115,7 +90,7 @@ export function setAgentAwarenessRelayTokenProvider(
if (isExistingIdentity) {
return;
}
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed");
}
function iosMajorVersion(): number {
@@ -174,41 +149,20 @@ const relayToken = Effect.gen(function* () {
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled before relay request", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!readRelayConfig()) return;
const token = yield* relayToken;
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in");
return;
}
const client = yield* ManagedRelayClient;
logRegistrationDebug("relay device registration request started", {
expectedGeneration,
});
yield* client.registerDevice({
clerkToken: token,
payload: body,
});
logRegistrationDebug("relay device registration request completed", {
expectedGeneration,
});
});
}
@@ -259,11 +213,10 @@ function logRegistrationError(context: string, error: unknown): void {
if (!__DEV__) {
return;
}
console.warn(`[agent-awareness] ${context}`, {
message: error instanceof Error ? error.message : String(error),
traceId: findErrorTraceId(error),
error,
});
console.warn(
`[agent-awareness] ${context}`,
error instanceof Error ? error.message : String(error),
);
}
function logRegistrationDebug(context: string, details?: unknown): void {
@@ -277,107 +230,20 @@ function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
context: string,
): void {
void (async () => {
const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(context, squashAtomCommandFailure(result));
}
})();
}
function mergeDeviceRegistrationInput(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): DeviceRegistrationInput {
return {
...((next.pushToStartToken ?? current.pushToStartToken)
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
: {}),
...((next.observedPushToken ?? current.observedPushToken)
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
: {}),
};
}
function registrationAddsInformation(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): boolean {
return (
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
);
}
function startPendingDeviceRegistration(): void {
if (activeDeviceRegistration || !pendingDeviceRegistration) {
return;
}
const next = pendingDeviceRegistration;
pendingDeviceRegistration = null;
const generation = deviceRegistrationGeneration;
logRegistrationDebug("device registration started", {
generation,
hasObservedPushToken: next.input.observedPushToken !== undefined,
hasPushToStartToken: next.input.pushToStartToken !== undefined,
void mobileRuntime.runPromise(operation).catch((error: unknown) => {
logRegistrationError(context, error);
});
const registration = {
input: next.input,
operation: Promise.resolve(),
};
activeDeviceRegistration = registration;
registration.operation = (async () => {
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(registerDevice(next.input, generation)),
);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(next.context, squashAtomCommandFailure(result));
}
logRegistrationDebug("device registration finished", { generation });
if (activeDeviceRegistration === registration) {
activeDeviceRegistration = null;
}
startPendingDeviceRegistration();
})();
}
function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
if (
activeDeviceRegistration &&
!registrationAddsInformation(activeDeviceRegistration.input, input)
) {
logRegistrationDebug("device registration coalesced with active request", {
generation: deviceRegistrationGeneration,
});
return;
}
logRegistrationDebug("device registration enqueued", {
generation: deviceRegistrationGeneration,
hasActiveRegistration: activeDeviceRegistration !== null,
hasPendingRegistration: pendingDeviceRegistration !== null,
});
pendingDeviceRegistration = pendingDeviceRegistration
? {
input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
context,
}
: { input, context };
startPendingDeviceRegistration();
}
function registerDevice(
input: DeviceRegistrationInput = {},
expectedGeneration = deviceRegistrationGeneration,
): Effect.Effect<void, unknown, ManagedRelayClient> {
function registerDevice(input?: {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
logRegistrationDebug("device registration skipped; platform does not support it");
return;
}
logRegistrationDebug("device registration loading local state", { expectedGeneration });
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
@@ -389,10 +255,6 @@ function registerDevice(
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
logRegistrationDebug("device registration local state ready", {
expectedGeneration,
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
});
yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({
deviceId,
@@ -404,7 +266,6 @@ function registerDevice(
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences,
}),
expectedGeneration,
);
});
}
@@ -416,7 +277,10 @@ function registerDeviceForCurrentUser(
}
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
runRegistrationInBackground(
registerDeviceForCurrentUser(pushToStartToken),
"push-to-start token registration failed",
);
}
function ensurePushToStartListener(): void {
@@ -439,8 +303,8 @@ function ensurePushTokenListener(): void {
pushTokenSubscription = Notifications.addPushTokenListener((token) => {
if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
enqueueDeviceRegistration(
{ observedPushToken: token.data.trim() },
runRegistrationInBackground(
registerDevice({ observedPushToken: token.data.trim() }),
"native APNs token rotation registration failed",
);
}
@@ -455,7 +319,7 @@ export function registerAgentAwarenessConnection(connection: SavedRemoteConnecti
environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener();
ensurePushTokenListener();
enqueueDeviceRegistration({}, "device registration failed");
runRegistrationInBackground(registerDevice(), "device registration failed");
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after environment connection failed",
@@ -508,9 +372,6 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
}
relayTokenProvider = null;
relayTokenProviderIdentity = null;
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
}
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -1,95 +0,0 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { useArchivedThreadListActions } from "../home/useThreadListActions";
import {
ArchivedThreadsScreen,
type ArchivedThreadsHeaderEnvironment,
} from "./ArchivedThreadsScreen";
import { buildArchivedThreadGroups, type ArchivedThreadSortOrder } from "./archivedThreadList";
import {
refreshArchivedThreadsForEnvironment,
useArchivedThreadSnapshots,
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const [sortOrder, setSortOrder] = useState<ArchivedThreadSortOrder>("newest");
const environments = useMemo<ReadonlyArray<ArchivedThreadsHeaderEnvironment>>(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(Order.String, (environment: ArchivedThreadsHeaderEnvironment) =>
environment.label.toLocaleLowerCase(),
),
),
[savedConnectionsById],
);
const environmentIds = useMemo(
() => environments.map((environment) => environment.environmentId),
[environments],
);
const environmentLabels = useMemo(
() =>
Object.fromEntries(
environments.map((environment) => [environment.environmentId, environment.label]),
),
[environments],
);
const { error, isLoading, refresh, snapshots } = useArchivedThreadSnapshots(environmentIds);
const groups = useMemo(
() =>
buildArchivedThreadGroups({
snapshots,
environmentLabels,
environmentId: selectedEnvironmentId,
searchQuery,
sortOrder,
}),
[environmentLabels, searchQuery, selectedEnvironmentId, snapshots, sortOrder],
);
const refreshChangedEnvironment = useCallback(
(thread: { readonly environmentId: EnvironmentId }) => {
refreshArchivedThreadsForEnvironment(thread.environmentId);
},
[],
);
const { unarchiveThread, confirmDeleteThread } =
useArchivedThreadListActions(refreshChangedEnvironment);
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [expand, refresh]),
);
return (
<ArchivedThreadsScreen
environments={environments}
error={error}
groups={groups}
isLoading={isLoading}
onDeleteThread={confirmDeleteThread}
onEnvironmentChange={setSelectedEnvironmentId}
onRefresh={refresh}
onSearchQueryChange={setSearchQuery}
onSortOrderChange={setSortOrder}
onUnarchiveThread={unarchiveThread}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
sortOrder={sortOrder}
/>
);
}
@@ -1,434 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useRef } from "react";
import {
ActivityIndicator,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "../home/thread-swipe-actions";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
export interface ArchivedThreadsHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
const THREAD_ACTIONS: MenuAction[] = [
{
id: "unarchive",
title: "Unarchive",
image: "arrow.uturn.backward",
},
{
id: "delete",
title: "Delete",
image: "trash",
attributes: { destructive: true },
},
];
function ArchivedThreadsHeader(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
}) {
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
return (
<>
<Stack.Screen
options={{
title: "Archived Threads",
headerSearchBarOptions: {
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
placement: "stacked",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Sort by archived date">
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
</>
);
}
function ProjectGroupLabel(props: {
readonly environmentLabel: string | null;
readonly project: EnvironmentProject;
}) {
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
projectTitle={props.project.title}
size={18}
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
numberOfLines={1}
style={{ letterSpacing: 0.5 }}
>
{props.project.title}
</Text>
{props.environmentLabel ? (
<Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
{props.environmentLabel}
</Text>
) : null}
</View>
);
}
function ArchivedThreadRow(props: {
readonly environmentLabel: string | null;
readonly isLast: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onUnarchive: () => void;
readonly thread: EnvironmentThreadShell;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const cardColor = useThemeColor("--color-card");
const iconColor = useThemeColor("--color-icon-subtle");
const separatorColor = useThemeColor("--color-separator");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
if (event.nativeEvent.event === "unarchive") {
props.onUnarchive();
} else if (event.nativeEvent.event === "delete") {
props.onDelete();
}
},
[props.onDelete, props.onUnarchive],
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<Text
className="min-w-0 flex-1 text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
</ReanimatedSwipeable>
);
}
function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
return (
<View className="rounded-[20px] border border-danger-border bg-danger p-4">
<Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
<Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
<Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
</Pressable>
</View>
);
}
export function ArchivedThreadsScreen(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly error: string | null;
readonly groups: ReadonlyArray<ArchivedThreadGroup>;
readonly isLoading: boolean;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onRefresh: () => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const refreshTint = useThemeColor("--color-icon");
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
openSwipeableRef.current.close();
}
openSwipeableRef.current = methods;
}, []);
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current === methods) {
openSwipeableRef.current = null;
}
}, []);
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
return (
<View className="flex-1 bg-sheet">
<ArchivedThreadsHeader
environments={props.environments}
onEnvironmentChange={props.onEnvironmentChange}
onSearchQueryChange={props.onSearchQueryChange}
onSortOrderChange={props.onSortOrderChange}
selectedEnvironmentId={props.selectedEnvironmentId}
sortOrder={props.sortOrder}
/>
<ScrollView
className="flex-1"
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
thread={thread}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
</View>
);
}
@@ -1,144 +0,0 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildArchivedThreadGroups } from "./archivedThreadList";
const environmentId = EnvironmentId.make("environment-1");
function makeProject(
input: Partial<OrchestrationProjectShell> & Pick<OrchestrationProjectShell, "id" | "title">,
): OrchestrationProjectShell {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<OrchestrationThreadShell> &
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
): OrchestrationThreadShell {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: "2026-06-02T00:00:00.000Z",
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
function makeSnapshot(
projects: ReadonlyArray<OrchestrationProjectShell>,
threads: ReadonlyArray<OrchestrationThreadShell>,
targetEnvironmentId = environmentId,
): ArchivedSnapshotEntry {
return {
environmentId: targetEnvironmentId,
snapshot: {
snapshotSequence: 1,
projects,
threads,
updatedAt: "2026-06-04T00:00:00.000Z",
},
};
}
describe("buildArchivedThreadGroups", () => {
it("groups archived threads by project and sorts newest first", () => {
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const older = makeThread({
id: ThreadId.make("thread-older"),
projectId: project.id,
title: "Older",
});
const newer = makeThread({
archivedAt: "2026-06-03T00:00:00.000Z",
id: ThreadId.make("thread-newer"),
projectId: project.id,
title: "Newer",
});
const result = buildArchivedThreadGroups({
snapshots: [makeSnapshot([project], [older, newer])],
environmentLabels: { [environmentId]: "Julius's MacBook Pro" },
environmentId: null,
searchQuery: "",
sortOrder: "newest",
});
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-newer", "thread-older"]);
});
it("filters by environment and matches project, thread, and branch text", () => {
const secondEnvironmentId = EnvironmentId.make("environment-2");
const firstProject = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const secondProject = makeProject({ id: ProjectId.make("project-2"), title: "Website" });
const firstThread = makeThread({
branch: "fix/archive-screen",
id: ThreadId.make("thread-1"),
projectId: firstProject.id,
title: "Build settings route",
});
const secondThread = makeThread({
id: ThreadId.make("thread-2"),
projectId: secondProject.id,
title: "Unrelated",
});
const snapshots = [
makeSnapshot([firstProject], [firstThread]),
makeSnapshot([secondProject], [secondThread], secondEnvironmentId),
];
const result = buildArchivedThreadGroups({
snapshots,
environmentLabels: {
[environmentId]: "Local",
[secondEnvironmentId]: "Remote",
},
environmentId,
searchQuery: "archive-screen",
sortOrder: "oldest",
});
expect(result).toHaveLength(1);
expect(result[0]?.project.environmentId).toBe(environmentId);
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-1"]);
});
it("ignores non-archived entries returned in a snapshot", () => {
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const active = makeThread({
archivedAt: null,
id: ThreadId.make("thread-active"),
projectId: project.id,
title: "Active",
});
const result = buildArchivedThreadGroups({
snapshots: [makeSnapshot([project], [active])],
environmentLabels: {},
environmentId: null,
searchQuery: "",
sortOrder: "newest",
});
expect(result).toEqual([]);
});
});
@@ -1,106 +0,0 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import {
scopeProject,
scopeThreadShell,
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
export type ArchivedThreadSortOrder = "newest" | "oldest";
export interface ArchivedThreadGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
function archiveTimestamp(thread: EnvironmentThreadShell): number {
const timestamp = Date.parse(thread.archivedAt ?? thread.updatedAt);
return Number.isNaN(timestamp) ? 0 : timestamp;
}
function matchesQuery(value: string | null, query: string): boolean {
return value?.toLocaleLowerCase().includes(query) ?? false;
}
export function buildArchivedThreadGroups(input: {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly environmentLabels: Readonly<Record<string, string>>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly sortOrder: ArchivedThreadSortOrder;
}): ReadonlyArray<ArchivedThreadGroup> {
const query = input.searchQuery.trim().toLocaleLowerCase();
const groups: ArchivedThreadGroup[] = [];
for (const entry of input.snapshots) {
if (input.environmentId !== null && input.environmentId !== entry.environmentId) {
continue;
}
const environmentLabel = input.environmentLabels[entry.environmentId] ?? null;
const threadsByProjectId = new Map<string, EnvironmentThreadShell[]>();
for (const thread of entry.snapshot.threads) {
if (thread.archivedAt === null) {
continue;
}
const threads = threadsByProjectId.get(thread.projectId) ?? [];
threads.push(scopeThreadShell(entry.environmentId, thread));
threadsByProjectId.set(thread.projectId, threads);
}
for (const rawProject of entry.snapshot.projects) {
const project = scopeProject(entry.environmentId, rawProject);
const projectThreads = threadsByProjectId.get(project.id) ?? [];
const groupMatches =
query.length === 0 ||
matchesQuery(project.title, query) ||
matchesQuery(project.workspaceRoot, query) ||
matchesQuery(environmentLabel, query);
const matchingThreads = groupMatches
? projectThreads
: projectThreads.filter(
(thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
);
if (matchingThreads.length === 0) {
continue;
}
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
groups.push({
key: scopedProjectKey(project.environmentId, project.id),
project,
threads: Arr.sort(
matchingThreads,
Order.mapInput(
Order.Struct({ timestamp: timestampOrder, title: Order.String, id: Order.String }),
(thread: EnvironmentThreadShell) => ({
timestamp: archiveTimestamp(thread),
title: thread.title,
id: thread.id,
}),
),
),
});
}
}
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
return Arr.sort(
groups,
Order.mapInput(
Order.Struct({ timestamp: timestampOrder, title: Order.String, key: Order.String }),
(group: ArchivedThreadGroup) => ({
timestamp: group.threads[0] ? archiveTimestamp(group.threads[0]) : 0,
title: group.project.title,
key: group.key,
}),
),
);
}
@@ -1,47 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import {
type ArchivedSnapshotEntry,
createArchivedThreadSnapshotsAtomFamily,
makeArchivedThreadsEnvironmentKey,
} from "@t3tools/client-runtime/state/threads";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { orchestrationEnvironment } from "../../state/orchestration";
function archivedSnapshotAtom(environmentId: EnvironmentId) {
return orchestrationEnvironment.archivedShellSnapshot({
environmentId,
input: {},
});
}
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
getSnapshotAtom: archivedSnapshotAtom,
labelPrefix: "mobile:archived-thread-snapshots",
});
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
}
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly error: string | null;
readonly isLoading: boolean;
readonly refresh: () => void;
} {
const environmentKey = useMemo(
() => makeArchivedThreadsEnvironmentKey(environmentIds),
[environmentIds],
);
const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
const refresh = useCallback(() => {
for (const environmentId of environmentIds) {
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
}
}, [environmentIds]);
return { ...result, refresh };
}
@@ -1,60 +0,0 @@
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { appAtomRegistry } from "../../state/atom-registry";
import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
vi.mock("@clerk/expo", () => ({
ClerkProvider: vi.fn(),
useAuth: vi.fn(),
}));
vi.mock("@clerk/expo/token-cache", () => ({
tokenCache: {},
}));
vi.mock("../../lib/runtime", () => ({
runtime: {
runPromiseExit: vi.fn(),
},
}));
vi.mock("../../connection/catalog", () => ({
environmentCatalog: {
removeRelayEnvironments: {},
},
}));
vi.mock("./publicConfig", () => ({
resolveCloudPublicConfig: vi.fn(() => ({
clerk: { publishableKey: null },
relay: { url: null },
})),
resolveRelayClerkTokenOptions: vi.fn(),
}));
vi.mock("../agent-awareness/remoteRegistration", () => ({
setAgentAwarenessRelayTokenProvider: vi.fn(),
unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),
}));
afterEach(() => {
deactivateCloudRelayAccount();
vi.clearAllMocks();
});
describe("CloudAuthProvider relay account isolation", () => {
it("clears relay and agent-awareness credentials before cleanup can fail", async () => {
const tokenProvider = async () => "account-1-token";
activateCloudRelayAccount("account-1", tokenProvider);
expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");
deactivateCloudRelayAccount();
const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);
expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
expect(vi.mocked(setAgentAwarenessRelayTokenProvider)).toHaveBeenLastCalledWith(null);
await cleanup;
});
});
@@ -1,149 +1,63 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime";
import { type ReactNode, useEffect, useRef } from "react";
import { environmentCatalog } from "../../connection/catalog";
import { runtime } from "../../lib/runtime";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
return settleAsyncResult(() =>
runtime.runPromiseExit(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
),
);
}
export function deactivateCloudRelayAccount(): void {
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
}
export function activateCloudRelayAccount(
accountId: string,
tokenProvider: () => Promise<string | null>,
): void {
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: tokenProvider,
});
}
function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
reportFailure: false,
reportDefect: false,
});
const previousTokenProviderRef = useRef<{
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null>(null);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef<Promise<void> | null>(null);
useEffect(() => {
let cancelled = false;
if (!isLoaded) {
return;
}
const previousObservedAccount = observedAccountRef.current;
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
const queueAccountCleanup = (
previous: {
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null,
) => {
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
accountTransitionRef.current = previousTransition.then(async () => {
const cleanup = [
resetManagedRelayTokenCache(),
removeRelayEnvironments(),
...(previous
? [
settleAsyncResult(() =>
runtime.runPromiseExit(
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
),
),
]
: []),
];
const results = await Promise.all(cleanup);
for (const result of results) {
reportAtomCommandResult(result, { label: "cloud account cleanup" });
}
});
return accountTransitionRef.current;
};
if (!isSignedIn || !userId) {
const previous = previousTokenProviderRef.current;
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
if (previousObservedAccount !== null) {
void queueAccountCleanup(previous);
if (previous) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
return;
}
const previous = previousTokenProviderRef.current;
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
const activateSession = () => {
if (cancelled) {
return;
}
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
const result = await settlePromise(async () => {
await transition;
activateSession();
});
reportAtomCommandResult(result, { label: "cloud account activation" });
})();
};
if (
previousObservedAccount !== undefined &&
previousObservedAccount !== null &&
previousObservedAccount !== userId
) {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
activateAfterTransition(queueAccountCleanup(previous));
} else {
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
if (previous && previous.userId !== userId) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
return () => {
cancelled = true;
};
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
previousTokenProviderRef.current = { userId, provider: tokenProvider };
setAgentAwarenessRelayTokenProvider(tokenProvider, userId);
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId: userId,
readClerkToken: tokenProvider,
}),
);
}, [getToken, isLoaded, isSignedIn, userId]);
useEffect(
() => () => {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
},
[],
);
@@ -158,7 +72,8 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) {
useEffect(() => {
if (!publishableKey || !relayUrl) {
deactivateCloudRelayAccount();
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
}
}, [publishableKey, relayUrl]);
@@ -1,18 +0,0 @@
export function isCloudDebugEnabled(): boolean {
return (
(typeof __DEV__ !== "undefined" && __DEV__) ||
(typeof globalThis !== "undefined" &&
(globalThis as { __T3_CLOUD_DEBUG__?: boolean }).__T3_CLOUD_DEBUG__ === true)
);
}
export function cloudDebugLog(event: string, data?: Record<string, unknown>): void {
if (!isCloudDebugEnabled()) {
return;
}
if (data) {
console.log(`[t3-cloud] ${event}`, data);
} else {
console.log(`[t3-cloud] ${event}`);
}
}
@@ -1,88 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { describe, expect, it } from "vite-plus/test";
import { availableCloudEnvironmentPresentation } from "./cloudEnvironmentPresentation";
function relayStatus(
status: RelayEnvironmentStatusResponse["status"],
error?: string,
traceId?: string,
): RelayEnvironmentStatusResponse {
return {
environmentId: EnvironmentId.make("environment-cloud"),
endpoint: {
httpBaseUrl: "https://cloud.example.test/",
wsBaseUrl: "wss://cloud.example.test/ws",
providerKind: "cloudflare_tunnel",
},
status,
checkedAt: "2026-06-05T16:49:11.000Z",
...(error ? { error } : {}),
...(traceId ? { traceId } : {}),
};
}
describe("available cloud environment presentation", () => {
it("presents an online unsaved environment as available, not connected", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: relayStatus("online"),
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Relay online",
});
});
it("keeps relay status checks distinct from connection attempts", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: true,
status: null,
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Checking relay status...",
});
});
it("surfaces an offline relay as an error", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: relayStatus("offline", "Tunnel is unavailable.", "trace-offline"),
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: "Tunnel is unavailable.",
connectionErrorTraceId: "trace-offline",
connectionState: "error",
statusText: "Tunnel is unavailable.",
});
});
it("preserves trace metadata for relay request failures", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: null,
statusError: "Could not get relay environment status.",
statusErrorTraceId: "trace-status",
}),
).toMatchObject({
connectionError: "Could not get relay environment status.",
connectionErrorTraceId: "trace-status",
});
});
});
@@ -1,53 +0,0 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
export interface AvailableCloudEnvironmentPresentation {
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly statusText: string;
}
export function availableCloudEnvironmentPresentation(input: {
readonly isStatusPending: boolean;
readonly status: RelayEnvironmentStatusResponse | null;
readonly statusError: string | null;
readonly statusErrorTraceId: string | null;
}): AvailableCloudEnvironmentPresentation {
if (input.status?.status === "online") {
return {
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Relay online",
};
}
if (input.status?.status === "offline") {
const connectionError = input.status.error ?? "Relay is offline.";
return {
connectionError,
connectionErrorTraceId: input.status.traceId ?? null,
connectionState: "error",
statusText: connectionError,
};
}
if (input.statusError) {
return {
connectionError: input.statusError,
connectionErrorTraceId: input.statusErrorTraceId,
connectionState: "error",
statusText: input.statusError,
};
}
return {
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: input.isStatusPending
? "Available · Checking relay status..."
: "Available · Relay status unknown",
};
}
+6 -6
View File
@@ -12,7 +12,7 @@ import {
createDpopProof,
generateDpopProofKeyPair,
loadOrCreateDpopProofKeyPair,
cryptoLayer,
mobileCryptoLayer,
} from "./dpop";
vi.mock("expo-crypto", () => ({
@@ -75,7 +75,7 @@ describe("mobile DPoP", () => {
expect(Buffer.from(digest).toString("hex")).toBe(
NodeCrypto.createHash("sha256").update("typed-array").digest("hex"),
);
}).pipe(Effect.provide(cryptoLayer)),
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("persists and reuses the installation proof key", () =>
@@ -86,7 +86,7 @@ describe("mobile DPoP", () => {
expect(second.thumbprint).toBe(first.thumbprint);
expect(second.privateJwk).toEqual(first.privateJwk);
}).pipe(Effect.provide(cryptoLayer)),
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("rejects malformed persisted proof keys", () =>
@@ -96,7 +96,7 @@ describe("mobile DPoP", () => {
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error.message).toBe("Stored DPoP proof key is invalid.");
}).pipe(Effect.provide(cryptoLayer)),
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
@@ -135,7 +135,7 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(bootstrap.proof),
}),
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
}).pipe(Effect.provide(cryptoLayer)),
}).pipe(Effect.provide(mobileCryptoLayer)),
);
it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
@@ -161,6 +161,6 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(proof.proof),
}),
).toMatchObject({ ok: true });
}).pipe(Effect.provide(cryptoLayer)),
}).pipe(Effect.provide(mobileCryptoLayer)),
);
});
+1 -1
View File
@@ -70,7 +70,7 @@ function toExpoDigestAlgorithm(
}
}
export const cryptoLayer = Layer.succeed(
export const mobileCryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: ExpoCrypto.getRandomBytes,
@@ -8,8 +8,8 @@ import {
managedRelayClientLayer,
ManagedRelayClient,
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
remoteHttpClientLayer,
} from "@t3tools/client-runtime";
import { HttpClient } from "effect/unstable/http";
import {
@@ -55,8 +55,6 @@ const savedConnection = {
bearerToken: "local-bearer",
};
const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";
const createProofMock = vi.fn(
(input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
Effect.succeed(`dpop:${input.method}:${input.url}`),
@@ -354,7 +352,7 @@ describe("mobile cloud link environment client", () => {
});
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }));
expect(
fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
@@ -427,11 +425,9 @@ describe("mobile cloud link environment client", () => {
yield* withCloudServices(
Effect.gen(function* () {
const records = yield* listCloudEnvironmentsWithStatus({
clerkToken: stableClerkToken,
});
const records = yield* listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" });
yield* connectCloudEnvironment({
clerkToken: stableClerkToken,
clerkToken: "clerk-token",
environment: records[0]!.environment,
});
}),
@@ -662,7 +658,6 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
traceId: "trace-test",
});
expect(fetchMock).toHaveBeenCalledTimes(3);
}),
@@ -1008,7 +1003,6 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
traceId: "trace-connect",
});
}),
);
Loaded 100 of 772 files, more files were not shown because too many files have changed in this diff. Show more