Compare commits

..
Author SHA1 Message Date
Julius Marminge 38f46e6971 Refresh mobile dependency lockfile
- Update React Native peer dependency snapshots and local module hashes
2026-06-21 14:19:53 -07:00
Julius Marmingeandcodex ed0b6119c2 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-18 00:20:24 -07:00
Julius Marmingeandcodex b01bf05c50 Restore retained environment HTTP test helper
Co-authored-by: codex <[email protected]>
2026-06-18 00:19:18 -07:00
Julius Marmingeandcodex 344fca1edc Restore client behavior and stabilize async UI state
Co-authored-by: codex <[email protected]>
2026-06-18 00:17:04 -07:00
Julius Marminge c09f491b37 nuke browser tests cause codex just gets caught up in them 2026-06-18 00:00:47 -07:00
Julius Marmingeandcodex c55ae239ff Harden terminal reconnection and asset URL handling
- Keep terminal state consistent across close, reopen, and stale metadata
- Load historical attachments through signed asset URLs
- Serialize resizes and ignore requests for closed terminals

Co-authored-by: codex <[email protected]>
2026-06-17 22:24:54 -07:00
Julius Marminge ca35205f43 Stabilize draft promotion and live session recovery
- Finalize promoted drafts from inferred live threads
- Retry transient RPC and thread sync failures within a session
- Preserve full thread history and delay shell cache persistence
2026-06-17 19:26:56 -07:00
Julius Marminge 2b9cf7d18a Refactor connection-aware asset and VCS state handling
- Route mobile/web asset URLs through shared runtime state
- Replace remote HTTP header plumbing with environment asset URLs
- Add optional cached remote status reads without upstream refresh
2026-06-17 16:36:38 -07:00
Julius Marmingeandcodex a2ed9bbb4f Fix browser atom command mocks
Co-authored-by: codex <[email protected]>
2026-06-17 00:41:42 -07:00
Julius Marmingeandcodex 841bbd9a17 Harden connection state handling across app
- adopt atom command results for connection and relay flows
- preserve relay error trace IDs and improve failure handling
- add coverage for auth, registration, and environment updates

Co-authored-by: codex <[email protected]>
2026-06-16 23:47:55 -07:00
Julius Marminge 55228d4119 rm doc 2026-06-16 23:38:01 -07:00
Julius Marminge ebda0b6d28 rm service indirection 2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex bd079220f8 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex c1281076e6 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 16:47:56 -07:00
Julius Marmingeandcodex 449d7993d1 Centralize client runtime state management
Co-authored-by: codex <[email protected]>
2026-06-16 15:42:37 -07:00
Julius Marmingeandcodex 2eaface4b1 Rewrite client connection architecture
Move web, desktop, server, and mobile connection state onto the shared client runtime while preserving the separately reviewed native mobile UI stack.

Co-authored-by: codex <[email protected]>
2026-06-16 11:11:45 -07:00
241 changed files with 5395 additions and 10723 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
-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
-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,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 });
}),
);
@@ -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);
+12 -2
View File
@@ -1,6 +1,13 @@
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,
@@ -33,7 +40,6 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
@@ -48,7 +54,6 @@ 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);
@@ -75,6 +80,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);
+6 -2
View File
@@ -3,6 +3,12 @@ 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 UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
@@ -12,8 +18,6 @@ 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";
@@ -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(Object.fromEntries(headers.entries())),
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));
}),
});
-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),
+7 -19
View File
@@ -27,13 +27,13 @@ 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 DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.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";
@@ -119,6 +119,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -148,30 +149,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),
+17 -5
View File
@@ -4,13 +4,10 @@ import type {
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
@@ -42,8 +39,6 @@ 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),
@@ -100,6 +95,23 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
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* () {
@@ -121,9 +121,6 @@ export interface DesktopSavedEnvironmentsShape {
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>;
@@ -296,23 +293,6 @@ export const layer = Layer.effect(
).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(
@@ -405,18 +385,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))),
@@ -191,19 +191,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 +231,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));
}),
+30 -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;
@@ -328,7 +350,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",
@@ -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] = []
+1 -2
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",
@@ -101,7 +101,6 @@
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.12",
"react-native-svg": "15.15.4",
"react-native-webview": "^13.16.1",
"react-native-worklets": "0.8.3",
"shiki": "4.2.0",
"tailwind-merge": "^3.5.0",
+2 -3
View File
@@ -30,11 +30,10 @@ 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>
);
+89 -88
View File
@@ -1,33 +1,13 @@
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 { 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 ───────────────────────────────────────────────────── */
@@ -38,82 +18,103 @@ export default function HomeRouteScreen() {
const { savedConnectionsById } = useSavedRemoteConnections();
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",
hideNavigationBar: false,
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
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}
/>
</>
);
+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;
+2 -16
View File
@@ -65,8 +65,6 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -376,8 +374,6 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -420,20 +416,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");
@@ -471,9 +459,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>
);
}
-5
View File
@@ -3,7 +3,6 @@ import {
CloudSession,
EnvironmentOwnedDataCleanup,
PlatformConnectionSource,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
@@ -120,10 +119,6 @@ const capabilitiesLayer = Layer.succeedContext(
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
@@ -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 };
}
@@ -110,7 +110,6 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly styleJson?: string;
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
@@ -1,166 +0,0 @@
import { useMemo } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
type NativeMarkdownTextStyle,
} from "../../native/SelectableMarkdownText";
interface MarkdownPreviewStyles {
readonly theme: PartialMarkdownTheme;
readonly styles: NodeStyleOverrides;
readonly renderers: CustomRenderers;
readonly nativeTextStyle: NativeMarkdownTextStyle;
}
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const body = String(useThemeColor("--color-md-body"));
const strong = String(useThemeColor("--color-md-strong"));
const link = String(useThemeColor("--color-md-link"));
const blockquoteBorder = String(useThemeColor("--color-md-blockquote-border"));
const blockquoteBackground = String(useThemeColor("--color-md-blockquote-bg"));
const codeBackground = String(useThemeColor("--color-md-code-bg"));
const codeText = String(useThemeColor("--color-md-code-text"));
const horizontalRule = String(useThemeColor("--color-md-hr"));
return useMemo(() => {
const renderers: CustomRenderers = {
link: ({ href, children }) => (
<NativeText
onPress={() => {
if (href) {
void Linking.openURL(href);
}
}}
style={{
color: link,
fontFamily: "DMSans_500Medium",
textDecorationLine: "none",
}}
>
{children}
</NativeText>
),
};
return {
theme: {
colors: {
text: body,
heading: strong,
link,
blockquote: blockquoteBorder,
border: horizontalRule,
surfaceLight: blockquoteBackground,
accent: link,
tableBorder: horizontalRule,
tableHeader: blockquoteBackground,
tableHeaderText: strong,
code: codeText,
codeBackground,
},
},
styles: {
text: {
color: body,
fontFamily: "DMSans_400Regular",
fontSize: 15,
lineHeight: 22,
},
heading: {
color: strong,
fontFamily: "DMSans_700Bold",
},
strong: {
color: strong,
fontFamily: "DMSans_700Bold",
},
link: {
color: link,
fontFamily: "DMSans_500Medium",
},
blockquote: {
backgroundColor: blockquoteBackground,
borderLeftColor: blockquoteBorder,
borderLeftWidth: 3,
paddingLeft: 12,
},
code: {
backgroundColor: codeBackground,
color: codeText,
fontFamily: "ui-monospace",
},
codeBlock: {
backgroundColor: codeBackground,
borderRadius: 12,
color: codeText,
fontFamily: "ui-monospace",
padding: 12,
},
hr: {
backgroundColor: horizontalRule,
},
},
renderers,
nativeTextStyle: {
color: body,
strongColor: strong,
mutedColor: body,
linkColor: link,
inlineCodeColor: codeText,
codeColor: codeText,
codeBackgroundColor: codeBackground,
codeBlockBackgroundColor: codeBackground,
fileTextColor: codeText,
skillTextColor: codeText,
quoteMarkerColor: blockquoteBorder,
dividerColor: horizontalRule,
fontSize: 15,
lineHeight: 22,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
},
};
}, [
blockquoteBackground,
blockquoteBorder,
body,
codeBackground,
codeText,
horizontalRule,
link,
strong,
]);
}
export function FileMarkdownPreview(props: { readonly markdown: string }) {
const styles = useMarkdownPreviewStyles();
return (
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
<View className="mx-auto w-full max-w-[760px]">
{hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
) : (
<Markdown
options={{ gfm: true }}
renderers={styles.renderers}
styles={styles.styles}
theme={styles.theme}
>
{props.markdown}
</Markdown>
)}
</View>
</ScrollView>
);
}
@@ -1,191 +0,0 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import {
buildFileTree,
defaultExpandedTreePaths,
flattenFileTree,
type VisibleFileTreeNode,
} from "./fileTree";
function ancestorPaths(path: string): ReadonlyArray<string> {
const parts = path.split("/").filter(Boolean);
const ancestors: string[] = [];
for (let index = 1; index < parts.length; index += 1) {
ancestors.push(parts.slice(0, index).join("/"));
}
return ancestors;
}
const FileTreeRow = memo(function FileTreeRow(props: {
readonly item: VisibleFileTreeNode;
readonly selectedPath: string | null;
readonly expanded: boolean;
readonly iconColor: string;
readonly onPressDirectory: (path: string) => void;
readonly onPressFile: (path: string) => void;
}) {
const { node, depth } = props.item;
const selected = node.kind === "file" && node.path === props.selectedPath;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={node.path}
onPress={() => {
if (node.kind === "directory") {
props.onPressDirectory(node.path);
return;
}
props.onPressFile(node.path);
}}
className={cn(
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
selected && "bg-subtle-strong",
)}
style={{ paddingLeft: 8 + depth * 18 }}
>
{node.kind === "directory" ? (
<SymbolView
name={props.expanded ? "chevron.down" : "chevron.right"}
size={12}
tintColor={props.iconColor}
type="monochrome"
/>
) : (
<View className="w-3" />
)}
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
<Text
className={cn(
"min-w-0 flex-1 text-[14px] leading-[19px]",
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
)}
numberOfLines={1}
>
{node.name}
</Text>
{node.kind === "directory" ? (
<Text className="text-[11px] font-t3-medium text-foreground-tertiary">
{node.children.length}
</Text>
) : null}
</Pressable>
);
});
export function FileTreeBrowser(props: {
readonly entries: ReadonlyArray<ProjectEntry>;
readonly error: string | null;
readonly isPending: boolean;
readonly searchQuery: string;
readonly selectedPath: string | null;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
}) {
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
const iconColor = String(useThemeColor("--color-icon-muted"));
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
const visibleNodes = useMemo(
() =>
flattenFileTree({
nodes: tree,
expanded: expandedPaths,
searchQuery: props.searchQuery,
}),
[expandedPaths, props.searchQuery, tree],
);
useEffect(() => {
setExpandedPaths((current) => {
if (current.size > 0 || defaultExpanded.size === 0) {
return current;
}
return new Set(defaultExpanded);
});
}, [defaultExpanded]);
useEffect(() => {
if (!props.selectedPath) {
return;
}
setExpandedPaths((current) => {
const next = new Set(current);
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
next.add(ancestor);
}
return next;
});
}, [props.selectedPath]);
const toggleDirectory = useCallback((path: string) => {
setExpandedPaths((current) => {
const next = new Set(current);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
return (
<View className="flex-1 bg-sheet">
{props.error && props.entries.length === 0 ? (
<View className="px-4 py-5">
<Text className="text-[13px] font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
{props.error}
</Text>
</View>
) : (
<FlatList
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingVertical: 8 }}
refreshControl={
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
}
renderItem={({ item }) => (
<FileTreeRow
item={item}
selectedPath={props.selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPressFile={props.onSelectFile}
/>
)}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-[13px] font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
</View>
}
/>
)}
</View>
);
}
@@ -1,252 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ComponentType } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
import {
type NativeReviewDiffViewProps,
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
import {
REVIEW_DIFF_LINE_HEIGHT,
REVIEW_MONO_FONT_FAMILY,
renderVisibleWhitespace,
} from "../review/reviewDiffRendering";
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
NATIVE_SOURCE_CONTENT_WIDTH,
NATIVE_SOURCE_ROW_HEIGHT,
NATIVE_SOURCE_STYLE,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { sourceHighlightAtom } from "./sourceHighlightingState";
const SOURCE_LINE_HEIGHT = 24;
const SOURCE_LINE_NUMBER_WIDTH = 58;
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
interface SourceFileSurfaceProps {
readonly contents: string;
readonly path: string;
readonly initialLine?: number | null;
}
type SourceHighlightStatus = "highlighting" | "ready" | "error";
function splitSourceLines(contents: string): ReadonlyArray<string> {
return contents.replace(/\r\n?/g, "\n").split("\n");
}
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
readonly index: number;
readonly line: string;
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
readonly highlighted: boolean;
}) {
return (
<View
className={cn("flex-row", props.highlighted && "bg-primary/10")}
style={{ minHeight: SOURCE_LINE_HEIGHT }}
>
<NativeText
className="select-none pr-3 text-right text-[11px] leading-[24px] text-foreground-tertiary"
style={{
width: SOURCE_LINE_NUMBER_WIDTH,
fontFamily: REVIEW_MONO_FONT_FAMILY,
}}
>
{props.index + 1}
</NativeText>
<NativeText
selectable
numberOfLines={1}
className="text-[13px] font-medium leading-[24px] text-foreground"
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY, minWidth: 320 }}
>
{props.tokens && props.tokens.length > 0
? (() => {
let offset = 0;
return props.tokens.map((token) => {
const start = offset;
offset += token.content.length;
const fontWeight =
token.fontStyle !== null && (token.fontStyle & 2) === 2
? ("700" as const)
: ("500" as const);
const fontStyle =
token.fontStyle !== null && (token.fontStyle & 1) === 1
? ("italic" as const)
: ("normal" as const);
return (
<NativeText
key={`${start}:${token.content.length}:${token.color ?? ""}`}
selectable
style={{
color: token.color ?? undefined,
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontWeight,
fontStyle,
}}
>
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
</NativeText>
);
});
})()
: renderVisibleWhitespace(props.line || " ")}
</NativeText>
</View>
);
});
function useSourceFileModel(props: SourceFileSurfaceProps) {
const colorScheme = useColorScheme();
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
const normalizedContents = useMemo(
() => props.contents.replace(/\r\n?/g, "\n"),
[props.contents],
);
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
const targetIndex =
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
: null;
const highlightAtom = useMemo(
() => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
[normalizedContents, props.path, theme],
);
const highlightResult = useAtomValue(highlightAtom);
const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
? "error"
: AsyncResult.isSuccess(highlightResult)
? "ready"
: "highlighting";
return { lines, status, targetIndex, theme, tokens };
}
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
if (props.status === "highlighting") {
return <LoadingStrip />;
}
if (props.status === "error") {
return (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-[11px] font-t3-medium uppercase text-foreground-muted">
Plain text
</Text>
</View>
);
}
return null;
}
function NativeSourceFileSurface(
props: SourceFileSurfaceProps & {
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView } = props;
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
[targetIndex],
);
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
return (
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<NativeView
key={props.path}
collapsable={false}
testID="source-native-code-view"
style={{ flex: 1 }}
appearanceScheme={theme}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
rowsJson={rowsJson}
selectedRowIdsJson={selectedRowIdsJson}
styleJson={NATIVE_SOURCE_STYLE_JSON}
themeJson={themeJson}
tokensJson={tokensJson}
/>
</View>
);
}
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
const listRef = useRef<FlatList<string>>(null);
useEffect(() => {
if (targetIndex === null) {
return;
}
const frame = requestAnimationFrame(() => {
listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
});
return () => cancelAnimationFrame(frame);
}, [props.path, targetIndex]);
const renderLine = useCallback(
({ item, index }: { item: string; index: number }) => (
<HighlightedSourceLine
index={index}
line={item}
tokens={tokens?.[index] ?? null}
highlighted={index === targetIndex}
/>
),
[targetIndex, tokens],
);
return (
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<ScrollView horizontal bounces={false} className="flex-1">
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
getItemLayout={(_data, index) => ({
length: SOURCE_LINE_HEIGHT,
offset: SOURCE_LINE_HEIGHT * index,
index,
})}
contentContainerStyle={{
minWidth: "100%",
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
paddingTop: 8,
}}
renderItem={renderLine}
/>
</ScrollView>
</View>
);
}
export function SourceFileSurface(props: SourceFileSurfaceProps) {
const NativeView = resolveNativeReviewDiffView();
return NativeView ? (
<NativeSourceFileSurface {...props} NativeView={NativeView} />
) : (
<JavaScriptSourceFileSurface {...props} />
);
}
@@ -1,631 +0,0 @@
import Stack from "expo-router/stack";
import { SymbolView } from "expo-symbols";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Linking,
Pressable,
ScrollView,
Text as RNText,
View,
} from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
type ProjectListEntriesResult,
type ProjectReadFileResult,
ThreadId,
} from "@t3tools/contracts";
import { AppText as Text } from "../../components/AppText";
import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { SourceFileSurface } from "./SourceFileSurface";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
basename,
fileBreadcrumbs,
isBrowserPreviewFile,
isImagePreviewFile,
isMarkdownPreviewFile,
isSvgImagePreviewFile,
} from "./filePath";
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null;
}
return value ?? null;
}
function normalizeRoutePath(value: string | string[] | undefined): string | null {
const path = Array.isArray(value) ? value.join("/") : value;
if (path === undefined || path.trim().length === 0) {
return null;
}
return path;
}
function normalizeRouteLine(value: string | null): number | null {
if (value === null) {
return null;
}
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function defaultViewMode(path: string | null): FileViewMode {
return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
? "preview"
: "source";
}
function ModeButton(props: {
readonly active: boolean;
readonly icon: "doc.text" | "eye";
readonly label: string;
readonly onPress: () => void;
}) {
const iconColor = String(
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.active }}
className={cn(
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
props.active ? "bg-primary" : "bg-subtle",
)}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
<Text
className={cn(
"text-[12px] font-t3-bold",
props.active ? "text-primary-foreground" : "text-foreground-muted",
)}
>
{props.label}
</Text>
</Pressable>
);
}
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
const gradientId = `file-breadcrumb-${props.side}-fade`;
const isLeft = props.side === "left";
return (
<View
pointerEvents="none"
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
</View>
);
}
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const cardColor = String(useThemeColor("--color-card"));
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
const breadcrumbs = useMemo(
() => fileBreadcrumbs(props.projectName, props.relativePath),
[props.projectName, props.relativePath],
);
const updateFadeVisibility = useCallback(
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
Object.assign(scrollMetrics.current, metrics);
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
const maxOffset = Math.max(0, contentWidth - viewportWidth);
const next = {
left: maxOffset > 1 && offsetX > 1,
right: maxOffset > 1 && offsetX < maxOffset - 1,
};
setFadeVisibility((current) =>
current.left === next.left && current.right === next.right ? current : next,
);
},
[],
);
return (
<View className="min-w-0 flex-1">
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
onContentSizeChange={(contentWidth) => {
updateFadeVisibility({ contentWidth });
}}
onLayout={(event) => {
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
}}
onScroll={(event) => {
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
}}
scrollEventThrottle={16}
>
<View className="h-8 flex-row items-center">
{breadcrumbs.map((crumb, index) => (
<View key={crumb.path || "project"} className="flex-row items-center">
{index > 0 ? (
<SymbolView
name="chevron.right"
size={10}
tintColor={iconColor}
type="monochrome"
/>
) : null}
<Text
className={cn(
"max-w-[180px] px-1 text-[12px]",
crumb.kind === "file"
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-muted",
)}
numberOfLines={1}
>
{crumb.label}
</Text>
</View>
))}
</View>
</ScrollView>
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
</View>
);
}
function FilePreviewHeader(props: {
readonly activeMode: FileViewMode;
readonly showModeSelector: boolean;
readonly externalPreviewUri?: string | null;
readonly projectName: string;
readonly relativePath: string;
readonly onSetMode: (mode: FileViewMode) => void;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
return (
<View className="border-b border-border bg-card px-3 py-2">
<View className="flex-row items-center gap-2">
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
<CopyTextButton
accessibilityLabel="Copy file path"
text={props.relativePath}
tintColor={iconColor}
buttonSize={32}
iconSize={13}
/>
</View>
{props.showModeSelector ? (
<View className="mt-2 flex-row items-center gap-2">
<ModeButton
active={props.activeMode === "preview"}
icon="eye"
label="Preview"
onPress={() => props.onSetMode("preview")}
/>
<ModeButton
active={props.activeMode === "source"}
icon="doc.text"
label="Source"
onPress={() => props.onSetMode("source")}
/>
{props.externalPreviewUri !== undefined ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open preview in Safari"
disabled={props.externalPreviewUri === null}
hitSlop={8}
className={cn(
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
props.externalPreviewUri === null && "opacity-40",
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void Linking.openURL(props.externalPreviewUri);
}
}}
>
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
</Pressable>
) : null}
</View>
) : null}
</View>
);
}
function FileContent(props: {
readonly activeMode: FileViewMode;
readonly previewUri: string | null;
readonly fileContents: string | null;
readonly fileError: string | null;
readonly relativePath: string;
readonly initialLine: number | null;
readonly truncated: boolean;
}) {
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
const isImageFile = isImagePreviewFile(props.relativePath);
if (props.activeMode === "preview" && isImageFile) {
if (isSvgImagePreviewFile(props.relativePath)) {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
}
return (
<WorkspaceFileImagePreview
accessibilityLabel={basename(props.relativePath)}
uri={props.previewUri}
/>
);
}
if (props.activeMode === "preview" && isBrowserFile) {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
}
if (props.fileError && props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<EmptyState title="File unavailable" detail={props.fileError} />
</View>
);
}
if (props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Loading file...</Text>
</View>
);
}
return (
<View className="flex-1 bg-card">
{props.truncated ? (
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
<Text className="text-[11px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
Partial file
</Text>
<Text className="text-[12px] leading-[17px] text-amber-800 dark:text-amber-200">
Preview limited to the first 1 MB of a truncated file.
</Text>
</View>
) : null}
{props.activeMode === "preview" && isMarkdown ? (
<FileMarkdownPreview markdown={props.fileContents} />
) : (
<SourceFileSurface
contents={props.fileContents}
path={props.relativePath}
initialLine={props.initialLine}
/>
)}
</View>
);
}
function useThreadFilesWorkspace() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const routeEnvironmentId = firstRouteParam(params.environmentId);
const routeThreadId = firstRouteParam(params.threadId);
const { selectedThread, selectedThreadProject } = useThreadSelection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const environmentId =
routeEnvironmentId !== null
? EnvironmentId.make(routeEnvironmentId)
: (selectedThread?.environmentId ?? null);
const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
const project = selectedThreadProject as {
readonly title?: string;
readonly workspaceRoot?: string;
} | null;
return {
cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
environmentId,
projectName: project?.title ?? "Files",
selectedThread,
threadId,
};
}
function FilesUnavailable() {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<EmptyState
title="Files unavailable"
detail="This thread does not have an active workspace path."
/>
</View>
);
}
function FilesHeaderTitle(props: { readonly projectName: string }) {
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
return (
<View style={{ alignItems: "center", maxWidth: 220 }}>
<RNText
numberOfLines={1}
style={{
color: foregroundColor,
fontFamily: "DMSans_700Bold",
fontSize: 18,
fontWeight: "900",
letterSpacing: -0.4,
}}
>
Files
</RNText>
<RNText
numberOfLines={1}
style={{
color: secondaryForegroundColor,
fontFamily: "DMSans_500Medium",
fontSize: 12,
fontWeight: "500",
letterSpacing: 0.2,
}}
>
{props.projectName}
</RNText>
</View>
);
}
function FilesToolbarBottomFade() {
const sheetColor = String(useThemeColor("--color-sheet"));
if (process.env.EXPO_OS !== "ios") {
return null;
}
return (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{
bottom: 0,
height: 112,
left: 0,
position: "absolute",
right: 0,
zIndex: 1,
}}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
<Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
<Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
<Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
</Svg>
</View>
);
}
export function ThreadFilesTreeScreen() {
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null
? projectEnvironment.listEntries({
environmentId,
input: { cwd },
})
: null,
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleSelectFile = useCallback(
(path: string) => {
if (environmentId === null || threadId === null) {
return;
}
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
},
[environmentId, router, threadId],
);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
if (cwd === null) {
return <FilesUnavailable />;
}
return (
<View className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Files",
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
headerSearchBarOptions: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
</Stack.Toolbar>
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={null}
onRefresh={entriesQuery.refresh}
onSelectFile={handleSelectFile}
/>
<FilesToolbarBottomFade />
</View>
);
}
export function ThreadFileScreen() {
const params = useLocalSearchParams<{
line?: string | string[];
path?: string | string[];
}>();
const relativePath = normalizeRoutePath(params.path);
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const [modeOverride, setModeOverride] = useState<{
readonly path: string;
readonly mode: FileViewMode;
} | null>(null);
const [previewRevision, setPreviewRevision] = useState(0);
const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
const canPreview =
relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
const activeMode =
relativePath !== null && modeOverride?.path === relativePath
? modeOverride.mode
: defaultViewMode(relativePath);
const resolvedActiveMode = canPreview ? activeMode : "source";
const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
const assetPreviewUri = useWorkspaceFileAssetUrl({
cwd,
environmentId,
relativePath: assetPreviewPath,
threadId,
});
const previewUri =
assetPreviewUri === null || previewRevision === 0
? assetPreviewUri
: `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
const needsFileContents =
relativePath !== null &&
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
const fileQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
? projectEnvironment.readFile({
environmentId,
input: { cwd, relativePath },
})
: null,
);
const fileData = fileQuery.data as ProjectReadFileResult | null;
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
if (cwd === null) {
return <FilesUnavailable />;
}
if (relativePath === null) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<EmptyState title="File unavailable" detail="This file path is invalid." />
</View>
);
}
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: basename(relativePath) }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
setPreviewRevision((current) => current + 1);
return;
}
fileQuery.refresh();
}}
/>
</Stack.Toolbar>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</View>
</ReviewHighlighterProvider>
);
}
@@ -1,118 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { useMemo, useState } from "react";
import { ActivityIndicator, Image, Pressable, View } from "react-native";
import ImageViewing from "react-native-image-viewing";
import { AsyncResult } from "effect/unstable/reactivity";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { workspaceFileImageAtom } from "./workspace-file-image-cache";
function ResolvedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
}) {
const [loadError, setLoadError] = useState<string | null>(null);
const [fullScreenVisible, setFullScreenVisible] = useState(false);
const imageSource = useMemo(
() => ({ uri: props.uri, cache: "force-cache" as const }),
[props.uri],
);
const fullScreenImages = useMemo(() => [imageSource], [imageSource]);
return (
<View className="relative flex-1 bg-subtle">
<Pressable
accessibilityRole="button"
accessibilityLabel={`Open full-screen preview of ${props.accessibilityLabel}`}
disabled={loadError !== null}
className="flex-1 p-4 active:bg-subtle-strong"
onPress={() => setFullScreenVisible(true)}
>
<Image
accessible={false}
source={imageSource}
className="h-full w-full"
resizeMode="contain"
onLoadStart={() => setLoadError(null)}
onError={(event) => {
setLoadError(event.nativeEvent.error || "The image could not be rendered.");
}}
/>
</Pressable>
{loadError !== null ? (
<View className="absolute inset-0 items-center justify-center bg-card px-6">
<EmptyState title="Image unavailable" detail={loadError} />
</View>
) : null}
<ImageViewing
images={fullScreenImages}
imageIndex={0}
visible={fullScreenVisible}
onRequestClose={() => setFullScreenVisible(false)}
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
);
}
function CachedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
}) {
const imageAtom = useMemo(() => workspaceFileImageAtom(props.uri), [props.uri]);
const imageResult = useAtomValue(imageAtom);
if (AsyncResult.isFailure(imageResult)) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<EmptyState
title="Image unavailable"
detail="The image could not be loaded into the local cache."
/>
</View>
);
}
if (!AsyncResult.isSuccess(imageResult)) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Loading image...</Text>
</View>
);
}
return (
<ResolvedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={imageResult.value}
/>
);
}
export function WorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string | null;
}) {
if (props.uri === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">
Preparing image preview...
</Text>
</View>
);
}
return (
<CachedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={props.uri}
/>
);
}
@@ -1,62 +0,0 @@
import { useState } from "react";
import { ActivityIndicator, View } from "react-native";
import { WebView } from "react-native-webview";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
const [loadProgress, setLoadProgress] = useState(0);
const [loadError, setLoadError] = useState<string | null>(null);
if (props.uri === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Preparing preview...</Text>
</View>
);
}
return (
<View className="relative flex-1 bg-card">
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
{loadError ? (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-[12px] font-t3-bold text-foreground">Preview failed</Text>
<Text className="mt-0.5 text-[12px] leading-[17px] text-foreground-muted">
{loadError}
</Text>
</View>
) : null}
<WebView
source={{ uri: props.uri }}
originWhitelist={["*"]}
allowsBackForwardNavigationGestures
allowsFullscreenVideo
setSupportMultipleWindows={false}
startInLoadingState
onLoadProgress={(event) => {
setLoadProgress(event.nativeEvent.progress);
}}
onLoadStart={() => {
setLoadProgress(0.05);
setLoadError(null);
}}
onLoadEnd={() => {
setLoadProgress(0);
}}
onError={(event) => {
setLoadProgress(0);
setLoadError(event.nativeEvent.description || "The file could not be rendered.");
}}
renderLoading={() => (
<View className="absolute inset-0 items-center justify-center bg-card">
<ActivityIndicator />
</View>
)}
style={{ flex: 1, backgroundColor: "transparent" }}
/>
</View>
);
}
@@ -1,43 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
isBrowserPreviewFile,
isImagePreviewFile,
isSvgImagePreviewFile,
resolveWorkspaceRelativeFilePath,
} from "./filePath";
describe("resolveWorkspaceRelativeFilePath", () => {
it("keeps normalized workspace-relative paths", () => {
expect(resolveWorkspaceRelativeFilePath("/repo", "./src/../src/main.ts")).toBe("src/main.ts");
});
it("converts absolute paths inside the workspace", () => {
expect(
resolveWorkspaceRelativeFilePath("/Users/julius/repo", "/Users/julius/repo/src/main.ts"),
).toBe("src/main.ts");
expect(resolveWorkspaceRelativeFilePath("C:\\repo", "c:\\repo\\src\\main.ts")).toBe(
"src/main.ts",
);
});
it("rejects paths outside the workspace", () => {
expect(resolveWorkspaceRelativeFilePath("/repo", "/other/main.ts")).toBeNull();
expect(resolveWorkspaceRelativeFilePath("/repo", "../other/main.ts")).toBeNull();
expect(resolveWorkspaceRelativeFilePath(null, "/repo/main.ts")).toBeNull();
});
});
describe("file preview types", () => {
it("recognizes browser and image previews", () => {
expect(isBrowserPreviewFile("reports/summary.html")).toBe(true);
expect(isImagePreviewFile("assets/icon.png")).toBe(true);
expect(isImagePreviewFile("assets/diagram.SVG?raw=1")).toBe(true);
expect(isImagePreviewFile("src/image.ts")).toBe(false);
});
it("identifies SVG images that need web rendering", () => {
expect(isSvgImagePreviewFile("assets/diagram.svg#icon")).toBe(true);
expect(isSvgImagePreviewFile("assets/photo.png")).toBe(false);
});
});
-116
View File
@@ -1,116 +0,0 @@
import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
} from "@t3tools/shared/filePreview";
export interface FileBreadcrumb {
readonly label: string;
readonly path: string;
readonly kind: "project" | "directory" | "file";
}
function isWindowsAbsolutePath(value: string): boolean {
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
}
function isAbsolutePath(value: string): boolean {
return value.startsWith("/") || isWindowsAbsolutePath(value);
}
function isWindowsPathStyle(value: string): boolean {
return isWindowsAbsolutePath(value) || /^[A-Za-z]:\\/.test(value);
}
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
const cleanBase = base.replace(/[\\/]+$/, "");
if (separator === "\\") {
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
}
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
}
export function basename(path: string): string {
const parts = path.split(/[\\/]/).filter(Boolean);
return parts.at(-1) ?? path;
}
export function resolveWorkspaceFilePath(cwd: string, relativePath: string): string {
if (isAbsolutePath(relativePath)) {
return relativePath;
}
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
return joinPath(cwd, relativePath, separator);
}
function normalizeRelativePath(value: string): string | null {
const segments: string[] = [];
for (const segment of value.replaceAll("\\", "/").split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
if (segments.length === 0) {
return null;
}
segments.pop();
continue;
}
segments.push(segment);
}
return segments.length > 0 ? segments.join("/") : null;
}
export function resolveWorkspaceRelativeFilePath(
workspaceRoot: string | null | undefined,
targetPath: string,
): string | null {
if (!isAbsolutePath(targetPath)) {
if (targetPath.startsWith("~/") || targetPath.startsWith("~\\")) {
return null;
}
return normalizeRelativePath(targetPath);
}
if (!workspaceRoot) {
return null;
}
const normalizedTarget = targetPath.replaceAll("\\", "/");
const normalizedRoot = workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, "");
const caseInsensitive = isWindowsAbsolutePath(targetPath) || isWindowsAbsolutePath(workspaceRoot);
const comparableTarget = caseInsensitive ? normalizedTarget.toLowerCase() : normalizedTarget;
const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
if (!comparableTarget.startsWith(`${comparableRoot}/`)) {
return null;
}
return normalizeRelativePath(normalizedTarget.slice(normalizedRoot.length + 1));
}
export function isBrowserPreviewFile(path: string): boolean {
return isWorkspaceBrowserPreviewPath(path);
}
export function isImagePreviewFile(path: string): boolean {
return isWorkspaceImagePreviewPath(path);
}
export function isSvgImagePreviewFile(path: string): boolean {
return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? "");
}
export function isMarkdownPreviewFile(path: string): boolean {
return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
}
export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
const parts = relativePath.split("/").filter(Boolean);
return [
{ label: projectName, path: "", kind: "project" },
...parts.map((part, index) => ({
label: part,
path: parts.slice(0, index + 1).join("/"),
kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
})),
];
}
@@ -1,109 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import type { ProjectEntry } from "@t3tools/contracts";
import {
buildFileTree,
countFileNodes,
defaultExpandedTreePaths,
firstFilePath,
flattenFileTree,
} from "./fileTree";
const entries = [
{ kind: "file", path: "README.md" },
{ kind: "directory", path: "src" },
{ kind: "file", path: "src/index.ts" },
{ kind: "file", path: "src/components/App.tsx" },
{ kind: "file", path: "package.json" },
] satisfies ReadonlyArray<ProjectEntry>;
describe("mobile file tree helpers", () => {
it("builds a deterministic hierarchy with directories before files", () => {
const tree = buildFileTree(entries);
expect(tree.map((node) => `${node.kind}:${node.path}`)).toEqual([
"directory:src",
"file:package.json",
"file:README.md",
]);
expect(tree[0]?.children.map((node) => `${node.kind}:${node.path}`)).toEqual([
"directory:src/components",
"file:src/index.ts",
]);
expect(countFileNodes(tree)).toBe(4);
expect(firstFilePath(tree)).toBe("src/components/App.tsx");
});
it("flattens expanded directories and hides collapsed descendants", () => {
const tree = buildFileTree(entries);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(["src"]),
}).map((item) => `${item.depth}:${item.node.path}`),
).toEqual(["0:src", "1:src/components", "1:src/index.ts", "0:package.json", "0:README.md"]);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
}).map((item) => item.node.path),
).toEqual(["src", "package.json", "README.md"]);
});
it("includes matching descendants and their ancestors during search", () => {
const tree = buildFileTree(entries);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
searchQuery: "app",
}).map((item) => item.node.path),
).toEqual(["src", "src/components", "src/components/App.tsx"]);
});
it("supports fuzzy, whitespace-separated path queries", () => {
const tree = buildFileTree([
{
kind: "file",
path: ".plans/19-version-control-phase-1-vcs-driver-foundation.md",
},
{
kind: "file",
path: ".repos/alchemy-effect/examples/aws-lambda/src/JobNotifications.ts",
},
{ kind: "directory", path: "apps/web/src/components/chat" },
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.test.ts" },
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.tsx" },
{ kind: "file", path: "apps/web/src/components/chat/Composer.tsx" },
]);
const expectedPaths = [
"apps",
"apps/web",
"apps/web/src",
"apps/web/src/components",
"apps/web/src/components/chat",
"apps/web/src/components/chat/ChatHeader.test.ts",
"apps/web/src/components/chat/ChatHeader.tsx",
];
for (const searchQuery of ["chat hea", "cht hdr"]) {
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
searchQuery,
}).map((item) => item.node.path),
).toEqual(expectedPaths);
}
});
it("expands top-level directories by default", () => {
const tree = buildFileTree(entries);
expect([...defaultExpandedTreePaths(tree)]).toEqual(["src"]);
});
});
-220
View File
@@ -1,220 +0,0 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
export interface FileTreeNode {
readonly path: string;
readonly name: string;
readonly kind: ProjectEntry["kind"];
readonly children: ReadonlyArray<FileTreeNode>;
readonly searchSegments: ReadonlyArray<string>;
readonly searchWords: ReadonlyArray<string>;
}
export interface VisibleFileTreeNode {
readonly node: FileTreeNode;
readonly depth: number;
}
interface MutableFileTreeNode {
path: string;
name: string;
kind: ProjectEntry["kind"];
children: Map<string, MutableFileTreeNode>;
}
function createMutableNode(
path: string,
name: string,
kind: ProjectEntry["kind"],
): MutableFileTreeNode {
return {
path,
name,
kind,
children: new Map(),
};
}
function splitSearchWords(value: string): ReadonlyArray<string> {
return value
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((word) => word.toLowerCase());
}
function buildNodeSearchTerms(path: string): {
readonly segments: ReadonlyArray<string>;
readonly words: ReadonlyArray<string>;
} {
const segments: string[] = [];
const words: string[] = [];
for (const segment of path.split("/")) {
if (!segment) {
continue;
}
segments.push(segment.toLowerCase());
words.push(...splitSearchWords(segment));
}
return { segments, words };
}
function freezeNode(node: MutableFileTreeNode): FileTreeNode {
const searchTerms = buildNodeSearchTerms(node.path);
return {
path: node.path,
name: node.name,
kind: node.kind,
children: [...node.children.values()].sort(compareNodes).map(freezeNode),
searchSegments: searchTerms.segments,
searchWords: searchTerms.words,
};
}
function compareNodes(
left: Pick<FileTreeNode, "kind" | "name">,
right: Pick<FileTreeNode, "kind" | "name">,
): number {
if (left.kind !== right.kind) {
return left.kind === "directory" ? -1 : 1;
}
return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
}
export function buildFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
const root = createMutableNode("", "", "directory");
for (const entry of entries) {
const parts = entry.path.split("/").filter(Boolean);
if (parts.length === 0) {
continue;
}
let current = root;
for (let index = 0; index < parts.length; index += 1) {
const part = parts[index];
if (!part) {
continue;
}
const path = parts.slice(0, index + 1).join("/");
const isLeaf = index === parts.length - 1;
const kind = isLeaf ? entry.kind : "directory";
let child = current.children.get(part);
if (!child) {
child = createMutableNode(path, part, kind);
current.children.set(part, child);
} else if (isLeaf) {
child.kind = entry.kind;
}
current = child;
}
}
return [...root.children.values()].sort(compareNodes).map(freezeNode);
}
export function countFileNodes(nodes: ReadonlyArray<FileTreeNode>): number {
let count = 0;
for (const node of nodes) {
if (node.kind === "file") {
count += 1;
} else {
count += countFileNodes(node.children);
}
}
return count;
}
export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
const expanded = new Set<string>();
for (const node of nodes) {
if (node.kind === "directory") {
expanded.add(node.path);
}
}
return expanded;
}
function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
return (
scoreQueryMatch({
value,
query: token,
exactBase: 0,
prefixBase: 2,
boundaryBase: 4,
includesBase: 6,
...(fuzzy ? { fuzzyBase: 100 } : {}),
boundaryMarkers: ["/", "-", "_", "."],
}) !== null
);
}
function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
return tokens.every(
(token) =>
node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
);
}
function flattenNode(
output: VisibleFileTreeNode[],
node: FileTreeNode,
depth: number,
expanded: ReadonlySet<string>,
searchTokens: ReadonlyArray<string>,
): boolean {
const isSearching = searchTokens.length > 0;
const matches = isSearching && nodeMatchesSearch(node, searchTokens);
let descendantMatches = false;
const childOutput: VisibleFileTreeNode[] = [];
if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
for (const child of node.children) {
if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
descendantMatches = true;
}
}
}
const visible = !isSearching || matches || descendantMatches;
if (!visible) {
return false;
}
output.push({ node, depth });
output.push(...childOutput);
return matches || descendantMatches;
}
export function flattenFileTree(input: {
readonly nodes: ReadonlyArray<FileTreeNode>;
readonly expanded: ReadonlySet<string>;
readonly searchQuery?: string;
}): ReadonlyArray<VisibleFileTreeNode> {
const output: VisibleFileTreeNode[] = [];
const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
for (const node of input.nodes) {
flattenNode(output, node, 0, input.expanded, searchTokens);
}
return output;
}
export function firstFilePath(nodes: ReadonlyArray<FileTreeNode>): string | null {
for (const node of nodes) {
if (node.kind === "file") {
return node.path;
}
const child = firstFilePath(node.children);
if (child !== null) {
return child;
}
}
return null;
}
@@ -1,46 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
describe("nativeSourceFileAdapter", () => {
it("maps plain source lines onto context rows with stable line numbers", () => {
expect(buildNativeSourceRows(["const value = 1;", "\treturn value;"])).toEqual([
{
kind: "line",
id: nativeSourceRowId(0),
fileId: "source-file",
content: "const value = 1;",
change: "context",
newLineNumber: 1,
},
{
kind: "line",
id: nativeSourceRowId(1),
fileId: "source-file",
content: " return value;",
change: "context",
newLineNumber: 2,
},
]);
});
it("maps cached source tokens to the same row identifiers", () => {
expect(
buildNativeSourceTokens([
[{ content: "const", color: "#ff0000", fontStyle: 2 }],
[{ content: "\tvalue", color: null, fontStyle: null }],
]),
).toEqual({
[nativeSourceRowId(0)]: [{ content: "const", color: "#ff0000", fontStyle: 2 }],
[nativeSourceRowId(1)]: [{ content: " value", color: null, fontStyle: null }],
});
});
it("clears native tokens while highlighting is unavailable", () => {
expect(buildNativeSourceTokens(null)).toEqual({});
});
});
@@ -1,65 +0,0 @@
import type {
NativeReviewDiffRow,
NativeReviewDiffStyle,
NativeReviewDiffToken,
} from "../diffs/nativeReviewDiffSurface";
import type { SourceHighlightTokens } from "./sourceHighlightingState";
export const NATIVE_SOURCE_ROW_HEIGHT = 24;
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: 58,
codePadding: 8,
codeFontSize: 13,
codeFontWeight: "medium",
lineNumberFontSize: 11,
lineNumberFontWeight: "medium",
emptyStateFontSize: 12,
emptyStateFontWeight: "medium",
};
const SOURCE_FILE_ID = "source-file";
function expandTabs(value: string): string {
return value.replace(/\t/g, " ");
}
export function nativeSourceRowId(index: number): string {
return `source-line:${index}`;
}
export function buildNativeSourceRows(
lines: ReadonlyArray<string>,
): ReadonlyArray<NativeReviewDiffRow> {
return lines.map((line, index) => ({
kind: "line",
id: nativeSourceRowId(index),
fileId: SOURCE_FILE_ID,
content: expandTabs(line),
change: "context",
newLineNumber: index + 1,
}));
}
export function buildNativeSourceTokens(
tokenLines: SourceHighlightTokens | null,
): Readonly<Record<string, ReadonlyArray<NativeReviewDiffToken>>> {
if (tokenLines === null) {
return {};
}
return Object.fromEntries(
tokenLines.map((tokens, index) => [
nativeSourceRowId(index),
tokens.map((token) => ({
content: expandTabs(token.content),
color: token.color,
fontStyle: token.fontStyle,
})),
]),
);
}
@@ -1,123 +0,0 @@
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
createSourceHighlightAtomFamily,
type SourceHighlightTokens,
} from "./sourceHighlightingState";
const highlightedTokens: SourceHighlightTokens = [
[{ content: "const", color: "#0000ff", fontStyle: null }],
];
afterEach(() => {
vi.restoreAllMocks();
});
describe("sourceHighlightingState", () => {
it("reuses completed highlighting across equivalent route remounts", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 1_000 });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const input = {
path: "src/example.ts",
contents: "const value = 1;",
theme: "light" as const,
};
const firstAtom = sourceHighlightAtom(input);
const firstUnmount = registry.mount(firstAtom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
});
firstUnmount();
const remountedAtom = sourceHighlightAtom({ ...input });
const secondUnmount = registry.mount(remountedAtom);
expect(remountedAtom).toBe(firstAtom);
expect(AsyncResult.isSuccess(registry.get(remountedAtom))).toBe(true);
expect(highlight).toHaveBeenCalledTimes(1);
secondUnmount();
registry.dispose();
});
it("does not reuse highlighting when the source contents change", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
const registry = AtomRegistry.make();
const firstAtom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const secondAtom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 2;",
theme: "light",
});
const firstUnmount = registry.mount(firstAtom);
const secondUnmount = registry.mount(secondAtom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
expect(AsyncResult.isSuccess(registry.get(secondAtom))).toBe(true);
});
expect(secondAtom).not.toBe(firstAtom);
expect(highlight).toHaveBeenCalledTimes(2);
firstUnmount();
secondUnmount();
registry.dispose();
});
it("recomputes highlighting after the idle cache entry expires", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 5 });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const atom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const firstUnmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
firstUnmount();
await new Promise((resolve) => setTimeout(resolve, 25));
const secondUnmount = registry.mount(atom);
await vi.waitFor(() => {
expect(highlight).toHaveBeenCalledTimes(2);
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
secondUnmount();
registry.dispose();
});
it("exposes highlighter errors as a failed async result", async () => {
const highlight = vi.fn(async () => {
throw new Error("highlight failed");
});
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
const registry = AtomRegistry.make();
const atom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
unmount();
registry.dispose();
});
});
@@ -1,50 +0,0 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
import {
highlightSourceFile,
type ReviewDiffTheme,
type ReviewHighlightedToken,
} from "../review/shikiReviewHighlighter";
const SOURCE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000;
export interface SourceHighlightInput {
readonly path: string;
readonly contents: string;
readonly theme: ReviewDiffTheme;
}
export type SourceHighlightTokens = ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighlightTokens>;
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
readonly cause: unknown;
}> {}
export function createSourceHighlightAtomFamily(options?: {
readonly highlight?: SourceHighlighter;
readonly idleTtlMs?: number;
}) {
const highlight = options?.highlight ?? highlightSourceFile;
const idleTtlMs = options?.idleTtlMs ?? SOURCE_HIGHLIGHT_IDLE_TTL_MS;
const family = Atom.family((request: SourceHighlightCacheKey) =>
Atom.make(
Effect.tryPromise({
try: () => highlight(request),
catch: (cause) => new SourceHighlightError({ cause }),
}),
).pipe(
Atom.setIdleTTL(idleTtlMs),
Atom.withLabel(`mobile:source-highlight:${request.theme}:${request.path}`),
),
);
return (input: SourceHighlightInput) => family(new SourceHighlightCacheKey(input));
}
export const sourceHighlightAtom = createSourceHighlightAtomFamily();
@@ -1,64 +0,0 @@
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { describe, expect, it, vi } from "vite-plus/test";
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
describe("workspaceFileImageAtom", () => {
it("reuses a prefetched image across route remounts", async () => {
const prefetch = vi.fn(async () => true);
const imageAtom = createWorkspaceFileImageAtomFamily({ idleTtlMs: 1_000, prefetch });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const first = imageAtom("https://example.test/image.png");
const firstUnmount = registry.mount(first);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
});
firstUnmount();
const remounted = imageAtom("https://example.test/image.png");
const secondUnmount = registry.mount(remounted);
expect(remounted).toBe(first);
expect(AsyncResult.isSuccess(registry.get(remounted))).toBe(true);
expect(prefetch).toHaveBeenCalledTimes(1);
secondUnmount();
registry.dispose();
});
it("prefetches different asset URLs independently", async () => {
const prefetch = vi.fn(async () => true);
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch });
const registry = AtomRegistry.make();
const first = imageAtom("https://example.test/first.png");
const second = imageAtom("https://example.test/second.png");
const firstUnmount = registry.mount(first);
const secondUnmount = registry.mount(second);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
expect(AsyncResult.isSuccess(registry.get(second))).toBe(true);
});
expect(prefetch).toHaveBeenCalledTimes(2);
firstUnmount();
secondUnmount();
registry.dispose();
});
it("exposes prefetch failures", async () => {
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
const registry = AtomRegistry.make();
const atom = imageAtom("https://example.test/missing.png");
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
unmount();
registry.dispose();
});
});
@@ -1,48 +0,0 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
type ImagePrefetch = (uri: string) => Promise<boolean>;
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
readonly cause?: unknown;
readonly uri: string;
}> {}
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
const { Image } = await import("react-native");
return Image.prefetch(uri);
}
export function createWorkspaceFileImageAtomFamily(options?: {
readonly idleTtlMs?: number;
readonly prefetch?: ImagePrefetch;
}) {
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
const family = Atom.family((key: WorkspaceImageCacheKey) =>
Atom.make(
Effect.tryPromise({
try: async () => {
const cached = await prefetch(key.uri);
if (!cached) {
throw new WorkspaceImagePrefetchError({ uri: key.uri });
}
return key.uri;
},
catch: (cause) =>
cause instanceof WorkspaceImagePrefetchError
? cause
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
}),
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
);
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
}
export const workspaceFileImageAtom = createWorkspaceFileImageAtomFamily();
@@ -1,31 +0,0 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceFilePath } from "./filePath";
export function useWorkspaceFileAssetUrl(props: {
readonly cwd: string | null;
readonly environmentId: EnvironmentId | null;
readonly relativePath: string | null;
readonly threadId: ThreadId | null;
}) {
const absolutePath = useMemo(
() =>
props.cwd !== null && props.relativePath !== null
? resolveWorkspaceFilePath(props.cwd, props.relativePath)
: null,
[props.cwd, props.relativePath],
);
return useAssetUrl(
props.environmentId,
absolutePath !== null && props.threadId !== null
? {
_tag: "workspace-file",
threadId: props.threadId,
path: absolutePath,
}
: null,
);
}
@@ -1,244 +0,0 @@
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 { Stack } from "expo-router";
import { Text as RNText, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import type { HomeProjectSortOrder } from "./homeThreadList";
export interface HomeHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const THREAD_SORT_OPTIONS: ReadonlyArray<{
readonly value: SidebarThreadSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
readonly value: SidebarProjectGroupingMode;
readonly label: string;
readonly subtitle: string;
}> = [
{
value: "repository",
label: "Group by repository",
subtitle: "Combine matching repositories across environments",
},
{
value: "repository_path",
label: "Group by repository path",
subtitle: "Combine only matching paths within a repository",
},
{
value: "separate",
label: "Keep separate",
subtitle: "Show every project path separately",
},
];
export function HomeHeader(props: {
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const hasCustomListOptions =
props.selectedEnvironmentId !== null ||
props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER ||
props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE;
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
allowToolbarIntegration: true,
},
}}
/>
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View
style={{
width: 128,
height: 32,
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.Menu
accessibilityLabel="Filter and sort threads"
icon={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Thread list options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
subtitle="Show threads from every environment"
>
<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 projects">
<Stack.Toolbar.Label>Sort projects</Stack.Toolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Sort threads">
<Stack.Toolbar.Label>Sort threads</Stack.Toolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Group projects">
<Stack.Toolbar.Label>Group projects</Stack.Toolbar.Label>
{PROJECT_GROUPING_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectGroupingMode === option.value}
onPress={() => props.onProjectGroupingModeChange(option.value)}
subtitle={option.subtitle}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
<Stack.Toolbar.Button
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
separateBackground
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={props.onStartNewTask}
separateBackground
/>
</Stack.Toolbar>
</>
);
}
+146 -294
View File
@@ -2,26 +2,12 @@ import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Easing,
LinearTransition,
type ExitAnimationsValues,
withDelay,
withTiming,
} from "react-native-reanimated";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
@@ -29,14 +15,9 @@ import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "./thread-swipe-actions";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -46,17 +27,26 @@ interface HomeScreenProps {
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
}
interface ProjectGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
const projectGroupActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
}),
(group: ProjectGroup) => ({
activityAt: new Date(group.threads[0]!.updatedAt ?? group.threads[0]!.createdAt).getTime(),
}),
);
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
@@ -75,33 +65,6 @@ function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string
}
const COLLAPSED_THREAD_LIMIT = 6;
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
function threadRowExit(values: ExitAnimationsValues) {
"worklet";
return {
initialValues: {
height: values.currentHeight,
opacity: 1,
originX: values.currentOriginX,
},
animations: {
height: withDelay(
90,
withTiming(0, {
duration: 170,
easing: Easing.inOut(Easing.cubic),
}),
),
opacity: withDelay(80, withTiming(0, { duration: 100 })),
originX: withTiming(values.currentOriginX - values.windowWidth, {
duration: 190,
easing: Easing.out(Easing.cubic),
}),
},
};
}
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -170,7 +133,6 @@ function deriveEmptyState(props: {
function ProjectGroupLabel(props: {
readonly project: EnvironmentProject;
readonly title: string;
readonly totalThreadCount: number;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
@@ -190,7 +152,7 @@ function ProjectGroupLabel(props: {
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
{props.title}
{props.project.title}
</Text>
{hiddenCount > 0 ? (
@@ -213,172 +175,95 @@ function ThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
readonly onArchive: () => void;
readonly onDelete: () => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly isLast: boolean;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const cardColor = useThemeColor("--color-card");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, 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;
}, []);
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: `Archive ${props.thread.title}`,
icon: "archivebox",
label: "Archive",
onPress: props.onArchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
>
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={props.thread.title}
accessibilityRole="button"
className="bg-card"
onPress={() => {
swipeableRef.current?.close();
props.onPress();
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
{/* Git status indicator */}
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
<View style={{ flex: 1, gap: 3 }}>
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text
className="text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
</Pressable>
</ReanimatedSwipeable>
{/* Content */}
<View style={{ flex: 1, gap: 3 }}>
{/* Title + Status + Timestamp */}
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
{/* Environment + branch */}
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text
className="text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
</Pressable>
);
}
@@ -438,7 +323,6 @@ function StaleCatalogStatusPill(props: {
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
@@ -451,50 +335,51 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, []);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
openSwipeableRef.current?.close();
openSwipeableRef.current = methods;
/* Build project title lookup for search */
const projectTitleByKey = useMemo(() => {
const map = new Map<string, string>();
for (const p of props.projects) {
map.set(scopedProjectKey(p.environmentId, p.id), p.title);
}
}, []);
return map;
}, [props.projects]);
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current === methods) {
openSwipeableRef.current = null;
/* Filter threads by search query */
const filteredThreads = useMemo(() => {
const q = props.searchQuery.trim().toLowerCase();
if (!q) return props.threads;
return props.threads.filter((t) => {
if (t.title.toLowerCase().includes(q)) return true;
const key = scopedProjectKey(t.environmentId, t.projectId);
return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
});
}, [props.threads, props.searchQuery, projectTitleByKey]);
/* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, EnvironmentThreadShell[]>();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
if (existing) existing.push(thread);
else byProject.set(key, [thread]);
}
}, []);
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
threadSortOrder: props.threadSortOrder,
projectGroupingMode: props.projectGroupingMode,
}),
[
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
props.threads,
],
);
const groups: ProjectGroup[] = [];
for (const project of props.projects) {
const key = scopedProjectKey(project.environmentId, project.id);
const threads = byProject.get(key);
if (threads && threads.length > 0) {
groups.push({ key, project, threads });
}
}
return Arr.sort(groups, projectGroupActivityOrder);
}, [props.projects, filteredThreads]);
/* Empty states */
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const hasSearchQuery = props.searchQuery.trim().length > 0;
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
const shouldShowConnectionStatus =
props.catalogState.networkStatus === "offline" ||
props.catalogState.hasConnectingEnvironment ||
@@ -511,7 +396,6 @@ export function HomeScreen(props: HomeScreenProps) {
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
className="flex-1"
contentContainerStyle={{
paddingHorizontal: 16,
@@ -534,18 +418,8 @@ export function HomeScreen(props: HomeScreenProps) {
</View>
) : null}
</View>
) : !hasResults && hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : !hasResults && selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : !hasResults ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session."
/>
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
@@ -554,52 +428,30 @@ export function HomeScreen(props: HomeScreenProps) {
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<Animated.View
key={group.key}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<View key={group.key}>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
project={group.representative}
title={group.title}
totalThreadCount={group.threads.length}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => {
const threadKey = `${thread.environmentId}:${thread.id}`;
return (
<Animated.View
key={threadKey}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ThreadRow
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
null
}
isLast={i === visibleThreads.length - 1}
onArchive={() => props.onArchiveThread(thread)}
onDelete={() => props.onDeleteThread(thread)}
onPress={() => props.onSelectThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
</Animated.View>
);
})}
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
</View>
</Animated.View>
</View>
);
})
)}
@@ -1,223 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildHomeThreadGroups } from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
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<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
): EnvironmentThreadShell {
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: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
overrides: Partial<Parameters<typeof buildHomeThreadGroups>[0]> = {},
) {
return buildHomeThreadGroups({
projects,
threads,
environmentId: null,
searchQuery: "",
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
...overrides,
});
}
describe("buildHomeThreadGroups", () => {
it("sorts the newest thread first regardless of snapshot order", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("thread-old"),
projectId: project.id,
title: "Older thread",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("thread-new"),
projectId: project.id,
title: "Newer thread",
updatedAt: "2026-06-03T00:00:00.000Z",
}),
];
expect(buildGroups([project], threads)[0]?.threads.map((thread) => thread.id)).toEqual([
"thread-new",
"thread-old",
]);
});
it("supports independent project and thread creation-time sorting", () => {
const environmentId = EnvironmentId.make("environment-1");
const olderProject = makeProject({
environmentId,
id: ProjectId.make("project-older"),
title: "Older project",
});
const newerProject = makeProject({
environmentId,
id: ProjectId.make("project-newer"),
title: "Newer project",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("old-created"),
projectId: olderProject.id,
title: "Updated recently",
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-05T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("new-created"),
projectId: olderProject.id,
title: "Created recently",
createdAt: "2026-06-04T00:00:00.000Z",
updatedAt: "2026-06-04T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("newest-project-thread"),
projectId: newerProject.id,
title: "Newest project",
createdAt: "2026-06-06T00:00:00.000Z",
}),
];
const groups = buildGroups([olderProject, newerProject], threads, {
projectSortOrder: "created_at",
threadSortOrder: "created_at",
projectGroupingMode: "separate",
});
expect(groups.map((group) => group.representative.id)).toEqual([
"project-newer",
"project-older",
]);
expect(groups[1]?.threads.map((thread) => thread.id)).toEqual(["new-created", "old-created"]);
});
it("filters both projects and threads to one environment", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-local"),
title: "Local",
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote"),
title: "Remote",
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId: project.environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
const groups = buildGroups(projects, threads, { environmentId: remoteEnvironmentId });
expect(groups).toHaveLength(1);
expect(groups[0]?.representative.environmentId).toBe(remoteEnvironmentId);
expect(groups[0]?.threads.map((thread) => thread.environmentId)).toEqual([remoteEnvironmentId]);
});
it("matches web repository, repository-path, and separate grouping modes", () => {
const environmentId = EnvironmentId.make("environment-1");
const repositoryIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
rootPath: "/workspaces/t3code",
};
const projects = [
makeProject({
environmentId,
id: ProjectId.make("project-web"),
title: "Web",
workspaceRoot: "/workspaces/t3code/apps/web",
repositoryIdentity,
}),
makeProject({
environmentId,
id: ProjectId.make("project-mobile"),
title: "Mobile",
workspaceRoot: "/workspaces/t3code/apps/mobile",
repositoryIdentity,
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
});
@@ -1,140 +0,0 @@
import {
deriveLogicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
return group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}): ReadonlyArray<HomeThreadGroup> {
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const project of input.projects) {
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
continue;
}
const groupKey = deriveLogicalProjectKey(project, {
groupingMode: input.projectGroupingMode,
});
const physicalKey = scopedProjectKey(project.environmentId, project.id);
groupKeyByProjectKey.set(physicalKey, groupKey);
const existing = groups.get(groupKey);
if (existing) {
existing.projects.push(project);
} else {
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
}
}
for (const thread of input.threads) {
if (thread.archivedAt !== null) {
continue;
}
if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
continue;
}
const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
const groupKey = groupKeyByProjectKey.get(physicalKey);
if (!groupKey) {
continue;
}
groups.get(groupKey)?.threads.push(thread);
}
const query = input.searchQuery.trim().toLocaleLowerCase();
const result: HomeThreadGroup[] = [];
for (const group of groups.values()) {
const representative = group.projects[0];
if (!representative || group.threads.length === 0) {
continue;
}
const title =
group.projects.length > 1
? deriveProjectGroupLabel({ representative, members: group.projects })
: representative.title;
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
if (matchingThreads.length === 0) {
continue;
}
result.push({
key: group.key,
title,
representative,
projects: group.projects,
threads: sortThreads(matchingThreads, input.threadSortOrder),
});
}
return Arr.sort(
result,
Order.mapInput(
Order.Struct({
timestamp: Order.flip(Order.Number),
title: Order.String,
key: Order.String,
}),
(group: HomeThreadGroup) => ({
timestamp: groupSortTimestamp(group, input.projectSortOrder),
title: group.title,
key: group.key,
}),
),
);
}
@@ -1,238 +0,0 @@
import { SymbolView } from "expo-symbols";
import type { ComponentProps } from "react";
import type { ColorValue } from "react-native";
import { Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Extrapolation,
interpolate,
runOnJS,
type SharedValue,
useAnimatedReaction,
useAnimatedStyle,
} from "react-native-reanimated";
import { AppText as Text } from "../../components/AppText";
const ACTION_ITEM_WIDTH = 50;
const ACTION_CIRCLE_SIZE = 36;
const ACTION_ICON_SIZE = 15;
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
export const THREAD_SWIPE_SPRING = {
damping: 26,
mass: 0.7,
overshootClamping: true,
stiffness: 330,
};
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly backgroundColor: string;
readonly entryRange: readonly [number, number];
readonly fullSwipeThreshold: number;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue<number>;
}) {
const actionStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
const fullSwipeProgress = interpolate(
reveal,
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
return {
opacity: props.stretchesOnFullSwipe ? entryProgress : entryProgress * (1 - fullSwipeProgress),
transform: [
{
translateX:
interpolate(entryProgress, [0, 1], [22, 0]) -
(props.stretchesOnFullSwipe ? 0 : stretch),
},
{ scale: interpolate(entryProgress, [0, 1], [0.78, 1]) },
],
};
});
const circleStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
return {
transform: [{ translateX: -stretch }],
width: ACTION_CIRCLE_SIZE + stretch,
};
});
const iconStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
const armedProgress = interpolate(
reveal,
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
return {
transform: [{ translateX: -stretch * (0.5 + armedProgress * 0.5) }],
};
});
const labelStyle = useAnimatedStyle(() => {
if (!props.stretchesOnFullSwipe) {
return { opacity: 1 };
}
const reveal = Math.max(-props.translation.value, 0);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
return {
opacity: interpolate(
reveal,
[props.fullSwipeThreshold - 24, props.fullSwipeThreshold],
[1, 0],
Extrapolation.CLAMP,
),
transform: [{ translateX: -stretch * 0.5 }],
};
});
return (
<Animated.View
style={[
{
alignItems: "center",
height: "100%",
justifyContent: "center",
width: ACTION_ITEM_WIDTH,
zIndex: props.stretchesOnFullSwipe ? 2 : 1,
},
actionStyle,
]}
>
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.onPress}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: ACTION_CIRCLE_SIZE,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: ACTION_CIRCLE_SIZE,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: ACTION_CIRCLE_SIZE,
},
iconStyle,
]}
>
<SymbolView
name={props.icon}
size={ACTION_ICON_SIZE}
tintColor="#ffffff"
type="monochrome"
/>
</Animated.View>
</View>
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
<Text className="text-[10px] font-t3-medium text-foreground-muted">{props.label}</Text>
</Animated.View>
</Pressable>
</Animated.View>
);
}
export function ThreadSwipeActions(props: {
readonly backgroundColor: ColorValue;
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
};
readonly swipeableMethods: SwipeableMethods;
readonly threadTitle: string;
readonly translation: SharedValue<number>;
}) {
useAnimatedReaction(
() => -props.translation.value >= props.fullSwipeThreshold,
(armed, previous) => {
if (armed !== previous) {
runOnJS(props.onFullSwipeArmedChange)(armed);
}
},
[props.fullSwipeThreshold, props.onFullSwipeArmedChange],
);
return (
<View
style={{
backgroundColor: props.backgroundColor,
flexDirection: "row",
height: "100%",
width: THREAD_SWIPE_ACTIONS_WIDTH,
}}
>
<SwipeActionButton
accessibilityLabel={props.primaryAction.accessibilityLabel}
backgroundColor="#007aff"
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={props.primaryAction.icon}
label={props.primaryAction.label}
onPress={props.primaryAction.onPress}
stretchesOnFullSwipe={false}
translation={props.translation}
/>
<SwipeActionButton
accessibilityLabel={`Delete ${props.threadTitle}`}
backgroundColor="#ff2d55"
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon="trash"
label="Delete"
onPress={() => {
props.swipeableMethods.close();
props.onDelete();
}}
stretchesOnFullSwipe
translation={props.translation}
/>
</View>
);
}
@@ -1,142 +0,0 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
import { Alert } from "react-native";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
type ThreadListAction = "archive" | "unarchive" | "delete";
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
const verb =
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
return `The thread could not be ${verb}.`;
}
function selectionHaptic(): void {
if (process.env.EXPO_OS === "ios") {
void Haptics.selectionAsync();
}
}
function actionFailureTitle(action: ThreadListAction): string {
if (action === "archive") return "Could not archive thread";
if (action === "unarchive") return "Could not unarchive thread";
return "Could not delete thread";
}
function useThreadActionExecutor(
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
) {
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
const inFlightThreadKeys = useRef(new Set<string>());
const executeAction = useCallback(
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (inFlightThreadKeys.current.has(key)) {
return;
}
inFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const mutation =
action === "archive"
? archiveMutation
: action === "unarchive"
? unarchiveMutation
: deleteMutation;
const result = await mutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
return;
}
onCompleted?.(action, thread);
} finally {
inFlightThreadKeys.current.delete(key);
}
},
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
);
return executeAction;
}
function useConfirmDeleteThread(
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
) {
return useCallback(
(thread: EnvironmentThreadShell) => {
Alert.alert(
"Delete thread?",
`“${thread.title}” will be permanently deleted, including its terminal history.`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => {
void executeAction("delete", thread);
},
},
],
);
},
[executeAction],
);
}
export function useThreadListActions(): {
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
} {
const executeAction = useThreadActionExecutor();
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
void executeAction("archive", thread);
},
[executeAction],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { archiveThread, confirmDeleteThread };
}
export function useArchivedThreadListActions(
onCompleted: (thread: EnvironmentThreadShell) => void,
): {
readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
} {
const handleCompleted = useCallback(
(_action: ThreadListAction, thread: EnvironmentThreadShell) => {
onCompleted(thread);
},
[onCompleted],
);
const executeAction = useThreadActionExecutor(handleCompleted);
const unarchiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
void executeAction("unarchive", thread);
},
[executeAction],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { unarchiveThread, confirmDeleteThread };
}
@@ -695,15 +695,6 @@ export async function highlightCodeSnippet(input: {
return highlightLines(input.code, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
}
export async function highlightSourceFile(input: {
readonly path: string;
readonly contents: string;
readonly theme: ReviewDiffTheme;
}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
const language = await resolveLanguageFromPath(input.path);
return highlightLines(input.contents, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
}
async function highlightPatchLinesInChunks(input: {
readonly lines: ReadonlyArray<string>;
readonly language: string;
@@ -62,7 +62,6 @@ export interface ThreadDetailScreenProps {
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: LayoutVariant;
@@ -310,7 +309,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
+194 -109
View File
@@ -4,7 +4,6 @@ import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Markdown,
@@ -55,7 +54,6 @@ import {
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import type { LayoutVariant } from "../../lib/layout";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
@@ -66,9 +64,7 @@ import {
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -87,7 +83,6 @@ function formatMessageTime(input: string): string {
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
@@ -125,6 +120,32 @@ function MessageAttachmentImage(props: {
);
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
return (match?.[1] ?? trimmed).trim();
}
function compactActivityDetail(detail: string | null): string | null {
if (!detail) {
return null;
}
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : null;
}
function buildActivityRows(
activities: Extract<ThreadFeedEntry, { type: "activity-group" }>["activities"],
) {
return activities.map((activity) => ({
...activity,
detail: compactActivityDetail(activity.detail),
}));
}
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const MARKDOWN_COLORS = {
light: {
body: "#111111",
@@ -134,12 +155,10 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(0, 0, 0, 0.02)",
codeBackground: "rgba(0, 0, 0, 0.04)",
codeText: "#262626",
inlineCodeText: "#5f6368",
horizontalRule: "rgba(0, 0, 0, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.22)",
userCodeText: "#ffffff",
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.16)",
userFenceText: "#ffffff",
},
@@ -151,12 +170,10 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(255, 255, 255, 0.03)",
codeBackground: "rgba(255, 255, 255, 0.06)",
codeText: "#e5e5e5",
inlineCodeText: "#b8bcc2",
horizontalRule: "rgba(255, 255, 255, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.18)",
userCodeText: "#ffffff",
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.28)",
userFenceText: "#ffffff",
},
@@ -185,18 +202,27 @@ interface ReviewCommentColors {
const failedMarkdownFaviconHosts = new Set<string>();
const markdownLinkStyles = StyleSheet.create({
inlineIcon: {
favicon: {
width: 14,
height: 14,
borderRadius: 3,
marginHorizontal: 3,
transform: [{ translateY: 2 }],
},
favicon: {
borderRadius: 3,
},
file: {
fontFamily: "DMSans_700Bold",
fontWeight: "700",
borderRadius: 5,
borderWidth: StyleSheet.hairlineWidth,
fontFamily: "DMSans_500Medium",
fontSize: 13,
lineHeight: 20,
paddingHorizontal: 6,
paddingVertical: 2,
},
fileIcon: {
width: 15,
height: 15,
marginRight: 4,
transform: [{ translateY: 2 }],
},
});
@@ -224,7 +250,7 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
source={{
uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,
}}
style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}
style={markdownLinkStyles.favicon}
onError={() => {
failedMarkdownFaviconHosts.add(props.host);
setFailed(true);
@@ -261,9 +287,11 @@ function useReviewCommentColors(): ReviewCommentColors {
);
}
function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {
function useMarkdownStyles(): MarkdownStyleSets {
const colorScheme = useColorScheme();
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
const inlineChipBackground = String(useThemeColor("--color-subtle"));
const inlineSkillBackground = String(useThemeColor("--color-inline-skill-background"));
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
return useMemo(() => {
@@ -274,12 +302,10 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
const markdownBlockquoteBorder = colors.blockquoteBorder;
const markdownCodeBg = colors.codeBackground;
const markdownCodeText = colors.codeText;
const markdownInlineCodeText = colors.inlineCodeText;
const markdownHrColor = colors.horizontalRule;
const markdownUserBodyColor = colors.userBody;
const markdownUserCodeBg = colors.userCodeBackground;
const markdownUserCodeText = colors.userCodeText;
const markdownUserInlineCodeText = colors.userInlineCodeText;
const markdownUserFenceBg = colors.userFenceBackground;
const markdownUserFenceText = colors.userFenceText;
@@ -368,23 +394,28 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
};
const createMarkdownRenderers = (
inlineBackgroundColor: string,
inlineTextColor: string,
inlineCodeTextColor: string,
blockBackgroundColor: string,
blockTextColor: string,
preserveSoftBreaks: boolean,
): CustomRenderers => ({
link: ({ children, href = "" }) => {
const presentation = resolveMarkdownLinkPresentation(href);
if (presentation.kind === "file") {
return (
<NativeText
onPress={() => onLinkPress(href)}
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
style={[
markdownLinkStyles.file,
{
backgroundColor: inlineBackgroundColor,
borderColor: markdownHrColor,
color: inlineTextColor,
},
]}
>
<Image
source={markdownFileIconSource(presentation.icon)}
style={markdownLinkStyles.inlineIcon}
style={markdownLinkStyles.fileIcon}
/>
{presentation.label}
</NativeText>
@@ -461,24 +492,28 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
),
code_inline: ({ content }) => {
const value = content ?? "";
const wrapsPoorly =
value.length > 24 || value.includes("/") || value.includes("\\") || value.includes(":");
return (
<NativeText
style={{
color: inlineCodeTextColor,
color: inlineTextColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 22,
lineHeight: 18,
...(wrapsPoorly
? { opacity: 0.82 }
: {
backgroundColor: inlineBackgroundColor,
borderRadius: 4,
paddingHorizontal: 3,
}),
}}
>
{value}
</NativeText>
);
},
...(preserveSoftBreaks
? {
soft_break: () => <NativeText>{"\n"}</NativeText>,
}
: {}),
code_block: ({ content, language }) => (
<View
style={{
@@ -584,23 +619,23 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
theme: userTheme,
styles: userStyles,
renderers: createMarkdownRenderers(
markdownUserCodeBg,
markdownUserCodeText,
markdownUserInlineCodeText,
markdownUserFenceBg,
markdownUserFenceText,
true,
),
nativeTextStyle: {
color: markdownUserBodyColor,
strongColor: markdownUserBodyColor,
mutedColor: markdownUserBodyColor,
linkColor: markdownUserBodyColor,
inlineCodeColor: markdownUserInlineCodeText,
codeColor: markdownUserCodeText,
codeBackgroundColor: markdownUserCodeBg,
codeBlockBackgroundColor: markdownUserFenceBg,
fileBackgroundColor: "rgba(255, 255, 255, 0.12)",
fileTextColor: "#ffffff",
skillTextColor: "#f0abfc",
skillBackgroundColor: "rgba(217, 70, 239, 0.24)",
skillTextColor: "#ffffff",
quoteMarkerColor: markdownUserBodyColor,
dividerColor: markdownUserBodyColor,
fontSize: 15,
@@ -614,22 +649,22 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
theme: assistantTheme,
styles: assistantStyles,
renderers: createMarkdownRenderers(
markdownCodeText,
markdownInlineCodeText,
markdownCodeBg,
markdownCodeText,
false,
markdownCodeBg,
markdownCodeText,
),
nativeTextStyle: {
color: markdownBodyColor,
strongColor: markdownStrongColor,
mutedColor: markdownBodyColor,
linkColor: markdownLinkColor,
inlineCodeColor: markdownInlineCodeText,
codeColor: markdownCodeText,
codeBackgroundColor: markdownCodeBg,
codeBlockBackgroundColor: markdownCodeBg,
fileBackgroundColor: inlineChipBackground,
fileTextColor: markdownCodeText,
skillBackgroundColor: inlineSkillBackground,
skillTextColor: inlineSkillForeground,
quoteMarkerColor: markdownBlockquoteBorder,
dividerColor: markdownHrColor,
@@ -641,7 +676,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
},
},
};
}, [colors, inlineSkillForeground, onLinkPress]);
}, [colors, inlineChipBackground, inlineSkillBackground, inlineSkillForeground]);
}
function renderFeedEntry(
@@ -657,13 +692,11 @@ function renderFeedEntry(
readonly onToggleWorkRow: (rowId: string) => void;
readonly onToggleTurnFold: (turnId: TurnId) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
readonly onMarkdownLinkPress: (href: string) => void;
readonly iconSubtleColor: string | import("react-native").ColorValue;
readonly userBubbleColor: string | import("react-native").ColorValue;
readonly markdownStyles: MarkdownStyleSets;
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
},
) {
const entry = info.item;
@@ -712,10 +745,9 @@ function renderFeedEntry(
return (
<View className="mb-5 items-end">
<View
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
className="max-w-[85%] gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
backgroundColor: userBubbleColor,
maxWidth: props.userBubbleMaxWidth,
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
}}
>
@@ -725,7 +757,6 @@ function renderFeedEntry(
markdownStyles={styles}
reviewCommentColors={props.reviewCommentColors}
skills={props.skills}
onLinkPress={props.onMarkdownLinkPress}
/>
) : null}
{attachments.map((attachment) => {
@@ -772,7 +803,6 @@ function renderFeedEntry(
markdown={message.text}
skills={props.skills}
textStyle={styles.nativeTextStyle}
onLinkPress={props.onMarkdownLinkPress}
/>
) : (
<Markdown
@@ -838,17 +868,123 @@ function renderFeedEntry(
);
}
const rows = buildActivityRows(entry.activities).filter(
(activity) => !(activity.toolLike && activity.status === "neutral"),
);
if (rows.length === 0) {
return null;
}
const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
const headerTitle = onlyToolRows
? rows.length === 1
? "1 tool call"
: `${rows.length} tool calls`
: "Work log";
return (
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={props.onToggleWorkRow}
/>
<View className="mb-3 rounded-[16px] border border-neutral-300/70 bg-background px-2 py-2.5 dark:border-white/[0.1] dark:bg-white/[0.035]">
<View className="mb-1.5 flex-row items-center justify-between gap-3 px-2">
<Text className="font-t3-medium text-xs text-foreground">{headerTitle}</Text>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: isExpanded }}
onPress={() => props.onToggleWorkGroup(entry.id)}
className="flex-row items-center gap-1"
>
<Text className="font-t3-medium text-xs text-foreground-muted">
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</Text>
<SymbolView
name={isExpanded ? "chevron.up" : "chevron.down"}
size={12}
tintColor={iconSubtleColor}
type="monochrome"
/>
</Pressable>
) : null}
</View>
{visibleRows.map((row, index) => (
<Pressable
key={row.id}
accessibilityRole={row.fullDetail ? "button" : undefined}
accessibilityState={
row.fullDetail ? { expanded: props.expandedWorkRows[row.id] ?? false } : undefined
}
onPress={() => {
if (row.fullDetail) {
props.onToggleWorkRow(row.id);
}
}}
onLongPress={() => props.onCopyWorkRow(row.id, row.copyText)}
className={cn(
"rounded-lg px-2 py-1.5",
index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
)}
>
<View className="flex-row items-center gap-2">
<View className="w-4 items-center justify-center">
<SymbolView
name={
row.status === "failure"
? "xmark"
: row.status === "success"
? "checkmark"
: row.status === "neutral"
? "minus"
: "terminal"
}
size={row.status ? 11 : 13}
tintColor={row.status === "failure" ? "#e11d48" : iconSubtleColor}
type="monochrome"
/>
</View>
<Text
className="min-w-0 flex-1 text-[12px] leading-[18px] text-neutral-700 dark:text-neutral-300"
numberOfLines={props.expandedWorkRows[row.id] ? undefined : 1}
>
{row.detail ? `${row.summary} - ${row.detail}` : row.summary}
</Text>
{row.fullDetail ? (
<SymbolView
name={props.expandedWorkRows[row.id] ? "chevron.up" : "chevron.down"}
size={11}
tintColor={iconSubtleColor}
type="monochrome"
/>
) : null}
{props.copiedRowId === row.id ? (
<Text className="shrink-0 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
</View>
{row.fullDetail && props.expandedWorkRows[row.id] ? (
<ScrollView
horizontal
nestedScrollEnabled
directionalLockEnabled
showsHorizontalScrollIndicator
bounces={false}
className="mt-2 rounded-lg bg-neutral-100 dark:bg-black/20"
contentContainerStyle={{ paddingHorizontal: 10, paddingVertical: 8 }}
>
<Text
selectable
className="text-[11px] leading-[17px] text-neutral-600 dark:text-neutral-400"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
</ScrollView>
) : null}
</Pressable>
))}
</View>
);
}
@@ -857,7 +993,6 @@ function UserMessageContent(props: {
readonly markdownStyles: MarkdownStyleSet;
readonly reviewCommentColors: ReviewCommentColors;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly onLinkPress: (href: string) => void;
}) {
const segments = parseReviewCommentMessageSegments(props.text);
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
@@ -868,8 +1003,6 @@ function UserMessageContent(props: {
markdown={props.text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
preserveSoftBreaks
onLinkPress={props.onLinkPress}
/>
);
}
@@ -909,8 +1042,6 @@ function UserMessageContent(props: {
markdown={text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
preserveSoftBreaks
onLinkPress={props.onLinkPress}
/>
) : (
<Markdown
@@ -1123,7 +1254,6 @@ function ThreadFeedPlaceholder(props: {
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const router = useRouter();
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const scrollFrameRef = useRef<number | null>(null);
@@ -1153,7 +1283,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
const userBubbleMaxWidth = contentWidth * 0.85;
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
const insets = useSafeAreaInsets();
const topContentInset = props.contentTopInset ?? insets.top + 44;
@@ -1161,56 +1290,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
const onMarkdownLinkPress = useCallback(
(href: string) => {
const presentation = resolveMarkdownLinkPresentation(href);
if (presentation.kind === "file") {
const relativePath = resolveWorkspaceRelativeFilePath(
props.workspaceRoot,
presentation.path,
);
if (relativePath) {
void Haptics.selectionAsync();
router.push(
buildThreadFilesNavigation(
{ environmentId: props.environmentId, threadId: props.threadId },
relativePath,
presentation.line,
),
);
}
return;
}
if (presentation.href) {
void Linking.openURL(presentation.href);
}
},
[props.environmentId, props.threadId, props.workspaceRoot, router],
);
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
const markdownStyles = useMarkdownStyles();
const reviewCommentColors = useReviewCommentColors();
// LegendList does not invalidate visible rows when only the renderItem closure changes.
// Keep row-local interaction props in extraData so disclosures and copy feedback repaint.
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
reviewCommentColors,
userBubbleColor,
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
reviewCommentColors,
userBubbleColor,
],
[iconSubtleColor, markdownStyles, reviewCommentColors, userBubbleColor],
);
const presentedFeed = useMemo(
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
@@ -1401,13 +1490,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkRow,
onToggleTurnFold,
onPressImage,
onMarkdownLinkPress,
iconSubtleColor,
userBubbleColor,
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
skills: props.skills,
}),
[
@@ -1421,9 +1508,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
onCopyWorkRow,
onMarkdownLinkPress,
onPressImage,
onToggleTurnFold,
onToggleWorkGroup,
@@ -14,7 +14,7 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert, Linking } from "react-native";
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import { buildThreadReviewRoutePath } from "../../lib/routes";
import {
basename,
getTerminalStatusLabel,
@@ -69,7 +69,6 @@ export function ThreadGitControls(props: {
readonly gitStatus: VcsStatusResult | null;
readonly gitOperationLabel: string | null;
readonly canOpenTerminal: boolean;
readonly canOpenFiles: boolean;
readonly projectScripts: ReadonlyArray<ProjectScript>;
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
readonly onOpenTerminal: (terminalId?: string | null) => void;
@@ -260,14 +259,6 @@ export function ThreadGitControls(props: {
>
<Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="folder"
disabled={!props.canOpenFiles}
onPress={() => router.push(buildThreadFilesNavigation({ environmentId, threadId }))}
subtitle="Browse this workspace"
>
<Stack.Toolbar.Label>Files</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="ellipsis.circle"
onPress={() =>
@@ -420,7 +420,6 @@ export function ThreadRouteScreen() {
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
canOpenFiles={Boolean(selectedThreadProject?.workspaceRoot)}
projectScripts={selectedThreadProject?.scripts ?? []}
terminalSessions={terminalMenuSessions}
onOpenTerminal={handleOpenTerminal}
@@ -453,7 +452,6 @@ export function ThreadRouteScreen() {
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
@@ -1,261 +0,0 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: { type: LayoutAnimation.Types.easeInEaseOut },
delete: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
} as const;
function triggerDisclosureFeedback() {
LayoutAnimation.configureNext(WORK_LOG_LAYOUT_ANIMATION);
void Haptics.selectionAsync();
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
return (match?.[1] ?? trimmed).trim();
}
function compactActivityDetail(detail: string | null): string | null {
if (!detail) {
return null;
}
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : null;
}
function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
switch (icon) {
case "agent":
return "sparkles";
case "alert":
return "exclamationmark.triangle";
case "check":
return "checkmark";
case "command":
return "terminal";
case "edit":
return "square.and.pencil";
case "eye":
return "eye";
case "globe":
return "globe";
case "hammer":
return "hammer";
case "message":
return "bubble.left";
case "warning":
return "xmark";
case "wrench":
return "wrench";
case "zap":
return "bolt";
}
}
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const rows = props.activities
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
if (rows.length === 0) {
return null;
}
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows =
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
return (
<View className="-mx-1 mb-3 px-1 py-0.5">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-[11px] text-foreground-muted opacity-60">
work log
</Text>
) : null}
<View className="gap-px">
{visibleRows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
return (
<View key={row.id}>
<Pressable
accessibilityRole={canExpand ? "button" : undefined}
accessibilityLabel={displayText}
accessibilityHint={
canExpand
? "Double tap to show full details. Long press to copy."
: "Long press to copy."
}
accessibilityState={canExpand ? { expanded } : undefined}
hitSlop={4}
onPress={() => {
if (canExpand) {
triggerDisclosureFeedback();
props.onToggleRow(row.id);
}
}}
onLongPress={() => props.onCopyRow(row.id, row.copyText)}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="rounded-md px-0.5 py-0.5"
>
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={14}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
numberOfLines={1}
>
<Text
className={cn(
"font-t3-medium text-foreground",
iconIsDestructive && "text-rose-600 dark:text-rose-400",
)}
>
{row.summary}
</Text>
{row.detail ? (
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
) : null}
</Text>
<View className="shrink-0 flex-row items-center gap-px">
{props.copiedRowId === row.id ? (
<Text className="pr-1 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
<View className="h-4 w-4 items-center justify-center">
{canExpand ? (
<SymbolView
name={expanded ? "chevron.up" : "chevron.down"}
size={11}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
) : null}
</View>
<View className="h-4 w-4 items-center justify-center">
{row.status ? (
<SymbolView
name={
row.status === "failure"
? "xmark"
: row.status === "success"
? "checkmark"
: "minus"
}
size={11}
tintColor={row.status === "failure" ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
) : null}
</View>
</View>
</View>
</Pressable>
{expanded && row.fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-[11px] leading-[17px] text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
</ScrollView>
</View>
) : null}
</View>
);
})}
</View>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? "Show fewer tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
}
hitSlop={4}
onPress={() => {
triggerDisclosureFeedback();
props.onToggleGroup();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
>
<View className="h-5 w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={13}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? "Show fewer tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
</Text>
</Pressable>
) : null}
</View>
);
}
-21
View File
@@ -16,47 +16,26 @@ describe("resolveMarkdownLinkPresentation", () => {
resolveMarkdownLinkPresentation("file:///Users/julius/project/src/main.ts#L42C7"),
).toEqual({
kind: "file",
href: "file:///Users/julius/project/src/main.ts#L42C7",
icon: "typescript",
label: "main.ts:42:7",
path: "/Users/julius/project/src/main.ts",
line: 42,
column: 7,
});
});
it("recognizes relative source paths and bare filenames", () => {
expect(resolveMarkdownLinkPresentation("apps/mobile/src/index.ts:10")).toEqual({
kind: "file",
href: "apps/mobile/src/index.ts:10",
icon: "typescript",
label: "index.ts:10",
path: "apps/mobile/src/index.ts",
line: 10,
});
expect(resolveMarkdownLinkPresentation("AGENTS.md")).toEqual({
kind: "file",
href: "AGENTS.md",
icon: "agents",
label: "AGENTS.md",
path: "AGENTS.md",
});
expect(resolveMarkdownLinkPresentation("package.json")).toEqual({
kind: "file",
href: "package.json",
icon: "package",
label: "package.json",
path: "package.json",
});
});
it("extracts line fragments from relative file links", () => {
expect(resolveMarkdownLinkPresentation("src/main.ts#L18C2")).toMatchObject({
kind: "file",
path: "src/main.ts",
line: 18,
column: 2,
label: "main.ts:18:2",
});
});
+2 -22
View File
@@ -7,7 +7,6 @@ import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
nativeMarkdownWithPreservedSoftBreaks,
} from "@t3tools/mobile-markdown-text/markdown";
describe("nativeMarkdownTextRuns", () => {
@@ -55,11 +54,7 @@ describe("nativeMarkdownTextRuns", () => {
externalHost: "example.com",
},
{ text: " " },
{
text: "README.md:12",
href: "file:///repo/README.md#L12",
fileIcon: "readme",
},
{ text: "README.md:12", fileIcon: "readme" },
]);
});
@@ -78,21 +73,6 @@ describe("nativeMarkdownTextRuns", () => {
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: "first second\nthird" }]);
});
it("can preserve soft breaks for authored user messages", () => {
const node: MarkdownNode = {
type: "paragraph",
children: [
{ type: "text", content: "first" },
{ type: "soft_break" },
{ type: "text", content: "second" },
],
};
expect(nativeMarkdownTextRuns(nativeMarkdownWithPreservedSoftBreaks(node))).toEqual([
{ text: "first\nsecond" },
]);
});
it("normalizes common inline HTML and entities", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -150,7 +130,7 @@ describe("nativeMarkdownTextRuns", () => {
});
describe("nativeMarkdownDocumentRuns", () => {
it("decorates known skill references as selectable skill links", () => {
it("decorates known skill references as selectable skill chips", () => {
const node: MarkdownNode = {
type: "document",
children: [
-45
View File
@@ -1,45 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { buildThreadFilesNavigation, buildThreadFilesRoutePath } from "./routes";
const thread = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
};
describe("thread file routes", () => {
it("includes an optional source line in string routes", () => {
expect(buildThreadFilesRoutePath(thread, "src/main.ts", 42)).toBe(
"/threads/environment-1/thread-1/files/src/main.ts?line=42",
);
});
it("encodes each file path segment without encoding separators", () => {
expect(buildThreadFilesRoutePath(thread, "docs/My File#1.md")).toBe(
"/threads/environment-1/thread-1/files/docs/My%20File%231.md",
);
});
it("builds typed navigation params for a file and source line", () => {
expect(buildThreadFilesNavigation(thread, "src/main.ts", 42)).toEqual({
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
params: {
environmentId: "environment-1",
threadId: "thread-1",
path: ["src", "main.ts"],
line: "42",
},
});
});
it("targets the files index when no file path is provided", () => {
expect(buildThreadFilesNavigation(thread)).toEqual({
pathname: "/threads/[environmentId]/[threadId]/files",
params: {
environmentId: "environment-1",
threadId: "thread-1",
},
});
});
});
-53
View File
@@ -32,27 +32,6 @@ export function buildThreadReviewRoutePath(
return `${buildThreadRoutePath(input)}/review`;
}
export function buildThreadFilesRoutePath(
input: ThreadRouteInput | PlainThreadRouteInput,
relativePath?: string | null,
line?: number | null,
): string {
const basePath = `${buildThreadRoutePath(input)}/files`;
if (!relativePath) {
return basePath;
}
const pathSegments = relativePath.split("/").filter((segment) => segment.length > 0);
if (pathSegments.length === 0) {
return basePath;
}
const encodedPath = pathSegments.map(encodeURIComponent).join("/");
const lineParam =
Number.isFinite(line) && Number(line) > 0 ? `?line=${Math.floor(Number(line))}` : "";
return `${basePath}/${encodedPath}${lineParam}`;
}
export function buildThreadTerminalRoutePath(
input: ThreadRouteInput | PlainThreadRouteInput,
terminalId?: string | null,
@@ -92,38 +71,6 @@ export function buildThreadTerminalNavigation(
};
}
export function buildThreadFilesNavigation(
input: ThreadRouteInput | PlainThreadRouteInput,
relativePath?: string | null,
line?: number | null,
): Href {
const environmentId = String(input.environmentId);
const threadId = String("threadId" in input ? input.threadId : input.id);
const path = relativePath?.split("/").filter((segment) => segment.length > 0) ?? [];
if (path.length === 0) {
return {
pathname: "/threads/[environmentId]/[threadId]/files",
params: { environmentId, threadId },
};
}
const params: {
environmentId: string;
threadId: string;
path: string[];
line?: string;
} = { environmentId, threadId, path };
if (Number.isFinite(line) && Number(line) > 0) {
params.line = String(Math.floor(Number(line)));
}
return {
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
params,
};
}
export function dismissRoute(router: Router) {
if (router.canGoBack()) {
router.back();
+2 -53
View File
@@ -161,65 +161,14 @@ describe("buildThreadFeed", () => {
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
fullDetail: "/bin/zsh -lc 'bun run test'",
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
icon: "command",
fullDetail: null,
copyText: "Run tests\nbun run test",
toolLike: true,
status: "success",
},
]);
});
it("keeps MCP inputs available to expanded mobile work rows", () => {
const turnId = TurnId.make("turn-mcp");
const thread = makeThread({
id: ThreadId.make("thread-mcp"),
projectId: ProjectId.make("project-1"),
title: "Expandable MCP call",
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: "2026-04-01T00:00:03.000Z",
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("mcp-completed"),
kind: "tool.completed",
tone: "tool",
summary: "Call repository tool",
createdAt: "2026-04-01T00:00:02.000Z",
turnId,
payload: {
title: "Call repository tool",
itemType: "mcp_tool_call",
detail: "repository.search",
status: "completed",
data: {
item: {
server: "repository",
tool: "search",
arguments: { query: "work log" },
},
},
},
}),
],
});
const group = buildThreadFeed(thread, [], null)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities[0]?.icon).toBe("wrench");
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
expect(group.activities[0]?.fullDetail).toContain("repository.search");
});
it("folds settled turn work while leaving the terminal answer visible", () => {
const turnId = TurnId.make("turn-1");
const thread = makeThread({
+9 -72
View File
@@ -40,19 +40,6 @@ export interface ThreadFeedActivity {
readonly detail: string | null;
readonly fullDetail: string | null;
readonly copyText: string;
readonly icon:
| "agent"
| "alert"
| "check"
| "command"
| "edit"
| "eye"
| "globe"
| "hammer"
| "message"
| "warning"
| "wrench"
| "zap";
readonly toolLike: boolean;
readonly status: "success" | "failure" | "neutral" | null;
}
@@ -73,7 +60,6 @@ interface WorkLogEntry {
itemType?: ToolLifecycleItemType;
requestKind?: PendingApproval["requestKind"];
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
toolData?: unknown;
}
interface DerivedWorkLogEntry extends WorkLogEntry {
@@ -228,7 +214,7 @@ function resolvePendingUserInputAnswer(
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): DerivedWorkLogEntry[] {
): WorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
@@ -239,7 +225,9 @@ function deriveWorkLogEntries(
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries);
return collapseDerivedWorkLogEntries(entries).map(
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
);
}
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
@@ -313,12 +301,6 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (title) {
entry.toolTitle = title;
}
if (itemType === "mcp_tool_call") {
const data = asRecord(payload?.data);
if (data?.item !== undefined) {
entry.toolData = data.item;
}
}
if (itemType) {
entry.itemType = itemType;
}
@@ -383,7 +365,6 @@ function mergeDerivedWorkLogEntries(
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
const toolData = next.toolData ?? previous.toolData;
return {
...previous,
...next,
@@ -396,7 +377,6 @@ function mergeDerivedWorkLogEntries(
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
...(toolData !== undefined ? { toolData } : {}),
};
}
@@ -500,52 +480,6 @@ function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
return "neutral";
}
function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
if (
entry.activityKind === "user-input.requested" ||
entry.activityKind === "user-input.resolved"
) {
return "message";
}
if (entry.activityKind === "runtime.warning") return "warning";
if (entry.requestKind === "command") return "command";
if (entry.requestKind === "file-read") return "eye";
if (entry.requestKind === "file-change") return "edit";
if (entry.itemType === "command_execution" || entry.command) return "command";
if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
if (entry.itemType === "web_search") return "globe";
if (entry.itemType === "image_view") return "eye";
if (entry.itemType === "mcp_tool_call") return "wrench";
if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
return "hammer";
}
if (entry.tone === "error") return "alert";
if (entry.tone === "thinking") return "agent";
if (entry.tone === "info") return "check";
return "zap";
}
function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
const blocks: string[] = [];
const appendUniqueBlock = (value: string | null | undefined) => {
const trimmed = value?.trim();
if (trimmed && !blocks.includes(trimmed)) {
blocks.push(trimmed);
}
};
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
}
appendUniqueBlock(entry.rawCommand ?? entry.command);
appendUniqueBlock(entry.detail);
if ((entry.changedFiles?.length ?? 0) > 0) {
appendUniqueBlock(entry.changedFiles!.join("\n"));
}
return blocks.length > 0 ? blocks.join("\n\n") : null;
}
function workEntryPreview(
workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
): string | null {
@@ -1292,7 +1226,11 @@ export function buildThreadFeed(
.map<RawThreadFeedEntry>((entry) => {
const summary = workEntryHeading(entry);
const detail = workEntryPreview(entry);
const fullDetail = buildWorkEntryExpandedBody(entry);
const normalizedFullDetail = entry.detail
? unwrapKnownShellCommandWrapper(entry.detail)
: null;
const fullDetail =
normalizedFullDetail && normalizedFullDetail !== detail ? normalizedFullDetail : null;
return {
type: "activity",
id: entry.id,
@@ -1305,7 +1243,6 @@ export function buildThreadFeed(
summary,
detail,
fullDetail,
icon: workEntryIcon(entry),
copyText: [summary, detail, fullDetail]
.filter((value, index, values): value is string => {
return Boolean(value) && values.indexOf(value) === index;
@@ -89,42 +89,6 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact workspace URLs for image previews", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-image-workspace-",
});
const assetsDirectory = path.join(root, "assets");
const imagePath = path.join(assetsDirectory, "icon.png");
const siblingPath = path.join(assetsDirectory, "other.png");
yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
const result = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: imagePath,
},
workspaceRoot: root,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "icon.png")).toEqual({
kind: "file",
path: canonicalImagePath,
});
expect(yield* resolveAsset(token, "other.png")).toBeNull();
expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
+21 -45
View File
@@ -1,11 +1,5 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -30,14 +24,22 @@ export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
const PREVIEW_ASSET_EXTENSIONS = new Set([
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
...PREVIEWABLE_EXTENSIONS,
".avif",
".css",
".gif",
".ico",
".jpeg",
".jpg",
".js",
".mjs",
".otf",
".png",
".svg",
".ttf",
".webp",
".woff",
".woff2",
]);
@@ -50,13 +52,6 @@ const AssetClaimsSchema = Schema.Union([
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file-exact"),
workspaceRoot: Schema.String,
relativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
@@ -149,8 +144,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* failAccess("Only browser documents and images can be previewed.");
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
return yield* failAccess("Only HTML and PDF files can open in the browser.");
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
@@ -159,24 +154,15 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
}
const canonicalWorkspaceRoot = yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
? {
version: 1,
kind: "workspace-file-exact",
workspaceRoot: canonicalWorkspaceRoot,
relativePath: resolved.relativePath,
expiresAt,
}
: {
version: 1,
kind: "workspace-file",
workspaceRoot: canonicalWorkspaceRoot,
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
claims = {
version: 1,
kind: "workspace-file",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
fileName = path.basename(resolved.relativePath);
break;
}
@@ -282,16 +268,6 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return exactWorkspaceFile
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
: null;
}
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
+22 -23
View File
@@ -1,11 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
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 PlatformError from "effect/PlatformError";
@@ -146,13 +145,13 @@ const makeConcurrentCreateSecretStoreLayer = () =>
);
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
it.effect("returns Option.none when a secret file does not exist", () =>
it.effect("returns null when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const secret = yield* secretStore.get("missing-secret");
assert.isTrue(Option.isNone(secret));
expect(secret).toBeNull();
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -163,7 +162,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
assert.deepEqual(Array.from(second), Array.from(first));
expect(Array.from(second)).toEqual(Array.from(first));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -179,10 +178,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
{ concurrency: "unbounded" },
);
const persisted = yield* secretStore.get("session-signing-key");
const persistedBytes = Option.getOrThrow(persisted);
assert.deepEqual(Array.from(first), Array.from(persistedBytes));
assert.deepEqual(Array.from(second), Array.from(persistedBytes));
expect(persisted).not.toBeNull();
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);
@@ -218,10 +217,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
assert.isTrue(
chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets")),
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
true,
);
assert.isAtLeast(chmodCalls.filter((call) => call.mode === 0o600).length, 2);
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -231,10 +230,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to read secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to read secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
);
@@ -246,10 +245,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
);
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to persist secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to persist secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
);
@@ -259,10 +258,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to remove secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to remove secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
);
});
+41 -47
View File
@@ -1,23 +1,19 @@
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 FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { ServerConfig } from "../config.ts";
export class SecretStoreError extends Schema.TaggedErrorClass<SecretStoreError>()(
"SecretStoreError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const isPlatformError = (value: unknown): value is PlatformError.PlatformError =>
Predicate.isTagged(value, "PlatformError");
@@ -26,7 +22,7 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists";
export interface ServerSecretStoreShape {
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
@@ -61,10 +57,10 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
? Effect.succeed(null)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name}.`,
@@ -137,43 +133,41 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate random bytes for secret ${name}.`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
}),
),
)
: Effect.fail(error),
),
),
Effect.flatMap((existing) => {
if (existing) {
return Effect.succeed(existing);
}
return crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate random bytes for secret ${name}.`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
? Effect.succeed(created)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
),
)
: Effect.fail(error),
),
),
}),
),
),
);
}),
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
);
+3 -3
View File
@@ -385,9 +385,9 @@ const connectStatusCommand = Command.make("status", {
const status: CloudCliStatus = {
desired,
authenticated,
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
linked: cloudUserId !== null,
cloudUserId: cloudUserId ? bytesToString(cloudUserId) : null,
relayUrl: relayUrl ? bytesToString(relayUrl) : null,
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
+5 -6
View File
@@ -1,8 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
@@ -41,18 +40,18 @@ it.layer(NodeServices.layer)("CliState", (it) => {
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
assert.isFalse(yield* CliState.readCliDesiredCloudLink);
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
yield* CliState.setCliDesiredCloudLink(true);
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
expect(yield* CliState.readCliDesiredCloudLink).toBe(true);
for (const name of persistedCloudLinkSecrets) {
yield* secrets.set(name, new TextEncoder().encode(name));
}
yield* CliState.clearPersistedCloudLink;
assert.isFalse(yield* CliState.readCliDesiredCloudLink);
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
for (const name of persistedCloudLinkSecrets) {
assert.isTrue(Option.isNone(yield* secrets.get(name)));
expect(yield* secrets.get(name)).toBe(null);
}
}).pipe(Effect.provide(makeTestLayer())),
);
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff. Show more