Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5350fea938 |
No files matched your search
@@ -60,6 +60,52 @@ jobs:
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
test_browser:
|
||||
name: Test Browser
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: vp run --filter @t3tools/web test:browser:install
|
||||
|
||||
- name: Browser test / Chat view
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
|
||||
|
||||
- name: Browser test / Chat markdown
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
|
||||
|
||||
- name: Browser test / Components
|
||||
working-directory: apps/web
|
||||
run: |
|
||||
vp test run --mode browser --browser=chromium \
|
||||
src/components/GitActionsControl.browser.tsx \
|
||||
src/components/KeybindingsToast.browser.tsx \
|
||||
src/components/ThreadTerminalDrawer.browser.tsx \
|
||||
src/components/chat/MessagesTimeline.browser.tsx \
|
||||
src/components/chat/ProviderModelPicker.browser.tsx \
|
||||
src/components/chat/CompactComposerControlsMenu.browser.tsx \
|
||||
src/components/settings/SettingsPanels.browser.tsx
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -1,297 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
|
||||
decryptString: (value) => {
|
||||
return Effect.gen(function* () {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (
|
||||
!decoded.startsWith("encrypted:") ||
|
||||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
|
||||
) {
|
||||
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted catalog"),
|
||||
});
|
||||
}
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
baseDir: string,
|
||||
encryptionAvailable = true,
|
||||
failDecrypt: Ref.Ref<boolean> | null = null,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
);
|
||||
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
|
||||
return DesktopConnectionCatalogStore.layer.pipe(
|
||||
Layer.provideMerge(savedEnvironmentsLayer),
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
}
|
||||
|
||||
const withStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
|
||||
encryptionAvailable = true,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalog = '{"schemaVersion":1,"targets":[]}';
|
||||
|
||||
assert.isTrue(yield* store.set(catalog));
|
||||
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
|
||||
|
||||
yield* store.clear;
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist when secure storage is unavailable", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
assert.isFalse(yield* store.set("{}"));
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const records: readonly PersistedSavedEnvironmentRecord[] = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
httpBaseUrl: "https://relay.example.com/",
|
||||
wsBaseUrl: "wss://relay.example.com/",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
relayManaged: { relayUrl: "https://relay-control.example.com/" },
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
httpBaseUrl: "http://127.0.0.1:41773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:41773/",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
createdAt: "2026-06-03T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
];
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
assert.isTrue(
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
secret: "legacy-token",
|
||||
}),
|
||||
);
|
||||
|
||||
const migrated = yield* store.get;
|
||||
assert.isTrue(Option.isSome(migrated));
|
||||
if (Option.isNone(migrated)) {
|
||||
return;
|
||||
}
|
||||
const catalog = yield* decodeConnectionCatalog(migrated.value);
|
||||
|
||||
assert.deepInclude(catalog.targets[0], {
|
||||
_tag: "RelayConnectionTarget",
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[1], {
|
||||
_tag: "SshConnectionTarget",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[2], {
|
||||
_tag: "BearerConnectionTarget",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[0], {
|
||||
_tag: "SshConnectionProfile",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[1], {
|
||||
_tag: "BearerConnectionProfile",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
});
|
||||
assert.equal(catalog.credentials.length, 1);
|
||||
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
|
||||
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
|
||||
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
|
||||
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
|
||||
}
|
||||
|
||||
yield* savedEnvironments.setRegistry([]);
|
||||
assert.deepEqual(yield* store.get, migrated);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces malformed catalog documents without deleting them", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.cause, permissionError);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const failDecrypt = yield* Ref.make(false);
|
||||
const layer = makeLayer(baseDir, true, failDecrypt);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -1,328 +0,0 @@
|
||||
import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionTarget,
|
||||
RelayConnectionTarget,
|
||||
SshConnectionProfile,
|
||||
SshConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
|
||||
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const EncryptedConnectionCatalogDocument = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
encryptedCatalog: Schema.String,
|
||||
});
|
||||
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
|
||||
|
||||
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
|
||||
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
|
||||
RuntimeConnectionCatalogDocument,
|
||||
);
|
||||
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode the desktop connection catalog.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to migrate legacy desktop saved environments.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopConnectionCatalogStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopConnectionCatalogStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
DesktopConnectionCatalogStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not remove a temporary connection catalog file.", {
|
||||
tempPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
|
||||
return `${prefix}:${environmentId}`;
|
||||
}
|
||||
|
||||
const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (record.relayManaged !== undefined) {
|
||||
targets.push(
|
||||
new RelayConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (record.desktopSsh !== undefined) {
|
||||
const id = connectionId("ssh", record.environmentId);
|
||||
targets.push(
|
||||
new SshConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new SshConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
target: record.desktopSsh,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = connectionId("bearer", record.environmentId);
|
||||
targets.push(
|
||||
new BearerConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
credential: new BearerConnectionCredential({ token: token.value }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
targets,
|
||||
profiles,
|
||||
credentials,
|
||||
remoteDpopTokens: [],
|
||||
};
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopConnectionCatalogStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry;
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
|
||||
yield* writeCatalog(encoded);
|
||||
return Option.some(encoded);
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -99,7 +99,6 @@ export const layer = Layer.effect(
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
|
||||
@@ -10,10 +10,12 @@ import {
|
||||
} from "./methods/cloudAuth.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import {
|
||||
clearConnectionCatalog,
|
||||
getConnectionCatalog,
|
||||
setConnectionCatalog,
|
||||
} from "./methods/connectionCatalog.ts";
|
||||
getSavedEnvironmentRegistry,
|
||||
getSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
setSavedEnvironmentRegistry,
|
||||
setSavedEnvironmentSecret,
|
||||
} from "./methods/savedEnvironments.ts";
|
||||
import {
|
||||
getAdvertisedEndpoints,
|
||||
getServerExposureState,
|
||||
@@ -57,9 +59,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
yield* ipc.handle(setClientSettings);
|
||||
yield* ipc.handle(getConnectionCatalog);
|
||||
yield* ipc.handle(setConnectionCatalog);
|
||||
yield* ipc.handle(clearConnectionCatalog);
|
||||
yield* ipc.handle(getSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(setSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(getSavedEnvironmentSecret);
|
||||
yield* ipc.handle(setSavedEnvironmentSecret);
|
||||
yield* ipc.handle(removeSavedEnvironmentSecret);
|
||||
|
||||
yield* ipc.handle(discoverSshHosts);
|
||||
yield* ipc.handle(ensureSshEnvironment);
|
||||
|
||||
@@ -20,9 +20,11 @@ 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_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
|
||||
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
|
||||
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
|
||||
@@ -59,7 +59,7 @@ function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInpu
|
||||
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())),
|
||||
HttpClientRequest.setHeaders(headers),
|
||||
input.body === undefined
|
||||
? identity
|
||||
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return Option.getOrNull(yield* store.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return yield* store.set(catalog);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* store.clear;
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
|
||||
const NonBlankString = Schema.String.check(
|
||||
Schema.makeFilter((value) =>
|
||||
value.trim().length > 0 ? undefined : "Expected a non-empty string",
|
||||
),
|
||||
);
|
||||
|
||||
const SetSavedEnvironmentSecretInput = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
secret: NonBlankString,
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: SavedEnvironmentRegistryPayload,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.getRegistry;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: SavedEnvironmentRegistryPayload,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
}),
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: SetSavedEnvironmentSecretInput,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
|
||||
environmentId,
|
||||
secret,
|
||||
}) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.setSecret({
|
||||
environmentId,
|
||||
secret,
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export const removeSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.removeSecret(environmentId);
|
||||
}),
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
} from "@t3tools/client-runtime";
|
||||
import {
|
||||
EnvironmentAuthInvalidError,
|
||||
DesktopDiscoveredSshHostSchema,
|
||||
|
||||
@@ -29,7 +29,6 @@ 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 DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
@@ -118,7 +117,7 @@ const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layerShutdown,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
DesktopSavedEnvironments.layer,
|
||||
DesktopCloudAuthTokenStore.layer,
|
||||
DesktopAssets.layer,
|
||||
DesktopObservability.layer,
|
||||
|
||||
@@ -42,10 +42,16 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
|
||||
setClientSettings: (settings) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
|
||||
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
|
||||
setConnectionCatalog: (catalog) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
|
||||
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
|
||||
getSavedEnvironmentRegistry: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
|
||||
setSavedEnvironmentRegistry: (records) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
|
||||
getSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
setSavedEnvironmentSecret: (environmentId, secret) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
|
||||
@@ -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* () {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -272,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
});
|
||||
|
||||
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
|
||||
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats empty saved environment documents as empty", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
@@ -309,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces malformed saved environment documents", () =>
|
||||
it.effect("treats malformed saved environment documents as empty", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -318,15 +298,10 @@ describe("DesktopSavedEnvironments", () => {
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
registryError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
);
|
||||
const secretError = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -82,16 +82,6 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop saved environments: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentSecretDecodeError",
|
||||
)<{
|
||||
@@ -103,7 +93,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
@@ -114,16 +103,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
|
||||
|
||||
export interface DesktopSavedEnvironmentsShape {
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadError
|
||||
>;
|
||||
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
@@ -193,20 +176,18 @@ function normalizeSavedEnvironmentRegistryDocument(
|
||||
function readRegistryDocument(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
registryPath: string,
|
||||
): Effect.Effect<
|
||||
SavedEnvironmentRegistryDocument,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> {
|
||||
): Effect.Effect<SavedEnvironmentRegistryDocument> {
|
||||
return fileSystem.readFileString(registryPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed({ version: 1, records: [] })
|
||||
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed({ version: 1, records: [] }),
|
||||
onSome: (raw) =>
|
||||
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.map(normalizeSavedEnvironmentRegistryDocument),
|
||||
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -286,39 +267,21 @@ export const layer = Layer.effect(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
);
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
|
||||
);
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
@@ -336,7 +299,7 @@ export const layer = Layer.effect(
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
@@ -368,7 +331,7 @@ export const layer = Layer.effect(
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
);
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
@@ -405,18 +368,6 @@ export const layerTest = (input?: {
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: Ref.get(recordsRef),
|
||||
setRegistry: (records) => Ref.set(recordsRef, records),
|
||||
removeEnvironment: (environmentId) =>
|
||||
Ref.update(recordsRef, (records) =>
|
||||
records.filter((record) => record.environmentId !== environmentId),
|
||||
).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(secretsRef, (secrets) => {
|
||||
const nextSecrets = new Map(secrets);
|
||||
nextSecrets.delete(environmentId);
|
||||
return nextSecrets;
|
||||
}),
|
||||
),
|
||||
),
|
||||
getSecret: (environmentId) =>
|
||||
Ref.get(secretsRef).pipe(
|
||||
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
---
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
@@ -38,17 +36,17 @@ const {
|
||||
</a>
|
||||
<div class="nav-right">
|
||||
<a
|
||||
class="nav-stars"
|
||||
href={GITHUB_REPOSITORY_URL}
|
||||
class="nav-gh"
|
||||
href="https://github.com/pingdotgg/t3code"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
|
||||
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
|
||||
</svg>
|
||||
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
|
||||
<span>GitHub</span>
|
||||
</a>
|
||||
<a class="btn btn-primary" href="/#download">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -64,7 +62,7 @@ const {
|
||||
<span>© {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
|
||||
</div>
|
||||
<div class="footer-links">
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
</div>
|
||||
@@ -331,36 +329,23 @@ const {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.nav-stars {
|
||||
.nav-gh {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border-radius: 8px;
|
||||
color: var(--fg-muted);
|
||||
font-size: 13px;
|
||||
letter-spacing: -0.01em;
|
||||
white-space: nowrap;
|
||||
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.nav-stars:hover {
|
||||
.nav-gh:hover {
|
||||
color: var(--fg);
|
||||
border-color: var(--border-strong);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.nav-stars strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.nav-stars svg {
|
||||
color: var(--warn);
|
||||
flex-shrink: 0;
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.main {
|
||||
@@ -422,17 +407,4 @@ const {
|
||||
padding-right: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.nav-inner {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.nav-stars {
|
||||
height: 34px;
|
||||
gap: 6px;
|
||||
padding: 0 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +0,0 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "12k+",
|
||||
users: "100,000",
|
||||
} as const;
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import { tweets } from "../lib/tweets";
|
||||
|
||||
const desktopEndorsementRows = [
|
||||
@@ -56,12 +55,11 @@ const mobileEndorsementRows = [
|
||||
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
|
||||
<span id="download-label">Download for macOS</span>
|
||||
</a>
|
||||
<a class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
|
||||
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
|
||||
</svg>
|
||||
<span>Steal our code (legally)</span>
|
||||
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
Star on GitHub
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -84,8 +82,8 @@ const mobileEndorsementRows = [
|
||||
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
|
||||
<div class="container">
|
||||
<div class="endorsements-head">
|
||||
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
|
||||
<p>Some of them even tweeted about it.</p>
|
||||
<h2 id="endorsements-title">Developers love T3 Code</h2>
|
||||
<p>Real reactions from people building with T3 Code today.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -284,6 +282,10 @@ const mobileEndorsementRows = [
|
||||
<div class="section-head open-head">
|
||||
<div class="eyebrow">Open source</div>
|
||||
<h2>If you don't like something, fork it.</h2>
|
||||
<p>
|
||||
T3 Code is as open as they come. We built this app to be modifiable,
|
||||
customizable, and forkable. Go nuts - that's the whole point.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="open-grid">
|
||||
@@ -303,44 +305,43 @@ const mobileEndorsementRows = [
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tile open-pitch">
|
||||
<div class="open-pitch-copy">
|
||||
<ul class="open-pitch-list">
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="open-stats">
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">MIT</div>
|
||||
<div class="open-stat-lbl">License · commercial-friendly</div>
|
||||
</div>
|
||||
|
||||
<div class="open-pitch-footer">
|
||||
<div class="open-pitch-meta">
|
||||
<span>MIT licensed</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{MARKETING_STATS.githubStars} stars</span>
|
||||
</div>
|
||||
|
||||
<div class="open-pitch-actions">
|
||||
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
|
||||
Fork on GitHub
|
||||
</a>
|
||||
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
|
||||
Browse source
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">TypeScript</div>
|
||||
<div class="open-stat-lbl">End-to-end, strictly typed</div>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">1 monorepo</div>
|
||||
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">No telemetry</div>
|
||||
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="open-ctas">
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
|
||||
Star on GitHub
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
|
||||
Fork the repo
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
|
||||
Read CONTRIBUTING.md
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -514,7 +515,7 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-title {
|
||||
font-size: clamp(38px, 5.6vw, 76px);
|
||||
margin: 48px auto 22px;
|
||||
margin: 28px auto 22px;
|
||||
max-width: 20ch;
|
||||
text-wrap: balance;
|
||||
}
|
||||
@@ -530,42 +531,12 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
gap: 10px;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 56px;
|
||||
}
|
||||
|
||||
.hero-source-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--fg-muted);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
transition: color 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-source-link:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.hero-source-mark {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.hero-source-arrow {
|
||||
flex-shrink: 0;
|
||||
opacity: 0.6;
|
||||
transition: transform 0.18s ease, opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-source-link:hover .hero-source-arrow {
|
||||
transform: translate(2px, -2px);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Download button icons (platform-aware) */
|
||||
.dl-icon {
|
||||
display: none;
|
||||
@@ -685,30 +656,6 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-opencode,
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 580px;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-cursor {
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode img,
|
||||
.hero-float-mark.hf-cursor img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero-preview {
|
||||
max-width: 1180px;
|
||||
margin: 0 auto;
|
||||
@@ -812,11 +759,6 @@ const mobileEndorsementRows = [
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.endorsements-count {
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.endorsements-head p {
|
||||
color: var(--fg-muted);
|
||||
font-size: 18px;
|
||||
@@ -1020,11 +962,12 @@ const mobileEndorsementRows = [
|
||||
text-align: center;
|
||||
margin: 0 auto 56px;
|
||||
}
|
||||
.open-head p { margin: 0 auto; }
|
||||
|
||||
.open-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.25fr 1fr;
|
||||
gap: 20px;
|
||||
gap: 20px; margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.open-term { padding: 0; overflow: hidden; }
|
||||
@@ -1066,85 +1009,27 @@ const mobileEndorsementRows = [
|
||||
animation: blink 1s steps(2) infinite;
|
||||
}
|
||||
|
||||
.open-pitch {
|
||||
padding: 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 32px;
|
||||
background:
|
||||
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
|
||||
}
|
||||
|
||||
.open-pitch-list {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.open-pitch-list li {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.open-pitch-list strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.open-pitch-mark {
|
||||
flex: none;
|
||||
.open-stats {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin-top: 1px;
|
||||
border-radius: 7px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-dim);
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.open-stat {
|
||||
padding: 22px;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
}
|
||||
.open-stat-val {
|
||||
font-size: 22px; font-weight: 500;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
.open-stat-lbl {
|
||||
font-family: var(--font-mono); font-size: 10.5px;
|
||||
color: var(--fg-dim); letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.open-pitch-footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.open-pitch-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.open-pitch-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.open-source-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--fg-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: color 0.18s ease;
|
||||
}
|
||||
|
||||
.open-source-link:hover {
|
||||
color: var(--fg);
|
||||
.open-ctas {
|
||||
display: flex; gap: 10px;
|
||||
justify-content: center; flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* ── Final CTA ────────────────────────────────────────── */
|
||||
|
||||
@@ -131,11 +131,6 @@ const config: ExpoConfig = {
|
||||
{
|
||||
ios: {
|
||||
deploymentTarget: "18.0",
|
||||
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
|
||||
extraPods: [
|
||||
{ name: "GoogleUtilities", modular_headers: true },
|
||||
{ name: "RecaptchaInterop", modular_headers: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
{
|
||||
"cli": {
|
||||
"version": ">= 18.4.0",
|
||||
"appVersionSource": "remote",
|
||||
"promptToConfigurePushNotifications": false
|
||||
"appVersionSource": "remote"
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
|
||||
@@ -70,12 +70,7 @@ static void T3MarkdownTextApplyAttachments(
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
}
|
||||
attachment.image = image ?: [[UIImage alloc] init];
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -85,6 +80,104 @@ static void T3MarkdownTextApplyAttachments(
|
||||
}
|
||||
}
|
||||
|
||||
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextChipRange> &chipRanges)
|
||||
{
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
|
||||
for (const auto &chipRange : chipRanges) {
|
||||
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange range = NSMakeRange(
|
||||
chipRange.location,
|
||||
MIN(chipRange.length, attributedString.length - chipRange.location));
|
||||
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
if (color == nil) {
|
||||
continue;
|
||||
}
|
||||
[backgrounds addObject:@{
|
||||
@"range": [NSValue valueWithRange:range],
|
||||
@"color": color,
|
||||
@"strokeColor": [foregroundColor
|
||||
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
|
||||
}];
|
||||
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
|
||||
}
|
||||
return backgrounds;
|
||||
}
|
||||
|
||||
@interface T3MarkdownTextBackingView : UITextView
|
||||
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownTextBackingView
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
if (context != nil) {
|
||||
CGContextSaveGState(context);
|
||||
CGContextResetClip(context);
|
||||
CGContextClipToRect(context, self.bounds);
|
||||
}
|
||||
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
|
||||
const NSRange characterRange = [background[@"range"] rangeValue];
|
||||
UIColor *color = background[@"color"];
|
||||
UIColor *strokeColor = background[@"strokeColor"];
|
||||
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange glyphRange =
|
||||
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
|
||||
[color setFill];
|
||||
[self.layoutManager
|
||||
enumerateEnclosingRectsForGlyphRange:glyphRange
|
||||
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
|
||||
inTextContainer:self.textContainer
|
||||
usingBlock:^(CGRect glyphRect, BOOL *stop) {
|
||||
const CGFloat chipHeight = 22;
|
||||
CGRect chipRect = CGRectMake(
|
||||
glyphRect.origin.x - 4,
|
||||
CGRectGetMidY(glyphRect) - chipHeight / 2,
|
||||
glyphRect.size.width + 8,
|
||||
chipHeight);
|
||||
chipRect.origin.x += self.textContainerInset.left;
|
||||
chipRect.origin.y += self.textContainerInset.top;
|
||||
const CGFloat minimumX = self.textContainerInset.left + 0.5;
|
||||
const CGFloat maximumX =
|
||||
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
|
||||
if (chipRect.origin.x < minimumX) {
|
||||
chipRect.size.width -= minimumX - chipRect.origin.x;
|
||||
chipRect.origin.x = minimumX;
|
||||
}
|
||||
if (CGRectGetMaxX(chipRect) > maximumX) {
|
||||
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
|
||||
}
|
||||
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
|
||||
[path fill];
|
||||
[strokeColor setStroke];
|
||||
path.lineWidth = 1;
|
||||
[path stroke];
|
||||
}];
|
||||
}
|
||||
if (context != nil) {
|
||||
CGContextRestoreGState(context);
|
||||
}
|
||||
|
||||
[super drawRect:rect];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@protocol T3MarkdownOutsideTapTarget <NSObject>
|
||||
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
|
||||
@end
|
||||
@@ -192,7 +285,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
|
||||
@implementation T3MarkdownText {
|
||||
UIView * _view;
|
||||
UITextView * _textView;
|
||||
T3MarkdownTextBackingView * _textView;
|
||||
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
|
||||
__weak UIWindow * _outsideTapWindow;
|
||||
BOOL _suppressSelectionChange;
|
||||
@@ -215,7 +308,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
self.contentView = _view;
|
||||
self.clipsToBounds = true;
|
||||
|
||||
_textView = [[UITextView alloc] init];
|
||||
_textView = [[T3MarkdownTextBackingView alloc] init];
|
||||
_attachmentImages = [[NSMutableDictionary alloc] init];
|
||||
_pendingAttachmentUris = [[NSMutableSet alloc] init];
|
||||
_textView.scrollEnabled = false;
|
||||
@@ -312,6 +405,9 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
convertedAttrString,
|
||||
_state->getData().attachmentRanges,
|
||||
_attachmentImages);
|
||||
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
|
||||
convertedAttrString,
|
||||
_state->getData().chipRanges);
|
||||
[self loadAttachmentImages:_state->getData().attachmentRanges];
|
||||
|
||||
// Setting attributedText clears any active text selection, and re-assigning
|
||||
|
||||
@@ -28,20 +28,18 @@ struct T3MarkdownTextAttachmentRange {
|
||||
std::string imageUri;
|
||||
};
|
||||
|
||||
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
|
||||
return 14;
|
||||
}
|
||||
|
||||
inline Float T3MarkdownTextAttachmentBaselineOffset(
|
||||
const T3MarkdownTextAttachmentRange &) {
|
||||
return -2;
|
||||
}
|
||||
struct T3MarkdownTextChipRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
bool isSkill;
|
||||
};
|
||||
|
||||
class T3MarkdownTextStateReal final {
|
||||
public:
|
||||
AttributedString attributedString;
|
||||
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
|
||||
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
|
||||
std::vector<T3MarkdownTextChipRange> chipRanges;
|
||||
};
|
||||
|
||||
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
|
||||
@@ -74,5 +72,6 @@ private:
|
||||
mutable AttributedString _attributedString;
|
||||
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
|
||||
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
|
||||
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
|
||||
};
|
||||
} // namespace facebook::React
|
||||
@@ -9,8 +9,9 @@
|
||||
namespace facebook::react {
|
||||
|
||||
static constexpr Float ParagraphStyleEncodingOffset = 1000;
|
||||
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
|
||||
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
|
||||
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
|
||||
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
|
||||
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
|
||||
|
||||
static void applyParagraphStyles(
|
||||
NSMutableAttributedString *attributedString,
|
||||
@@ -57,12 +58,7 @@ static void applyAttachments(
|
||||
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
attachment.image = [[UIImage alloc] init];
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -95,6 +91,7 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
auto baseAttributedString = AttributedString{};
|
||||
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
|
||||
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
|
||||
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
|
||||
size_t utf16Offset = 0;
|
||||
const auto &children = getChildren();
|
||||
for (size_t i = 0; i < children.size(); i++) {
|
||||
@@ -187,19 +184,25 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
props.shadowRadius - ParagraphStyleEncodingOffset,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
chipRanges.push_back(T3MarkdownTextChipRange{
|
||||
utf16Offset,
|
||||
fragmentLength,
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset,
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(
|
||||
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
|
||||
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
|
||||
});
|
||||
}
|
||||
utf16Offset += fragmentLength;
|
||||
@@ -210,6 +213,7 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
_attributedString = baseAttributedString;
|
||||
_paragraphStyleRanges = paragraphStyleRanges;
|
||||
_attachmentRanges = attachmentRanges;
|
||||
_chipRanges = chipRanges;
|
||||
|
||||
NSMutableAttributedString *convertedAttributedString =
|
||||
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
|
||||
@@ -259,6 +263,7 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
|
||||
_attributedString,
|
||||
_paragraphStyleRanges,
|
||||
_attachmentRanges,
|
||||
_chipRanges,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -40,13 +40,11 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -314,7 +312,6 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const rows = collectTableRows(props.node);
|
||||
return (
|
||||
@@ -354,7 +351,6 @@ function NativeTable(props: {
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
@@ -368,17 +364,10 @@ function NativeTable(props: {
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const href = props.node.href;
|
||||
if (!href) {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -437,7 +426,6 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
@@ -447,15 +435,9 @@ function NativeMixedParagraph(props: {
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
@@ -466,7 +448,6 @@ function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly depth: number;
|
||||
}) {
|
||||
const ordered = props.node.ordered ?? false;
|
||||
@@ -527,7 +508,6 @@ function NativeList(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={props.depth + 1}
|
||||
compact
|
||||
/>
|
||||
@@ -544,7 +524,6 @@ export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly depth?: number;
|
||||
readonly compact?: boolean;
|
||||
}) {
|
||||
@@ -559,7 +538,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
/>
|
||||
))}
|
||||
@@ -575,21 +553,9 @@ export function NativeMarkdownBlock(props: {
|
||||
/>
|
||||
);
|
||||
case "table":
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <NativeTable node={props.node} textStyle={props.textStyle} />;
|
||||
case "image":
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
|
||||
case "horizontal_rule":
|
||||
return (
|
||||
<View
|
||||
@@ -617,7 +583,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -630,23 +595,14 @@ export function NativeMarkdownBlock(props: {
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
/>
|
||||
);
|
||||
case "paragraph":
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
);
|
||||
case "html_block":
|
||||
case "math_block":
|
||||
@@ -662,11 +618,7 @@ export function NativeMarkdownBlock(props: {
|
||||
: "transparent",
|
||||
}}
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
</View>
|
||||
);
|
||||
case "table_head":
|
||||
@@ -683,7 +635,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -691,12 +642,6 @@ export function NativeMarkdownBlock(props: {
|
||||
</View>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,61 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Asset } from "expo-asset";
|
||||
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
|
||||
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import { markdownFileIconSource } from "./markdownFileIcons";
|
||||
import type { MarkdownFileIcon } from "./markdownLinks";
|
||||
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
|
||||
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
|
||||
|
||||
const EXTERNAL_LINK_PREFIX = "◉ ";
|
||||
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
|
||||
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
|
||||
const CHIP_SUFFIX = "\u00A0";
|
||||
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
|
||||
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
|
||||
|
||||
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
|
||||
const iconSignature = JSON.stringify(
|
||||
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
|
||||
);
|
||||
const icons = useMemo(
|
||||
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
|
||||
[iconSignature],
|
||||
);
|
||||
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void Promise.all(
|
||||
icons.map(async (icon) => {
|
||||
const source = markdownFileIconSource(icon);
|
||||
const fallbackUri = Image.resolveAssetSource(source).uri;
|
||||
if (typeof source !== "number" && typeof source !== "string") {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
try {
|
||||
const asset = Asset.fromModule(source);
|
||||
await asset.downloadAsync();
|
||||
return [icon, asset.localUri ?? fallbackUri] as const;
|
||||
} catch {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
}),
|
||||
).then((entries) => {
|
||||
if (!cancelled) {
|
||||
setUris(new Map(entries));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [icons]);
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
return [
|
||||
run.text,
|
||||
@@ -35,16 +81,13 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const isChip = isFile || isSkill;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
const textDecorationLine = run.strikethrough
|
||||
? "line-through"
|
||||
: run.href && !isFile
|
||||
? "underline"
|
||||
: "none";
|
||||
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
|
||||
|
||||
return {
|
||||
color: isFile
|
||||
@@ -63,23 +106,20 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? textStyle.mutedColor
|
||||
: run.role === "list-marker"
|
||||
? textStyle.mutedColor
|
||||
: isCodeBlock
|
||||
: run.code || isFile
|
||||
? textStyle.codeColor
|
||||
: run.code
|
||||
? textStyle.inlineCodeColor
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily:
|
||||
isFile || isSkill
|
||||
? textStyle.boldFontFamily
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily: isChip
|
||||
? "DMSans_500Medium"
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
fontSize:
|
||||
run.role === "spacer"
|
||||
? (run.spacing ?? 10)
|
||||
@@ -89,7 +129,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
: run.code || isCodeBlock
|
||||
: run.code || isChip || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
lineHeight:
|
||||
@@ -103,9 +143,17 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? 18
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
|
||||
textDecorationLine,
|
||||
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
|
||||
backgroundColor: isCodeBlock
|
||||
? textStyle.codeBlockBackgroundColor
|
||||
: isSkill
|
||||
? textStyle.skillBackgroundColor
|
||||
: run.code
|
||||
? textStyle.codeBackgroundColor
|
||||
: isFile
|
||||
? textStyle.fileBackgroundColor
|
||||
: undefined,
|
||||
...(hasParagraphStyle
|
||||
? {
|
||||
shadowColor: "transparent",
|
||||
@@ -122,9 +170,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
export function NativeMarkdownSelectableText(props: {
|
||||
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const fileIconUris = useFileIconUris(props.runs);
|
||||
const occurrences = new Map<string, number>();
|
||||
const prefixedExternalLinks = new Set<string>();
|
||||
const keyedRuns = props.runs.map((run) => {
|
||||
@@ -134,9 +182,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
|
||||
let text = run.text;
|
||||
if (run.fileIcon) {
|
||||
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
|
||||
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
|
||||
} else if (run.skillName && run.skillLabel) {
|
||||
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
|
||||
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
|
||||
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
|
||||
prefixedExternalLinks.add(run.href);
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
@@ -152,11 +200,12 @@ export function NativeMarkdownSelectableText(props: {
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
props.textStyle.linkColor,
|
||||
props.textStyle.inlineCodeColor,
|
||||
props.textStyle.codeColor,
|
||||
props.textStyle.codeBackgroundColor,
|
||||
props.textStyle.codeBlockBackgroundColor,
|
||||
props.textStyle.fileBackgroundColor,
|
||||
props.textStyle.fileTextColor,
|
||||
props.textStyle.skillBackgroundColor,
|
||||
props.textStyle.skillTextColor,
|
||||
props.textStyle.quoteMarkerColor,
|
||||
props.textStyle.dividerColor,
|
||||
@@ -168,8 +217,7 @@ export function NativeMarkdownSelectableText(props: {
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
width: "100%",
|
||||
color: props.textStyle.color,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: props.textStyle.fontSize,
|
||||
@@ -183,20 +231,19 @@ export function NativeMarkdownSelectableText(props: {
|
||||
key={key}
|
||||
nativeID={
|
||||
run.fileIcon
|
||||
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
|
||||
? `t3-chip-file:${
|
||||
fileIconUris.get(run.fileIcon) ??
|
||||
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
|
||||
}`
|
||||
: run.skillName
|
||||
? "t3-skill:sf:cube"
|
||||
? "t3-chip-skill:sf:cube"
|
||||
: undefined
|
||||
}
|
||||
style={runStyle(run, props.textStyle)}
|
||||
onPress={
|
||||
href
|
||||
? () => {
|
||||
if (props.onLinkPress) {
|
||||
props.onLinkPress(href);
|
||||
} else {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
nativeMarkdownChunkSpacing,
|
||||
nativeMarkdownDocumentChunks,
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
@@ -34,20 +33,15 @@ export function SelectableMarkdownText({
|
||||
skills = EMPTY_SKILLS,
|
||||
textStyle,
|
||||
highlightCode,
|
||||
preserveSoftBreaks = false,
|
||||
onLinkPress,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
const chunks = useMemo(() => {
|
||||
const parsedDocument = parseMarkdownWithOptions(markdown, {
|
||||
const document = parseMarkdownWithOptions(markdown, {
|
||||
gfm: true,
|
||||
html: true,
|
||||
math: false,
|
||||
});
|
||||
const document = preserveSoftBreaks
|
||||
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
|
||||
: parsedDocument;
|
||||
return nativeMarkdownDocumentChunks(document).map((chunk) =>
|
||||
chunk.kind === "selectable"
|
||||
? {
|
||||
@@ -56,14 +50,10 @@ export function SelectableMarkdownText({
|
||||
}
|
||||
: chunk,
|
||||
);
|
||||
}, [markdown, preserveSoftBreaks, skills]);
|
||||
}, [markdown, skills]);
|
||||
|
||||
return (
|
||||
// A percentage width here creates a cyclic intrinsic measurement inside
|
||||
// shrink-to-fit containers such as user-message bubbles. Yoga then gives
|
||||
// the native text node an unbounded second pass and the parent only clips
|
||||
// the resulting single-line width instead of reflowing it.
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
<View style={{ width: "100%", marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
@@ -71,14 +61,9 @@ export function SelectableMarkdownText({
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,11 +3,12 @@ export interface NativeMarkdownTextStyle {
|
||||
readonly strongColor: string;
|
||||
readonly mutedColor: string;
|
||||
readonly linkColor: string;
|
||||
readonly inlineCodeColor: string;
|
||||
readonly codeColor: string;
|
||||
readonly codeBackgroundColor: string;
|
||||
readonly codeBlockBackgroundColor: string;
|
||||
readonly fileBackgroundColor: string;
|
||||
readonly fileTextColor: string;
|
||||
readonly skillBackgroundColor: string;
|
||||
readonly skillTextColor: string;
|
||||
readonly quoteMarkerColor: string;
|
||||
readonly dividerColor: string;
|
||||
@@ -40,8 +41,6 @@ export interface SelectableMarkdownTextProps {
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly preserveSoftBreaks?: boolean;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly marginTop?: number;
|
||||
readonly marginBottom?: number;
|
||||
}
|
||||
@@ -27,12 +27,8 @@ export type MarkdownLinkPresentation =
|
||||
}
|
||||
| {
|
||||
readonly kind: "file";
|
||||
readonly href: string;
|
||||
readonly icon: MarkdownFileIcon;
|
||||
readonly label: string;
|
||||
readonly path: string;
|
||||
readonly line?: number;
|
||||
readonly column?: number;
|
||||
}
|
||||
| {
|
||||
readonly kind: "link";
|
||||
@@ -251,7 +247,7 @@ function normalizeDestination(value: string): string {
|
||||
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
|
||||
}
|
||||
|
||||
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
|
||||
function fileUrlPath(href: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(href);
|
||||
if (parsed.protocol.toLowerCase() !== "file:") {
|
||||
@@ -260,44 +256,15 @@ function fileUrlTarget(href: string): { readonly path: string; readonly hash: st
|
||||
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
|
||||
? parsed.pathname.slice(1)
|
||||
: parsed.pathname;
|
||||
return { path, hash: parsed.hash };
|
||||
const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
|
||||
return `${safeDecode(path)}${
|
||||
lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
|
||||
}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
|
||||
const hashIndex = value.indexOf("#");
|
||||
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
|
||||
const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
|
||||
const queryIndex = pathWithSearch.indexOf("?");
|
||||
return {
|
||||
path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
|
||||
hash,
|
||||
};
|
||||
}
|
||||
|
||||
function splitFilePosition(
|
||||
path: string,
|
||||
hash: string,
|
||||
): { readonly path: string; readonly line?: number; readonly column?: number } {
|
||||
const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
|
||||
const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
|
||||
const match = suffixMatch ?? hashMatch;
|
||||
if (!match?.[1]) {
|
||||
return { path };
|
||||
}
|
||||
|
||||
const line = Number.parseInt(match[1], 10);
|
||||
const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
|
||||
const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
|
||||
return {
|
||||
path: pathWithoutPosition,
|
||||
...(line > 0 ? { line } : {}),
|
||||
...(column !== undefined && column > 0 ? { column } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function looksLikePosixFilesystemPath(path: string): boolean {
|
||||
if (!path.startsWith("/")) {
|
||||
return false;
|
||||
@@ -364,31 +331,14 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
|
||||
// Relative paths and non-URL link destinations are handled below.
|
||||
}
|
||||
|
||||
const source = normalized.toLowerCase().startsWith("file:")
|
||||
? fileUrlTarget(normalized)
|
||||
: stripSearchAndHash(normalized);
|
||||
const decodedSource = source
|
||||
? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
|
||||
: null;
|
||||
const fileTarget = decodedSource
|
||||
? splitFilePosition(decodedSource.path, decodedSource.hash)
|
||||
: null;
|
||||
const targetWithPosition = fileTarget
|
||||
? `${fileTarget.path}${
|
||||
fileTarget.line
|
||||
? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
|
||||
: ""
|
||||
}`
|
||||
: null;
|
||||
if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
|
||||
const fileTarget = normalized.toLowerCase().startsWith("file:")
|
||||
? fileUrlPath(normalized)
|
||||
: safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
|
||||
if (fileTarget && looksLikeFilePath(fileTarget)) {
|
||||
return {
|
||||
kind: "file",
|
||||
href: normalized,
|
||||
icon: resolveMarkdownFileIcon(fileTarget.path),
|
||||
label: fileLabel(targetWithPosition),
|
||||
path: fileTarget.path,
|
||||
...(fileTarget.line ? { line: fileTarget.line } : {}),
|
||||
...(fileTarget.column ? { column: fileTarget.column } : {}),
|
||||
icon: resolveMarkdownFileIcon(fileTarget),
|
||||
label: fileLabel(fileTarget),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -293,7 +293,6 @@ function appendNode(
|
||||
if (presentation.kind === "file") {
|
||||
return appendRun(runs, presentation.label, {
|
||||
...context,
|
||||
href: presentation.href,
|
||||
fileIcon: presentation.icon,
|
||||
});
|
||||
}
|
||||
@@ -320,15 +319,6 @@ export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<Native
|
||||
return appendChildren([], node, EMPTY_CONTEXT);
|
||||
}
|
||||
|
||||
export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
|
||||
const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
|
||||
return {
|
||||
...node,
|
||||
...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
|
||||
...(children ? { children } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function appendBlockTerminator(
|
||||
runs: NativeMarkdownTextRun[],
|
||||
context: RunContext,
|
||||
|
||||
@@ -57,10 +57,6 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setContentWidth(CGFloat(contentWidth))
|
||||
}
|
||||
|
||||
Prop("initialRowIndex") { (view: T3ReviewDiffView, initialRowIndex: Double) in
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +205,7 @@ private struct ReviewDiffNativeStyle {
|
||||
ReviewDiffNativeStyle(
|
||||
rowHeight: metric(payload?.rowHeight, fallback: 24),
|
||||
contentWidth: metric(payload?.contentWidth, fallback: 2800),
|
||||
changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
|
||||
changeBarWidth: metric(payload?.changeBarWidth, fallback: 4),
|
||||
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
|
||||
codePadding: metric(payload?.codePadding, fallback: 8),
|
||||
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
|
||||
@@ -243,13 +243,6 @@ private struct ReviewDiffNativeStyle {
|
||||
return CGFloat(value)
|
||||
}
|
||||
|
||||
private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
|
||||
guard let value, value.isFinite, value >= 0 else {
|
||||
return fallback
|
||||
}
|
||||
return CGFloat(value)
|
||||
}
|
||||
|
||||
private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
|
||||
switch value?.lowercased() {
|
||||
case "ultralight", "ultra-light":
|
||||
@@ -323,8 +316,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private var lastMetricsDebugKey = ""
|
||||
private var lastVisibleRangeDebugKey = ""
|
||||
private var tokensResetKey = ""
|
||||
private var initialRowIndex: Int?
|
||||
private var hasAppliedInitialRowIndex = false
|
||||
|
||||
let onDebug = EventDispatcher()
|
||||
let onToggleFile = EventDispatcher()
|
||||
@@ -403,7 +394,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
do {
|
||||
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
contentView.rows = rows
|
||||
hasAppliedInitialRowIndex = false
|
||||
emitDebug("rows-decoded", [
|
||||
"rows": rows.count,
|
||||
"firstKind": rows.first?.kind ?? "none",
|
||||
@@ -412,7 +402,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
} catch {
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
updateContentMetrics()
|
||||
emitDebug("rows-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
@@ -572,7 +561,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
contentView.setNeedsDisplay()
|
||||
applyInitialRowIndexIfNeeded()
|
||||
|
||||
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
|
||||
if debugKey != lastMetricsDebugKey {
|
||||
@@ -657,19 +645,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
applyStyle()
|
||||
}
|
||||
|
||||
func setInitialRowIndex(_ initialRowIndex: Double) {
|
||||
let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
|
||||
? Int(initialRowIndex.rounded(.down))
|
||||
: nil
|
||||
guard nextIndex != self.initialRowIndex else {
|
||||
return
|
||||
}
|
||||
|
||||
self.initialRowIndex = nextIndex
|
||||
hasAppliedInitialRowIndex = false
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
@@ -687,22 +662,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
}
|
||||
|
||||
private func applyInitialRowIndexIfNeeded() {
|
||||
guard !hasAppliedInitialRowIndex,
|
||||
let initialRowIndex,
|
||||
bounds.height > 0,
|
||||
let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
|
||||
return
|
||||
}
|
||||
|
||||
let targetScreenY = max(0, (bounds.height - rowFrame.height) * 0.3)
|
||||
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
|
||||
let targetOffset = min(max(rowFrame.minY - targetScreenY, 0), maxOffset)
|
||||
hasAppliedInitialRowIndex = true
|
||||
scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
|
||||
updateViewportFrame()
|
||||
}
|
||||
}
|
||||
|
||||
private enum ReviewDiffHorizontalPanKind {
|
||||
@@ -861,19 +820,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
|
||||
return style.rowHeight
|
||||
}
|
||||
|
||||
func frameForRow(at index: Int) -> CGRect? {
|
||||
guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return CGRect(
|
||||
x: 0,
|
||||
y: rowOffsets[index],
|
||||
width: max(viewportWidth, 1),
|
||||
height: height(for: rows[index])
|
||||
)
|
||||
}
|
||||
|
||||
private func rebuildRowLayout() {
|
||||
var nextOffsets: [CGFloat] = []
|
||||
var nextFileHeaderRowIndices: [Int] = []
|
||||
|
||||
@@ -49,10 +49,10 @@
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@react-native-menu/menu": "^2.0.0",
|
||||
"@shikijs/core": "4.2.0",
|
||||
"@shikijs/engine-javascript": "4.2.0",
|
||||
"@shikijs/langs": "4.2.0",
|
||||
"@shikijs/themes": "4.2.0",
|
||||
"@shikijs/core": "3.23.0",
|
||||
"@shikijs/engine-javascript": "3.23.0",
|
||||
"@shikijs/langs": "3.23.0",
|
||||
"@shikijs/themes": "3.23.0",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/mobile-markdown-text": "file:./modules/t3-markdown-text",
|
||||
@@ -77,7 +77,6 @@
|
||||
"expo-haptics": "~56.0.3",
|
||||
"expo-image-picker": "~56.0.14",
|
||||
"expo-linking": "~56.0.12",
|
||||
"expo-network": "~56.0.5",
|
||||
"expo-notifications": "~56.0.14",
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-router": "~56.2.7",
|
||||
@@ -99,11 +98,10 @@
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
"react-native-shiki-engine": "^0.3.12",
|
||||
"react-native-shiki-engine": "^0.3.9",
|
||||
"react-native-svg": "15.15.4",
|
||||
"react-native-webview": "^13.16.1",
|
||||
"react-native-worklets": "0.8.3",
|
||||
"shiki": "4.2.0",
|
||||
"shiki": "3.23.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"uniwind": "^1.6.2"
|
||||
},
|
||||
|
||||
@@ -16,8 +16,10 @@ import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { LoadingScreen } from "../components/LoadingScreen";
|
||||
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
|
||||
import {
|
||||
useRemoteEnvironmentBootstrap,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../state/use-remote-environment-registry";
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
|
||||
@@ -30,24 +32,22 @@ import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
function AppNavigator() {
|
||||
const pathname = usePathname();
|
||||
const expandedSettingsRouteIsActive =
|
||||
pathname === "/settings/archive" || pathname === "/settings/auth";
|
||||
const clerkRouteIsActive = pathname === "/settings/auth";
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
|
||||
<AppNavigatorContent />
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppNavigatorContent() {
|
||||
const { state } = useWorkspaceState();
|
||||
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
|
||||
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
const sheetStyle = useResolveClassNames("bg-sheet");
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
|
||||
const handleSettingsTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
@@ -81,7 +81,7 @@ function AppNavigatorContent() {
|
||||
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
|
||||
};
|
||||
|
||||
if (state.isLoadingConnections) {
|
||||
if (isLoadingSavedConnection) {
|
||||
return <LoadingScreen message="Loading remote workspace…" />;
|
||||
}
|
||||
|
||||
@@ -129,6 +129,8 @@ export default function RootLayout() {
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
useRemoteEnvironmentBootstrap();
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Alert, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -112,12 +111,12 @@ export default function ConnectionsNewRouteScreen() {
|
||||
const handleSubmit = useCallback(async () => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
const pairingUrl = buildPairingUrl(hostInput, codeInput);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
try {
|
||||
const pairingUrl = buildPairingUrl(hostInput, codeInput);
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
await onConnectPress(pairingUrl);
|
||||
dismissRoute(router);
|
||||
} else {
|
||||
} catch {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
|
||||
|
||||
@@ -1,119 +1,112 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
|
||||
import { useRemoteCatalog } from "../state/use-remote-catalog";
|
||||
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { HomeHeader } from "../features/home/HomeHeader";
|
||||
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
|
||||
import { useThreadListActions } from "../features/home/useThreadListActions";
|
||||
|
||||
interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export default function HomeRouteScreen() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const { projects, state: catalogState, threads } = useRemoteCatalog();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [listOptions, setListOptions] = useState<HomeListOptions>({
|
||||
selectedEnvironmentId: null,
|
||||
projectSortOrder:
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
});
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(
|
||||
Order.String,
|
||||
(environment: { readonly label: string }) => environment.label,
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const selectedEnvironmentId = environments.some(
|
||||
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
|
||||
)
|
||||
? listOptions.selectedEnvironmentId
|
||||
: null;
|
||||
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
|
||||
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
|
||||
}, []);
|
||||
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, projectSortOrder }));
|
||||
}, []);
|
||||
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, threadSortOrder }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
|
||||
setListOptions((current) => ({ ...current, projectGroupingMode }));
|
||||
}, []);
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenSettings={() => router.push("/settings")}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => router.push("/new")}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Header left: plain text, no Liquid Glass button chrome */}
|
||||
<Stack.Toolbar placement="left">
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 17,
|
||||
color: iconColor,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
T3 Code
|
||||
</RNText>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 99,
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 10,
|
||||
color: mutedColor,
|
||||
letterSpacing: 1.1,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="gearshape"
|
||||
onPress={() => router.push("/settings")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
|
||||
<Stack.Toolbar.Button
|
||||
icon="square.and.pencil"
|
||||
onPress={() => router.push("/new")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<HomeScreen
|
||||
projects={projects}
|
||||
threads={threads}
|
||||
catalogState={catalogState}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
onAddConnection={() => router.push("/connections/new")}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onOpenEnvironments={() => router.push("/settings/environments")}
|
||||
onSelectThread={(thread) => {
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
|
||||
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime";
|
||||
|
||||
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
|
||||
@@ -8,17 +8,16 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
|
||||
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
|
||||
|
||||
function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
|
||||
readonly title: string;
|
||||
readonly detail: string;
|
||||
readonly loading: boolean;
|
||||
} {
|
||||
if (catalogState.isLoadingConnections) {
|
||||
if (catalogState.isLoadingSavedConnections) {
|
||||
return {
|
||||
title: "Loading environments",
|
||||
detail: "Checking saved environments on this device.",
|
||||
@@ -26,7 +25,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
};
|
||||
}
|
||||
|
||||
if (!catalogState.hasConnections) {
|
||||
if (!catalogState.hasSavedConnections) {
|
||||
return {
|
||||
title: "No environments connected",
|
||||
detail: "Add an environment before creating a task.",
|
||||
@@ -34,12 +33,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
(catalogState.connectionState === "available" ||
|
||||
catalogState.connectionState === "offline" ||
|
||||
catalogState.connectionState === "error") &&
|
||||
!catalogState.hasLoadedShellSnapshot
|
||||
) {
|
||||
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
|
||||
return {
|
||||
title: "Environment unavailable",
|
||||
detail:
|
||||
@@ -69,9 +63,8 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
}
|
||||
|
||||
export default function NewTaskRoute() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { projects, state: catalogState, threads } = useRemoteCatalog();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
@@ -190,10 +183,15 @@ export default function NewTaskRoute() {
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={item.environmentId}
|
||||
size={20}
|
||||
projectTitle={item.title}
|
||||
httpBaseUrl={
|
||||
savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null
|
||||
}
|
||||
workspaceRoot={item.workspaceRoot}
|
||||
bearerToken={
|
||||
savedConnectionsById[item.environmentId]?.bearerToken ?? null
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
|
||||
|
||||
export default ArchivedThreadsRouteScreen;
|
||||
@@ -1,38 +1,32 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPhase,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Switch,
|
||||
type NativeSyntheticEvent,
|
||||
type TextLayoutEventData,
|
||||
View,
|
||||
} from "react-native";
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
|
||||
import {
|
||||
type RelayEnvironmentView,
|
||||
useConnectionController,
|
||||
} from "../../features/connection/useConnectionController";
|
||||
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
|
||||
import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation";
|
||||
hasCloudPublicConfig,
|
||||
resolveRelayClerkTokenOptions,
|
||||
} from "../../features/cloud/publicConfig";
|
||||
import {
|
||||
useManagedRelayEnvironments,
|
||||
useManagedRelayEnvironmentStatus,
|
||||
} from "../../features/cloud/managedRelayState";
|
||||
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
|
||||
import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot";
|
||||
import { splitEnvironmentSections } from "../../features/connection/environmentSections";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
connectSavedEnvironment,
|
||||
useRemoteConnections,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
|
||||
export default function SettingsEnvironmentsRouteScreen() {
|
||||
const {
|
||||
@@ -43,11 +37,7 @@ export default function SettingsEnvironmentsRouteScreen() {
|
||||
} = useRemoteConnections();
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
|
||||
connectedEnvironments,
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
const hasLocalEnvironments = localEnvironments.length > 0;
|
||||
const hasEnvironments = connectedEnvironments.length > 0;
|
||||
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
@@ -79,9 +69,9 @@ export default function SettingsEnvironmentsRouteScreen() {
|
||||
paddingTop: 16,
|
||||
}}
|
||||
>
|
||||
{hasLocalEnvironments ? (
|
||||
{hasEnvironments ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{localEnvironments.map((environment, index) => (
|
||||
{connectedEnvironments.map((environment, index) => (
|
||||
<View
|
||||
key={environment.environmentId}
|
||||
collapsable={false}
|
||||
@@ -118,43 +108,54 @@ export default function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() ? (
|
||||
<ConfiguredCloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
/>
|
||||
) : null}
|
||||
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredCloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
}) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
function ConfiguredCloudEnvironmentRows() {
|
||||
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const cloudEnvironmentsState = useManagedRelayEnvironments();
|
||||
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
const availableCloudEnvironments = useMemo(
|
||||
() =>
|
||||
(cloudEnvironmentsState.data ?? []).filter(
|
||||
(environment) => savedConnectionsById[environment.environmentId] === undefined,
|
||||
),
|
||||
[cloudEnvironmentsState.data, savedConnectionsById],
|
||||
);
|
||||
|
||||
const handleConnectCloudEnvironment = useCallback(
|
||||
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
|
||||
[controller],
|
||||
async (environment: RelayClientEnvironmentRecord) => {
|
||||
setConnectingCloudEnvironmentId(environment.environmentId);
|
||||
try {
|
||||
const token = await getToken(resolveRelayClerkTokenOptions());
|
||||
if (!token) {
|
||||
throw new Error("Sign in to T3 Cloud before connecting.");
|
||||
}
|
||||
await mobileRuntime.runPromise(
|
||||
connectCloudEnvironment({
|
||||
clerkToken: token,
|
||||
environment,
|
||||
}).pipe(Effect.flatMap(connectSavedEnvironment)),
|
||||
);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Connect failed",
|
||||
error instanceof Error ? error.message : "Could not connect to this environment.",
|
||||
);
|
||||
} finally {
|
||||
setConnectingCloudEnvironmentId(null);
|
||||
}
|
||||
},
|
||||
[getToken],
|
||||
);
|
||||
|
||||
const handleDisconnectCloudEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
|
||||
[controller],
|
||||
);
|
||||
|
||||
const handleToggleCloudError = useCallback((environmentId: string) => {
|
||||
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
|
||||
}, []);
|
||||
|
||||
if (!isSignedIn) return null;
|
||||
|
||||
return (
|
||||
@@ -163,13 +164,11 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
disabled={cloudEnvironmentsState.isPending}
|
||||
onPress={cloudEnvironmentsState.refresh}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
{cloudEnvironmentsState.isPending ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
|
||||
@@ -177,48 +176,33 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{hasCloudRows ? (
|
||||
{availableCloudEnvironments.length > 0 ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{props.connectedCloudEnvironments.map((environment, index) => (
|
||||
<ConnectedCloudEnvironmentRow
|
||||
{availableCloudEnvironments.map((environment, index) => (
|
||||
<CloudEnvironmentRow
|
||||
key={environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={index !== 0}
|
||||
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
|
||||
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
|
||||
errorExpanded={expandedErrorId === environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
{availableCloudEnvironments.map((environment, index) => (
|
||||
<CloudEnvironmentRow
|
||||
key={environment.environment.environmentId}
|
||||
environment={environment}
|
||||
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
|
||||
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
|
||||
onConnect={() => handleConnectCloudEnvironment(environment)}
|
||||
errorExpanded={expandedErrorId === environment.environment.environmentId}
|
||||
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : controller.relayDiscovery.isRefreshing ? (
|
||||
) : cloudEnvironmentsState.data === null ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
|
||||
<ActivityIndicator color={iconColor} />
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : controller.relayDiscovery.error ? (
|
||||
) : cloudEnvironmentsState.error ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">
|
||||
Could not load T3 Cloud environments
|
||||
</Text>
|
||||
<Text className="text-[13px] leading-[18px] text-foreground-muted">
|
||||
{controller.relayDiscovery.error}
|
||||
{cloudEnvironmentsState.error}
|
||||
</Text>
|
||||
{controller.relayDiscovery.errorTraceId ? (
|
||||
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
@@ -231,124 +215,23 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedCloudEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onDisconnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={props.environment.connectionError}
|
||||
connectionErrorTraceId={props.environment.connectionErrorTraceId}
|
||||
connectionState={props.environment.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environmentLabel}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
return;
|
||||
}
|
||||
props.onDisconnect();
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
value={props.environment.connectionState !== "available"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRow(props: {
|
||||
readonly environment: RelayEnvironmentView;
|
||||
readonly environment: RelayClientEnvironmentRecord;
|
||||
readonly borderTop: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly isConnecting: boolean;
|
||||
readonly onConnect: () => void;
|
||||
readonly onToggleError: () => void;
|
||||
}) {
|
||||
const presentation = availableCloudEnvironmentPresentation({
|
||||
isStatusPending: props.environment.availability === "checking",
|
||||
status: props.environment.status,
|
||||
statusError: props.environment.error,
|
||||
statusErrorTraceId: props.environment.traceId,
|
||||
});
|
||||
|
||||
return (
|
||||
<CloudEnvironmentRowShell
|
||||
borderTop={props.borderTop}
|
||||
connectionError={presentation.connectionError}
|
||||
connectionErrorTraceId={presentation.connectionErrorTraceId}
|
||||
connectionState={presentation.connectionState}
|
||||
errorExpanded={props.errorExpanded}
|
||||
label={props.environment.environment.label}
|
||||
onValueChange={(enabled) => {
|
||||
if (enabled) {
|
||||
props.onConnect();
|
||||
}
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
statusText={presentation.statusText}
|
||||
value={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowShell(props: {
|
||||
readonly borderTop: boolean;
|
||||
readonly connectionError: string | null;
|
||||
readonly connectionErrorTraceId: string | null;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
readonly disabled?: boolean;
|
||||
readonly errorExpanded: boolean;
|
||||
readonly label: string;
|
||||
readonly onToggleError: () => void;
|
||||
readonly onValueChange: (enabled: boolean) => void;
|
||||
readonly statusText?: string;
|
||||
readonly value: boolean;
|
||||
}) {
|
||||
const activeTrack = String(useThemeColor("--color-switch-active"));
|
||||
const track = String(useThemeColor("--color-secondary-border"));
|
||||
const chevron = useThemeColor("--color-chevron");
|
||||
const isRetrying =
|
||||
props.connectionState === "connecting" || props.connectionState === "reconnecting";
|
||||
const shouldPulse = isRetrying;
|
||||
const mutedColor = useThemeColor("--color-icon-muted");
|
||||
const statusState = useManagedRelayEnvironmentStatus(props.environment);
|
||||
const status = statusState.data;
|
||||
const disabled = props.isConnecting;
|
||||
const statusText =
|
||||
props.statusText ??
|
||||
connectionStatusText({
|
||||
phase: props.connectionState,
|
||||
error: props.connectionError,
|
||||
traceId: props.connectionErrorTraceId,
|
||||
});
|
||||
const statusClassName = props.connectionError
|
||||
? "text-rose-500 dark:text-rose-400"
|
||||
: "text-foreground-muted";
|
||||
const [errorMeasurement, setErrorMeasurement] = useState<{
|
||||
readonly text: string;
|
||||
readonly lineCount: number;
|
||||
} | null>(null);
|
||||
const errorTraceId = props.connectionErrorTraceId;
|
||||
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
|
||||
const errorLineCount =
|
||||
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
|
||||
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
|
||||
const isErrorExpanded = errorCanExpand && props.errorExpanded;
|
||||
const StatusContainer = errorCanExpand ? Pressable : View;
|
||||
const onMeasuredErrorTextLayout = useCallback(
|
||||
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
|
||||
if (!props.connectionError) {
|
||||
return;
|
||||
}
|
||||
const nextLineCount = event.nativeEvent.lines.length;
|
||||
setErrorMeasurement((currentMeasurement) =>
|
||||
currentMeasurement?.text === measuredErrorText &&
|
||||
currentMeasurement.lineCount === nextLineCount
|
||||
? currentMeasurement
|
||||
: { text: measuredErrorText, lineCount: nextLineCount },
|
||||
);
|
||||
},
|
||||
[measuredErrorText, props.connectionError],
|
||||
);
|
||||
status === null
|
||||
? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable"))
|
||||
: status.status === "online"
|
||||
? "Online"
|
||||
: (status.error ?? "Offline");
|
||||
|
||||
return (
|
||||
<View
|
||||
collapsable={false}
|
||||
@@ -357,96 +240,36 @@ function CloudEnvironmentRowShell(props: {
|
||||
props.borderTop && "border-t border-border",
|
||||
)}
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<View className="min-w-0 flex-row items-center gap-2">
|
||||
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
|
||||
<Text
|
||||
className="min-w-0 flex-shrink text-[16px] font-t3-bold leading-[21px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</View>
|
||||
{props.connectionError ? (
|
||||
<Text
|
||||
aria-hidden
|
||||
className={cn("absolute left-0 right-0 text-[12px] leading-[16px]", statusClassName)}
|
||||
onTextLayout={onMeasuredErrorTextLayout}
|
||||
style={{ opacity: 0, zIndex: -1 }}
|
||||
>
|
||||
{measuredErrorText}
|
||||
</Text>
|
||||
) : null}
|
||||
<StatusContainer
|
||||
{...(errorCanExpand
|
||||
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
|
||||
: {})}
|
||||
className="min-w-0 flex-row items-start gap-1"
|
||||
>
|
||||
<Text
|
||||
className={cn("min-w-0 flex-1 text-[12px] leading-[16px]", statusClassName)}
|
||||
numberOfLines={isErrorExpanded ? undefined : 1}
|
||||
>
|
||||
{statusText}
|
||||
{errorTraceId ? (
|
||||
<>
|
||||
{" Trace ID: "}
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className={cn("text-[12px] leading-[16px] underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
style={{ textDecorationStyle: "dotted" }}
|
||||
>
|
||||
{errorTraceId}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
{errorCanExpand ? (
|
||||
<SymbolView
|
||||
name="chevron.down"
|
||||
size={10}
|
||||
tintColor={chevron}
|
||||
type="monochrome"
|
||||
style={{
|
||||
marginTop: 3,
|
||||
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</StatusContainer>
|
||||
<View className="h-9 w-9 items-center justify-center rounded-[14px] bg-subtle">
|
||||
<SymbolView
|
||||
name="cloud"
|
||||
size={17}
|
||||
tintColor={mutedColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</View>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
onValueChange={props.onValueChange}
|
||||
trackColor={{ false: track, true: activeTrack }}
|
||||
value={props.value}
|
||||
/>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
|
||||
{props.environment.label}
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{props.environment.endpoint.httpBaseUrl}
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{statusText}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={disabled}
|
||||
onPress={props.onConnect}
|
||||
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
{props.isConnecting ? "Connecting" : "Connect"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.traceId);
|
||||
}}
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="text-[12px] font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -8,13 +8,6 @@ import type { ComponentProps, ReactNode } from "react";
|
||||
import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
|
||||
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
|
||||
@@ -25,10 +18,10 @@ import {
|
||||
hasCloudPublicConfig,
|
||||
resolveRelayClerkTokenOptions,
|
||||
} from "../../features/cloud/publicConfig";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import { loadPreferences } from "../../lib/storage";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
|
||||
|
||||
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
|
||||
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
|
||||
@@ -39,7 +32,7 @@ export default function SettingsRouteScreen() {
|
||||
|
||||
function LocalSettingsRouteScreen() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const environmentCount = Object.keys(savedConnectionsById).length;
|
||||
|
||||
return (
|
||||
@@ -65,8 +58,6 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -79,7 +70,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
|
||||
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
|
||||
|
||||
@@ -96,13 +87,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
setNotificationStatus("unsupported");
|
||||
return;
|
||||
}
|
||||
const result = await settlePromise(() => Notifications.getPermissionsAsync());
|
||||
if (result._tag === "Failure") {
|
||||
reportAtomCommandResult(result, { label: "notification permission refresh" });
|
||||
setNotificationStatus("disabled");
|
||||
return;
|
||||
}
|
||||
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
|
||||
const permission = await Notifications.getPermissionsAsync();
|
||||
setNotificationStatus(permission.granted ? "enabled" : "disabled");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -118,66 +104,60 @@ function ConfiguredSettingsRouteScreen() {
|
||||
setLiveActivityStatus("signed-out");
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const result = await settlePromise(() => loadPreferences());
|
||||
if (result._tag === "Failure") {
|
||||
reportAtomCommandResult(result, { label: "live activity preference load" });
|
||||
void loadPreferences().then(
|
||||
(preferences) => {
|
||||
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled");
|
||||
},
|
||||
() => {
|
||||
setLiveActivityStatus("enabled");
|
||||
return;
|
||||
}
|
||||
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
|
||||
})();
|
||||
},
|
||||
);
|
||||
}, [isLoaded, isSignedIn]);
|
||||
|
||||
const requestNotifications = useCallback(async () => {
|
||||
const result = await settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
try {
|
||||
const result = await mobileRuntime.runPromise(
|
||||
requestAgentNotificationPermission.pipe(
|
||||
Effect.tap((permission) =>
|
||||
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
);
|
||||
if (result.type === "granted") {
|
||||
setNotificationStatus("enabled");
|
||||
Alert.alert(
|
||||
"Notifications enabled",
|
||||
"Live Activity notifications are enabled for this device.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (result.type === "unsupported") {
|
||||
setNotificationStatus("unsupported");
|
||||
Alert.alert(
|
||||
"Notifications unavailable",
|
||||
error instanceof Error ? error.message : "Could not request notification permission.",
|
||||
"Live Activity notifications are only available on iOS.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setNotificationStatus("disabled");
|
||||
if (result.canAskAgain) {
|
||||
Alert.alert("Notifications disabled", "Notifications were not enabled.");
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.value.type === "granted") {
|
||||
setNotificationStatus("enabled");
|
||||
Alert.alert(
|
||||
"Notifications enabled",
|
||||
"Live Activity notifications are enabled for this device.",
|
||||
"Notifications disabled",
|
||||
"Notifications were denied for this app. Open Settings to enable them.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (result.value.type === "unsupported") {
|
||||
setNotificationStatus("unsupported");
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Notifications unavailable",
|
||||
"Live Activity notifications are only available on iOS.",
|
||||
error instanceof Error ? error.message : "Could not request notification permission.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setNotificationStatus("disabled");
|
||||
if (result.value.canAskAgain) {
|
||||
Alert.alert("Notifications disabled", "Notifications were not enabled.");
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"Notifications disabled",
|
||||
"Notifications were denied for this app. Open Settings to enable them.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
|
||||
],
|
||||
);
|
||||
}, []);
|
||||
|
||||
const promptSignIn = useCallback(() => {
|
||||
@@ -198,51 +178,36 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
setLiveActivityStatus("linking");
|
||||
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
|
||||
if (tokenResult._tag === "Failure") {
|
||||
try {
|
||||
const token = await getToken(resolveRelayClerkTokenOptions());
|
||||
if (!token) {
|
||||
promptSignIn();
|
||||
setLiveActivityStatus("signed-out");
|
||||
return;
|
||||
}
|
||||
|
||||
await mobileRuntime.runPromise(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: true,
|
||||
clerkToken: token,
|
||||
connections,
|
||||
}),
|
||||
);
|
||||
refreshManagedRelayEnvironments();
|
||||
setLiveActivityStatus("enabled");
|
||||
Alert.alert(
|
||||
"Live Activities enabled",
|
||||
environmentCount > 0
|
||||
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
|
||||
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
|
||||
);
|
||||
} catch (error) {
|
||||
setLiveActivityStatus("disabled");
|
||||
const error = squashAtomCommandFailure(tokenResult);
|
||||
Alert.alert(
|
||||
"Live Activities unavailable",
|
||||
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!tokenResult.value) {
|
||||
promptSignIn();
|
||||
setLiveActivityStatus("signed-out");
|
||||
return;
|
||||
}
|
||||
|
||||
const updateResult = await settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: true,
|
||||
clerkToken: tokenResult.value,
|
||||
connections,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (updateResult._tag === "Failure") {
|
||||
setLiveActivityStatus("disabled");
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
const error = squashAtomCommandFailure(updateResult);
|
||||
Alert.alert(
|
||||
"Live Activities unavailable",
|
||||
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
refreshManagedRelayEnvironments();
|
||||
setLiveActivityStatus("enabled");
|
||||
Alert.alert(
|
||||
"Live Activities enabled",
|
||||
environmentCount > 0
|
||||
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
|
||||
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
|
||||
);
|
||||
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
|
||||
|
||||
const handleDeviceNotificationsChange = useCallback(
|
||||
@@ -269,36 +234,19 @@ function ConfiguredSettingsRouteScreen() {
|
||||
if (!enabled) {
|
||||
setLiveActivityStatus("disabled");
|
||||
void (async () => {
|
||||
let token: string | null = null;
|
||||
if (isSignedIn) {
|
||||
const tokenResult = await settlePromise(() =>
|
||||
getToken(resolveRelayClerkTokenOptions()),
|
||||
);
|
||||
if (tokenResult._tag === "Failure") {
|
||||
reportAtomCommandResult(tokenResult, {
|
||||
label: "live activity disable token lookup",
|
||||
});
|
||||
return;
|
||||
}
|
||||
token = tokenResult.value;
|
||||
}
|
||||
|
||||
const updateResult = await settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
try {
|
||||
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null;
|
||||
await mobileRuntime.runPromise(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: false,
|
||||
clerkToken: token,
|
||||
connections,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (updateResult._tag === "Failure") {
|
||||
reportAtomCommandResult(updateResult, {
|
||||
label: "live activity disable",
|
||||
});
|
||||
return;
|
||||
);
|
||||
refreshManagedRelayEnvironments();
|
||||
} catch {
|
||||
// The switch is optimistic; a future refresh reconciles relay state.
|
||||
}
|
||||
refreshManagedRelayEnvironments();
|
||||
})();
|
||||
return;
|
||||
}
|
||||
@@ -376,8 +324,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -420,20 +366,12 @@ function AppSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
function ArchivedThreadsSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="Threads">
|
||||
<SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsRow(props: {
|
||||
readonly disabled?: boolean;
|
||||
readonly icon: SymbolName;
|
||||
readonly label: string;
|
||||
readonly value?: string;
|
||||
readonly href?: "/settings/archive" | "/settings/environments";
|
||||
readonly href?: "/settings/environments";
|
||||
readonly onPress?: () => void;
|
||||
}) {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
@@ -444,20 +382,15 @@ function SettingsRow(props: {
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="shrink-0 text-[17px] text-foreground" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
<View className="min-w-0 flex-1 items-end">
|
||||
{props.value ? (
|
||||
<Text
|
||||
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.value}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
|
||||
{props.value ? (
|
||||
<Text
|
||||
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.value}
|
||||
</Text>
|
||||
) : null}
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={16}
|
||||
@@ -471,9 +404,7 @@ function SettingsRow(props: {
|
||||
if (props.href) {
|
||||
return (
|
||||
<Link href={props.href} asChild>
|
||||
<Pressable accessibilityLabel={props.label} accessibilityRole="button">
|
||||
{content}
|
||||
</Pressable>
|
||||
<Pressable>{content}</Pressable>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,32 +55,6 @@ export default function ThreadLayout() {
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/index"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/[...path]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "File",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review-comment"
|
||||
options={{
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFileRoute() {
|
||||
return <ThreadFileScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFilesIndexRoute() {
|
||||
return <ThreadFilesTreeScreen />;
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
cancelAnimation,
|
||||
Easing,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withRepeat,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
const INDICATOR_WIDTH_FRACTION = 0.3;
|
||||
const MIN_INDICATOR_WIDTH = 48;
|
||||
|
||||
function LoadingStripFrame(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly onLayout?: (width: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
accessibilityElementsHidden
|
||||
importantForAccessibility="no-hide-descendants"
|
||||
className="absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden"
|
||||
onLayout={
|
||||
props.onLayout
|
||||
? (event) => {
|
||||
props.onLayout?.(event.nativeEvent.layout.width);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function IndeterminateLoadingStrip() {
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const travelProgress = useSharedValue(0);
|
||||
const indicatorWidth = Math.max(MIN_INDICATOR_WIDTH, containerWidth * INDICATOR_WIDTH_FRACTION);
|
||||
|
||||
useEffect(() => {
|
||||
travelProgress.value = 0;
|
||||
travelProgress.value = withRepeat(
|
||||
withTiming(1, {
|
||||
duration: 1100,
|
||||
easing: Easing.inOut(Easing.quad),
|
||||
}),
|
||||
-1,
|
||||
false,
|
||||
);
|
||||
|
||||
return () => {
|
||||
cancelAnimation(travelProgress);
|
||||
};
|
||||
}, [travelProgress]);
|
||||
|
||||
const indicatorStyle = useAnimatedStyle(
|
||||
() => ({
|
||||
transform: [
|
||||
{
|
||||
translateX: (containerWidth + indicatorWidth) * travelProgress.value - indicatorWidth,
|
||||
},
|
||||
],
|
||||
width: indicatorWidth,
|
||||
}),
|
||||
[containerWidth, indicatorWidth],
|
||||
);
|
||||
|
||||
return (
|
||||
<LoadingStripFrame onLayout={setContainerWidth}>
|
||||
<Animated.View className="h-full rounded-full bg-primary" style={indicatorStyle} />
|
||||
</LoadingStripFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoadingStrip(props: { readonly progress?: number }) {
|
||||
if (props.progress === undefined) {
|
||||
return <IndeterminateLoadingStrip />;
|
||||
}
|
||||
|
||||
const clampedProgress = Math.min(1, Math.max(0, props.progress));
|
||||
|
||||
return (
|
||||
<LoadingStripFrame>
|
||||
<View
|
||||
className="h-full rounded-r-full bg-primary"
|
||||
style={{ width: `${clampedProgress * 100}%` }}
|
||||
/>
|
||||
</LoadingStripFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,86 +1,65 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useState } from "react";
|
||||
import { Image, View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
|
||||
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
|
||||
const loadedFaviconUrls = new Set<string>();
|
||||
|
||||
/* ─── Component ──────────────────────────────────────────────────────── */
|
||||
export function ProjectFavicon(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly size?: number;
|
||||
readonly projectTitle: string;
|
||||
readonly httpBaseUrl?: string | null;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly bearerToken?: string | null;
|
||||
}) {
|
||||
const size = props.size ?? 42;
|
||||
const faviconUrl = useAssetUrl(
|
||||
props.environmentId,
|
||||
props.workspaceRoot === null || props.workspaceRoot === undefined
|
||||
? null
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={faviconUrl}
|
||||
faviconUrl={faviconUrl}
|
||||
projectTitle={props.projectTitle}
|
||||
size={size}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectFaviconImage(props: {
|
||||
readonly faviconUrl: string | null;
|
||||
readonly projectTitle: string;
|
||||
readonly size: number;
|
||||
}) {
|
||||
const iconMuted = useThemeColor("--color-icon-subtle");
|
||||
|
||||
const faviconUrl =
|
||||
props.httpBaseUrl && props.workspaceRoot
|
||||
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
|
||||
: null;
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
|
||||
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
const showImage = props.faviconUrl !== null && status === "loaded";
|
||||
const showImage = faviconUrl && status === "loaded";
|
||||
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: props.size,
|
||||
height: props.size,
|
||||
width: size,
|
||||
height: size,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{/* Folder icon fallback (matches web's FolderIcon) */}
|
||||
{!showImage ? (
|
||||
<SymbolView
|
||||
name="folder.fill"
|
||||
size={props.size * 0.78}
|
||||
tintColor={iconMuted}
|
||||
type="monochrome"
|
||||
/>
|
||||
<SymbolView name="folder.fill" size={size * 0.78} tintColor={iconMuted} type="monochrome" />
|
||||
) : null}
|
||||
|
||||
{/* Favicon image (hidden until loaded) */}
|
||||
{props.faviconUrl ? (
|
||||
{faviconUrl ? (
|
||||
<Image
|
||||
source={{
|
||||
uri: props.faviconUrl,
|
||||
uri: faviconUrl,
|
||||
...(props.bearerToken
|
||||
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
|
||||
: {}),
|
||||
}}
|
||||
accessibilityLabel={`${props.projectTitle} favicon`}
|
||||
style={{
|
||||
width: props.size,
|
||||
height: props.size,
|
||||
borderRadius: props.size * 0.16,
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: size * 0.16,
|
||||
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
|
||||
}}
|
||||
resizeMode="contain"
|
||||
onLoad={() => {
|
||||
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
|
||||
if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
|
||||
setStatus("loaded");
|
||||
}}
|
||||
onError={() => setStatus("error")}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import {
|
||||
ConnectionCatalogDocument,
|
||||
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
|
||||
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
|
||||
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => catalogError("decode", cause),
|
||||
});
|
||||
return yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
|
||||
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
|
||||
});
|
||||
|
||||
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
|
||||
catalog: ConnectionCatalogDocumentType,
|
||||
) {
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
|
||||
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
|
||||
return JSON.stringify(encoded);
|
||||
});
|
||||
|
||||
interface CatalogStore {
|
||||
readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
|
||||
readonly update: (
|
||||
transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
|
||||
) => Effect.Effect<void, ConnectionTransientError>;
|
||||
}
|
||||
|
||||
export interface SecureCatalogStorage {
|
||||
readonly getItem: (key: string) => Effect.Effect<string | null, ConnectionTransientError>;
|
||||
readonly setItem: (key: string, value: string) => Effect.Effect<void, ConnectionTransientError>;
|
||||
readonly deleteItem: (key: string) => Effect.Effect<void, ConnectionTransientError>;
|
||||
}
|
||||
|
||||
export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* (
|
||||
storage: SecureCatalogStorage,
|
||||
) {
|
||||
const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
|
||||
const lock = yield* Semaphore.make(1);
|
||||
|
||||
const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () {
|
||||
const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
|
||||
const catalog =
|
||||
legacyRaw === null || legacyRaw.trim() === ""
|
||||
? EMPTY_CONNECTION_CATALOG_DOCUMENT
|
||||
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
|
||||
Effect.mapError((cause) => catalogError("migrate", cause)),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
|
||||
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (legacyRaw !== null && legacyRaw.trim() !== "") {
|
||||
const encoded = yield* encodeCatalog(catalog);
|
||||
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
|
||||
yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);
|
||||
}
|
||||
return catalog;
|
||||
});
|
||||
|
||||
const loadUnlocked = Effect.fn("mobile.connectionStorage.loadCatalog")(function* () {
|
||||
const cached = yield* Ref.get(state);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
|
||||
let catalog: ConnectionCatalogDocumentType;
|
||||
if (raw !== null && raw.trim() !== "") {
|
||||
catalog = yield* decodeCatalog(raw).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
catalog = yield* loadLegacyCatalog();
|
||||
}
|
||||
yield* Ref.set(state, Option.some(catalog));
|
||||
return catalog;
|
||||
});
|
||||
|
||||
const read = lock.withPermits(1)(loadUnlocked());
|
||||
const update: CatalogStore["update"] = Effect.fn("mobile.connectionStorage.updateCatalog")(
|
||||
function* (transform) {
|
||||
yield* lock.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const next = transform(yield* loadUnlocked());
|
||||
const encoded = yield* encodeCatalog(next);
|
||||
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
|
||||
yield* Ref.set(state, Option.some(next));
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return { read, update } satisfies CatalogStore;
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
import { createEnvironmentCatalogAtoms } from "@t3tools/client-runtime/state/connections";
|
||||
|
||||
import { connectionAtomRuntime } from "./runtime";
|
||||
|
||||
export const environmentCatalog = createEnvironmentCatalogAtoms(connectionAtomRuntime);
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
|
||||
describe("migrateLegacyConnectionCatalog", () => {
|
||||
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
|
||||
Effect.gen(function* () {
|
||||
const bearerEnvironmentId = EnvironmentId.make("bearer-environment");
|
||||
const relayEnvironmentId = EnvironmentId.make("relay-environment");
|
||||
const catalog = yield* migrateLegacyConnectionCatalog(
|
||||
JSON.stringify({
|
||||
connections: [
|
||||
{
|
||||
environmentId: bearerEnvironmentId,
|
||||
environmentLabel: "Local Mac",
|
||||
pairingUrl: "https://local.example.test/pair",
|
||||
displayUrl: "https://local.example.test",
|
||||
httpBaseUrl: "https://local.example.test",
|
||||
wsBaseUrl: "wss://local.example.test",
|
||||
bearerToken: "bearer-token",
|
||||
authenticationMethod: "bearer",
|
||||
},
|
||||
{
|
||||
environmentId: relayEnvironmentId,
|
||||
environmentLabel: "Cloud Mac",
|
||||
pairingUrl: "https://relay.example.test",
|
||||
displayUrl: "https://relay.example.test",
|
||||
httpBaseUrl: "https://relay.example.test",
|
||||
wsBaseUrl: "wss://relay.example.test",
|
||||
bearerToken: null,
|
||||
authenticationMethod: "dpop",
|
||||
relayManaged: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(catalog.targets).toHaveLength(2);
|
||||
expect(
|
||||
catalog.targets.find((target) => target.environmentId === bearerEnvironmentId)?._tag,
|
||||
).toBe("BearerConnectionTarget");
|
||||
expect(
|
||||
catalog.targets.find((target) => target.environmentId === relayEnvironmentId)?._tag,
|
||||
).toBe("RelayConnectionTarget");
|
||||
expect(catalog.profiles).toHaveLength(1);
|
||||
expect(catalog.credentials).toHaveLength(1);
|
||||
expect(catalog.credentials[0]?.credential).toMatchObject({
|
||||
_tag: "BearerConnectionCredential",
|
||||
token: "bearer-token",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops invalid legacy bearer entries without credentials", () =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* migrateLegacyConnectionCatalog(
|
||||
JSON.stringify({
|
||||
connections: [
|
||||
{
|
||||
environmentId: EnvironmentId.make("invalid-bearer"),
|
||||
environmentLabel: "Invalid",
|
||||
pairingUrl: "https://invalid.example.test/pair",
|
||||
displayUrl: "https://invalid.example.test",
|
||||
httpBaseUrl: "https://invalid.example.test",
|
||||
wsBaseUrl: "wss://invalid.example.test",
|
||||
bearerToken: null,
|
||||
authenticationMethod: "bearer",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(catalog.targets).toEqual([]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionRegistration,
|
||||
RelayConnectionRegistration,
|
||||
RelayConnectionTarget,
|
||||
BearerConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
type ConnectionCatalogDocument,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
registerConnectionInCatalog,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const LegacySavedRemoteConnection = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
environmentLabel: Schema.String,
|
||||
pairingUrl: Schema.String,
|
||||
displayUrl: Schema.String,
|
||||
httpBaseUrl: Schema.String,
|
||||
wsBaseUrl: Schema.String,
|
||||
bearerToken: Schema.NullOr(Schema.String),
|
||||
authenticationMethod: Schema.optionalKey(Schema.Literals(["bearer", "dpop"])),
|
||||
dpopAccessToken: Schema.optionalKey(Schema.String),
|
||||
relayManaged: Schema.optionalKey(Schema.Literal(true)),
|
||||
});
|
||||
|
||||
const LegacyConnectionDocument = Schema.Struct({
|
||||
connections: Schema.optionalKey(Schema.Array(LegacySavedRemoteConnection)),
|
||||
});
|
||||
const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnectionDocument);
|
||||
|
||||
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
|
||||
"LegacyConnectionMigrationError",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
|
||||
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
|
||||
}
|
||||
|
||||
function migrateConnection(
|
||||
document: ConnectionCatalogDocument,
|
||||
connection: typeof LegacySavedRemoteConnection.Type,
|
||||
): ConnectionCatalogDocument {
|
||||
if (isRelayManaged(connection)) {
|
||||
return registerConnectionInCatalog(
|
||||
document,
|
||||
new RelayConnectionRegistration({
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (connection.bearerToken === null || connection.bearerToken.trim() === "") {
|
||||
return document;
|
||||
}
|
||||
|
||||
const connectionId = `bearer:${connection.environmentId}`;
|
||||
return registerConnectionInCatalog(
|
||||
document,
|
||||
new BearerConnectionRegistration({
|
||||
target: new BearerConnectionTarget({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
connectionId,
|
||||
}),
|
||||
profile: new BearerConnectionProfile({
|
||||
connectionId,
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
httpBaseUrl: connection.httpBaseUrl,
|
||||
wsBaseUrl: connection.wsBaseUrl,
|
||||
}),
|
||||
credential: new BearerConnectionCredential({
|
||||
token: connection.bearerToken,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const migrateLegacyConnectionCatalog = Effect.fn(
|
||||
"mobile.connectionMigration.migrateCatalog",
|
||||
)(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { ConnectionOnboarding } from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
createAtomCommandScheduler,
|
||||
createRuntimeCommand,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { connectionAtomRuntime } from "./runtime";
|
||||
|
||||
const onboardingScheduler = createAtomCommandScheduler();
|
||||
|
||||
export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {
|
||||
label: "mobile:connection:connect-pairing-url",
|
||||
scheduler: onboardingScheduler,
|
||||
concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },
|
||||
execute: (pairingUrl: string) =>
|
||||
ConnectionOnboarding.pipe(
|
||||
Effect.flatMap((onboarding) => onboarding.registerPairing({ pairingUrl })),
|
||||
),
|
||||
});
|
||||
|
||||
export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime, {
|
||||
label: "mobile:connection:update-bearer",
|
||||
scheduler: onboardingScheduler,
|
||||
concurrency: {
|
||||
mode: "serial",
|
||||
key: (input: { readonly environmentId: EnvironmentId }) => input.environmentId,
|
||||
},
|
||||
execute: (input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}) => ConnectionOnboarding.pipe(Effect.flatMap((onboarding) => onboarding.updateBearer(input))),
|
||||
});
|
||||
@@ -1,200 +0,0 @@
|
||||
import {
|
||||
ClientPresentation,
|
||||
CloudSession,
|
||||
EnvironmentOwnedDataCleanup,
|
||||
PlatformConnectionSource,
|
||||
RelayDeviceIdentity,
|
||||
SshEnvironmentGateway,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
ConnectionWakeups,
|
||||
Connectivity,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
|
||||
import { AuthStandardClientScopes } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Network from "expo-network";
|
||||
import { AppState } from "react-native";
|
||||
|
||||
import { authClientMetadata } from "../lib/authClientMetadata";
|
||||
import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
|
||||
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
|
||||
if (state.isConnected === false || state.isInternetReachable === false) {
|
||||
return "offline";
|
||||
}
|
||||
if (state.isConnected === true) {
|
||||
return "online";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const connectivityLayer = Layer.succeed(
|
||||
Connectivity,
|
||||
Connectivity.of({
|
||||
status: Effect.tryPromise({
|
||||
try: () => Network.getNetworkStateAsync(),
|
||||
catch: () => undefined,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => "unknown" as const,
|
||||
onSuccess: networkStatus,
|
||||
}),
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const wakeupsLayer = Layer.succeed(
|
||||
ConnectionWakeups,
|
||||
ConnectionWakeups.of({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const capabilitiesLayer = Layer.succeedContext(
|
||||
Context.make(
|
||||
CloudSession,
|
||||
CloudSession.of({
|
||||
clerkToken: Effect.gen(function* () {
|
||||
const session = appAtomRegistry.get(managedRelaySessionAtom);
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
message: "Sign in to T3 Cloud to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
message: "The T3 Cloud session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
}),
|
||||
}),
|
||||
).pipe(
|
||||
Context.add(
|
||||
RelayDeviceIdentity,
|
||||
RelayDeviceIdentity.of({
|
||||
deviceId: Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
),
|
||||
Context.add(
|
||||
ClientPresentation,
|
||||
ClientPresentation.of({
|
||||
metadata: authClientMetadata(),
|
||||
scopes: AuthStandardClientScopes,
|
||||
}),
|
||||
),
|
||||
Context.add(
|
||||
SshEnvironmentGateway,
|
||||
SshEnvironmentGateway.of({
|
||||
provision: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
prepare: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
disconnect: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const platformConnectionSourceLayer = Layer.succeed(
|
||||
PlatformConnectionSource,
|
||||
PlatformConnectionSource.of({
|
||||
registrations: Stream.empty,
|
||||
}),
|
||||
);
|
||||
|
||||
const environmentOwnedDataCleanupLayer = Layer.succeed(
|
||||
EnvironmentOwnedDataCleanup,
|
||||
EnvironmentOwnedDataCleanup.of({
|
||||
clear: (environmentId) =>
|
||||
Effect.all(
|
||||
[
|
||||
Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
|
||||
Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not clear mobile environment-owned data.", {
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectionPlatformLayer = Layer.mergeAll(
|
||||
connectionStorageLayer,
|
||||
connectivityLayer,
|
||||
wakeupsLayer,
|
||||
capabilitiesLayer,
|
||||
platformConnectionSourceLayer,
|
||||
environmentOwnedDataCleanupLayer,
|
||||
);
|
||||
@@ -1,16 +0,0 @@
|
||||
import { connectionLayer as clientConnectionLayer } from "@t3tools/client-runtime/connection";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { runtimeContextLayer } from "../lib/runtime";
|
||||
import { connectionPlatformLayer } from "./platform";
|
||||
|
||||
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
export const connectionLayer = clientConnectionLayer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
export const connectionAtomRuntime = Atom.runtime(connectionLayer);
|
||||
@@ -1,84 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import {
|
||||
CONNECTION_CATALOG_KEY,
|
||||
LEGACY_CONNECTIONS_KEY,
|
||||
makeCatalogStore,
|
||||
type SecureCatalogStorage,
|
||||
} from "./catalog-store";
|
||||
|
||||
function makeStorage(initial: Readonly<Record<string, string>>) {
|
||||
const values = new Map(Object.entries(initial));
|
||||
const deleted: Array<string> = [];
|
||||
const storage: SecureCatalogStorage = {
|
||||
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
|
||||
setItem: (key, value) =>
|
||||
Effect.sync(() => {
|
||||
values.set(key, value);
|
||||
}),
|
||||
deleteItem: (key) =>
|
||||
Effect.sync(() => {
|
||||
deleted.push(key);
|
||||
values.delete(key);
|
||||
}),
|
||||
};
|
||||
return { deleted, storage, values };
|
||||
}
|
||||
|
||||
describe("mobile connection catalog storage", () => {
|
||||
it.effect("recovers from a corrupt current catalog", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeStorage({
|
||||
[CONNECTION_CATALOG_KEY]: "{not-json",
|
||||
});
|
||||
const catalog = yield* makeCatalogStore(memory.storage);
|
||||
|
||||
expect((yield* catalog.read).targets).toEqual([]);
|
||||
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replaces and removes a corrupt legacy catalog", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeStorage({
|
||||
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }),
|
||||
});
|
||||
const catalog = yield* makeCatalogStore(memory.storage);
|
||||
|
||||
expect((yield* catalog.read).targets).toEqual([]);
|
||||
expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]);
|
||||
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to valid legacy data when the current catalog is corrupt", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeStorage({
|
||||
[CONNECTION_CATALOG_KEY]: "{not-json",
|
||||
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({
|
||||
connections: [
|
||||
{
|
||||
environmentId: "legacy-environment",
|
||||
environmentLabel: "Legacy",
|
||||
pairingUrl: "https://legacy.example.test/pair",
|
||||
displayUrl: "https://legacy.example.test",
|
||||
httpBaseUrl: "https://legacy.example.test",
|
||||
wsBaseUrl: "wss://legacy.example.test",
|
||||
bearerToken: "legacy-token",
|
||||
authenticationMethod: "bearer",
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const catalog = yield* makeCatalogStore(memory.storage);
|
||||
|
||||
expect((yield* catalog.read).targets).toHaveLength(1);
|
||||
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]);
|
||||
|
||||
yield* catalog.update((document) => document);
|
||||
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
|
||||
expect(memory.values.has(LEGACY_CONNECTIONS_KEY)).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,432 +0,0 @@
|
||||
import {
|
||||
ConnectionPersistenceError,
|
||||
ConnectionRegistrationStore,
|
||||
ConnectionTargetStore,
|
||||
EnvironmentCacheStore,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
removeCatalogValue,
|
||||
replaceCatalogValue,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { RemoteDpopAccessTokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionCredentialStore,
|
||||
ConnectionProfileStore,
|
||||
ConnectionTransientError,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
environmentId: EnvironmentId,
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
}
|
||||
|
||||
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
|
||||
function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(
|
||||
Paths.document,
|
||||
THREAD_SNAPSHOT_CACHE_DIRECTORY,
|
||||
encodeURIComponent(environmentId),
|
||||
);
|
||||
if (operation !== "clear-environment") {
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(
|
||||
yield* threadSnapshotDirectory(environmentId, operation),
|
||||
threadSnapshotFileName(threadId),
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
error: ConnectionTransientError,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(key),
|
||||
catch: (cause) => catalogError("load", cause),
|
||||
}),
|
||||
setItem: (key, value) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(key, value),
|
||||
catch: (cause) => catalogError("save", cause),
|
||||
}),
|
||||
deleteItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(key),
|
||||
catch: (cause) => catalogError("delete", cause),
|
||||
}),
|
||||
};
|
||||
|
||||
function shellSnapshotFileName(environmentId: EnvironmentId): string {
|
||||
return `${encodeURIComponent(environmentId)}.json`;
|
||||
}
|
||||
|
||||
const shellSnapshotFileInDirectory = Effect.fn(
|
||||
"mobile.connectionStorage.shellSnapshotFileInDirectory",
|
||||
)(function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-shell" | "save-shell" | "clear-environment",
|
||||
directoryName: string,
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, File, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, directoryName);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
const shellSnapshotFile = (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-shell" | "save-shell" | "clear-environment",
|
||||
) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
|
||||
|
||||
const legacyShellSnapshotFile = (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-shell" | "clear-environment",
|
||||
) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
|
||||
|
||||
export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* makeCatalogStore(secureCatalogStorage);
|
||||
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ConnectionProfileStore.of({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
Option.fromUndefinedOr(
|
||||
document.profiles.find((candidate) => candidate.connectionId === connectionId),
|
||||
),
|
||||
),
|
||||
),
|
||||
put: (profile) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
|
||||
})),
|
||||
remove: (connectionId) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
profiles: removeCatalogValue(
|
||||
document.profiles,
|
||||
(value) => value.connectionId,
|
||||
connectionId,
|
||||
),
|
||||
})),
|
||||
});
|
||||
const credentialStore = ConnectionCredentialStore.of({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
Option.fromUndefinedOr(
|
||||
document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
|
||||
),
|
||||
),
|
||||
),
|
||||
put: (connectionId, credential) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
|
||||
connectionId,
|
||||
credential,
|
||||
}),
|
||||
})),
|
||||
remove: (connectionId) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
credentials: removeCatalogValue(
|
||||
document.credentials,
|
||||
(value) => value.connectionId,
|
||||
connectionId,
|
||||
),
|
||||
})),
|
||||
});
|
||||
const remoteTokenStore = RemoteDpopAccessTokenStore.of({
|
||||
get: (environmentId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
Option.fromUndefinedOr(
|
||||
document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
|
||||
),
|
||||
),
|
||||
),
|
||||
put: (token) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
remoteDpopTokens: replaceCatalogValue(
|
||||
document.remoteDpopTokens,
|
||||
(value) => value.environmentId,
|
||||
token,
|
||||
),
|
||||
})),
|
||||
remove: (environmentId) =>
|
||||
catalog.update((document) => ({
|
||||
...document,
|
||||
remoteDpopTokens: removeCatalogValue(
|
||||
document.remoteDpopTokens,
|
||||
(value) => value.environmentId,
|
||||
environmentId,
|
||||
),
|
||||
})),
|
||||
});
|
||||
const cacheStore = EnvironmentCacheStore.of({
|
||||
loadShell: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "load-shell");
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}
|
||||
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
|
||||
if (!legacyFile.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "save-shell");
|
||||
const stored = {
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
|
||||
if (!file.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
}),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
environmentId,
|
||||
"clear-environment",
|
||||
);
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||
Context.add(ConnectionProfileStore, profileStore),
|
||||
Context.add(ConnectionCredentialStore, credentialStore),
|
||||
Context.add(RemoteDpopAccessTokenStore, remoteTokenStore),
|
||||
Context.add(EnvironmentCacheStore, cacheStore),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -2,8 +2,7 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
@@ -34,85 +33,90 @@ const connection: SavedRemoteConnection = {
|
||||
bearerToken: "local-bearer",
|
||||
};
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(ManagedRelayClient, null as never),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
);
|
||||
const runWithHttpClient = <A, E>(
|
||||
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>,
|
||||
): Promise<A> =>
|
||||
Effect.runPromise(
|
||||
effect.pipe(
|
||||
Effect.provideService(ManagedRelayClient, null as never),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("liveActivityPreferences", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it.effect("pushes disabled Live Activity preferences to relay registrations", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setLiveActivityUpdatesEnabled({
|
||||
it("pushes disabled Live Activity preferences to relay registrations", async () => {
|
||||
await runWithHttpClient(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: false,
|
||||
clerkToken: "clerk-token",
|
||||
connections: [connection],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("pushes enabled Live Activity preferences to relay registrations", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setLiveActivityUpdatesEnabled({
|
||||
it("pushes enabled Live Activity preferences to relay registrations", async () => {
|
||||
await runWithHttpClient(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: true,
|
||||
clerkToken: "clerk-token",
|
||||
connections: [connection],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps local preferences refreshable when signed out", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setLiveActivityUpdatesEnabled({
|
||||
it("keeps local preferences refreshable when signed out", async () => {
|
||||
await runWithHttpClient(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: false,
|
||||
clerkToken: null,
|
||||
connections: [connection],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
|
||||
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.effect("does not try to re-link managed relay connections without bearer credentials", () => {
|
||||
it("does not try to re-link managed relay connections without bearer credentials", async () => {
|
||||
const managedConnection: SavedRemoteConnection = {
|
||||
...connection,
|
||||
bearerToken: null,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* setLiveActivityUpdatesEnabled({
|
||||
await runWithHttpClient(
|
||||
setLiveActivityUpdatesEnabled({
|
||||
enabled: true,
|
||||
clerkToken: "clerk-token",
|
||||
connections: [connection, managedConnection],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
|
||||
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
|
||||
clerkToken: "clerk-token",
|
||||
connection,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime";
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { savePreferencesPatch } from "../../lib/storage";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
|
||||
|
||||
import type { Preferences } from "../../lib/storage";
|
||||
import type { MobilePreferences } from "../../lib/storage";
|
||||
|
||||
export function makeRelayDeviceRegistrationRequest(input: {
|
||||
readonly deviceId: string;
|
||||
@@ -10,7 +10,7 @@ export function makeRelayDeviceRegistrationRequest(input: {
|
||||
readonly pushToken?: string;
|
||||
readonly pushToStartToken?: string;
|
||||
readonly notificationsEnabled: boolean;
|
||||
readonly preferences: Preferences;
|
||||
readonly preferences: MobilePreferences;
|
||||
}): RelayDeviceRegistrationRequest {
|
||||
const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false;
|
||||
return {
|
||||
|
||||
@@ -6,16 +6,15 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import Constants from "expo-constants";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { type ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import type { ManagedRelayClient } from "@t3tools/client-runtime";
|
||||
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cryptoLayer } from "../cloud/dpop";
|
||||
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { mobileCryptoLayer } from "../cloud/dpop";
|
||||
import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import {
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
@@ -34,12 +33,6 @@ const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
const widgetMocks = vi.hoisted(() => ({
|
||||
getInstances: vi.fn(() => []),
|
||||
}));
|
||||
const backgroundRuntime = vi.hoisted(() => ({
|
||||
pending: [] as Array<{
|
||||
readonly operation: unknown;
|
||||
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
|
||||
}>,
|
||||
}));
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -102,11 +95,17 @@ vi.mock("react-native", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/runtime", () => ({
|
||||
runtime: {
|
||||
runPromiseExit: (operation: unknown) =>
|
||||
new Promise((resolve) => {
|
||||
backgroundRuntime.pending.push({ operation, resolve });
|
||||
}),
|
||||
mobileRuntime: {
|
||||
runPromise: <A, E>(operation: Effect.Effect<A, E>) =>
|
||||
Effect.runPromise(
|
||||
operation.pipe(
|
||||
Effect.provide(
|
||||
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
|
||||
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -139,40 +138,34 @@ function savedConnection(): SavedRemoteConnection {
|
||||
};
|
||||
}
|
||||
|
||||
const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pipe(
|
||||
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
|
||||
);
|
||||
const runRegistrationEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
|
||||
Effect.runPromise(
|
||||
effect.pipe(
|
||||
Effect.provide(
|
||||
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
|
||||
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
|
||||
function* () {
|
||||
let idlePasses = 0;
|
||||
for (;;) {
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
const pending = backgroundRuntime.pending.shift();
|
||||
if (!pending) {
|
||||
idlePasses++;
|
||||
if (idlePasses >= 3) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
idlePasses = 0;
|
||||
const exit = yield* Effect.exit(
|
||||
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
|
||||
);
|
||||
yield* Effect.sync(() => {
|
||||
pending.resolve(exit);
|
||||
});
|
||||
async function waitForFetchCalls(
|
||||
fetchMock: ReturnType<typeof vi.fn>,
|
||||
count: number,
|
||||
): Promise<void> {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
if (fetchMock.mock.calls.length >= count) {
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
beforeEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.stubGlobal("__DEV__", false);
|
||||
secureStore.clear();
|
||||
backgroundRuntime.pending.length = 0;
|
||||
Constants.expoConfig!.extra = {};
|
||||
__resetAgentAwarenessRemoteRegistrationForTest();
|
||||
widgetMocks.getInstances.mockReset();
|
||||
@@ -250,7 +243,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
|
||||
});
|
||||
|
||||
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
|
||||
it("registers at most one listener while a Live Activity push token is pending", async () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
const addPushTokenListener = vi.fn();
|
||||
const activity = {
|
||||
@@ -258,64 +251,56 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
addPushTokenListener,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
|
||||
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
|
||||
await expect(
|
||||
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
|
||||
).resolves.toBe(false);
|
||||
await expect(
|
||||
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
|
||||
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
|
||||
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"reports Live Activity token registration as skipped when relay auth is unavailable",
|
||||
() => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"registers APNS-started Live Activities for relay updates without mutating them locally",
|
||||
() => {
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
start: vi.fn(),
|
||||
update: vi.fn(),
|
||||
end: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* refreshActiveLiveActivityRemoteRegistration();
|
||||
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
expect(activity.start).not.toHaveBeenCalled();
|
||||
expect(activity.update).not.toHaveBeenCalled();
|
||||
expect(activity.end).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
|
||||
it("reports Live Activity token registration as skipped when relay auth is unavailable", async () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
|
||||
yield* refreshAgentAwarenessRegistration();
|
||||
await expect(
|
||||
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
it("registers APNS-started Live Activities for relay updates without mutating them locally", async () => {
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
|
||||
addPushTokenListener: vi.fn(),
|
||||
start: vi.fn(),
|
||||
update: vi.fn(),
|
||||
end: vi.fn(),
|
||||
};
|
||||
widgetMocks.getInstances.mockReturnValue([activity] as never);
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
await runRegistrationEffect(refreshActiveLiveActivityRemoteRegistration());
|
||||
|
||||
expect(activity.getPushToken).toHaveBeenCalled();
|
||||
expect(activity.start).not.toHaveBeenCalled();
|
||||
expect(activity.update).not.toHaveBeenCalled();
|
||||
expect(activity.end).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refreshes APNs registration for connected environments after settings changes", async () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
|
||||
|
||||
await runRegistrationEffect(refreshAgentAwarenessRegistration());
|
||||
|
||||
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.effect("registers the APNs device when cloud auth becomes available", () => {
|
||||
@@ -345,7 +330,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const [request, init] = fetchMock.mock.calls[1] as unknown as [
|
||||
@@ -372,65 +357,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
nowEpochSeconds: proofIat(dpop),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("coalesces simultaneous sign-in and environment connection registrations", () => {
|
||||
const fetchMock = vi.fn((request: RequestInfo | URL) => {
|
||||
const url = request instanceof Request ? request.url : String(request);
|
||||
return Promise.resolve(
|
||||
Response.json(
|
||||
url.endsWith("/v1/client/dpop-token")
|
||||
? {
|
||||
access_token: "relay-dpop-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 300,
|
||||
scope: "mobile:registration",
|
||||
}
|
||||
: { ok: true },
|
||||
),
|
||||
);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
|
||||
vi.mocked(Notifications.getPermissionsAsync).mockClear();
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(Notifications.getPermissionsAsync).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("continues queued device registration after a failed auth lookup", () => {
|
||||
Constants.expoConfig!.extra = {
|
||||
relay: {
|
||||
url: "https://relay.example.test/",
|
||||
},
|
||||
};
|
||||
|
||||
const tokenProvider = vi
|
||||
.fn<() => Promise<string | null>>()
|
||||
.mockRejectedValueOnce(new Error("auth unavailable"))
|
||||
.mockResolvedValue("clerk-token-user-a");
|
||||
setAgentAwarenessRelayTokenProvider(tokenProvider);
|
||||
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
|
||||
expect(tokenListener).toBeDefined();
|
||||
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
|
||||
expect(backgroundRuntime.pending).toHaveLength(0);
|
||||
expect(tokenProvider).toHaveBeenCalledTimes(2);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it("only registers again when the authenticated identity changes", () => {
|
||||
@@ -440,7 +367,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it.effect("registers rotated APNs tokens without rereading the native token", () => {
|
||||
it("registers rotated APNs tokens without rereading the native token", async () => {
|
||||
const fetchMock = vi.fn((request: RequestInfo | URL) => {
|
||||
const url = request instanceof Request ? request.url : String(request);
|
||||
return Promise.resolve(
|
||||
@@ -471,10 +398,9 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
expect(tokenListener).toBeDefined();
|
||||
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
@@ -506,13 +432,13 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
registerAgentAwarenessConnection(savedConnection());
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
return Effect.gen(function* () {
|
||||
yield* runBackgroundOperations();
|
||||
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
|
||||
fetchMock.mockClear();
|
||||
|
||||
unregisterAgentAwarenessConnection(savedConnection().environmentId);
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -8,16 +8,10 @@ import {
|
||||
type RelayDeviceRegistrationRequest,
|
||||
type RelayLiveActivityRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settleAsyncResult,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { ManagedRelayClient } from "@t3tools/client-runtime";
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import {
|
||||
loadAgentAwarenessDeviceId,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
@@ -35,20 +29,6 @@ let pushTokenSubscription: { remove: () => void } | null = null;
|
||||
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||
let relayTokenProvider: (() => Promise<string | null>) | null = null;
|
||||
let relayTokenProviderIdentity: string | null = null;
|
||||
let deviceRegistrationGeneration = 0;
|
||||
let activeDeviceRegistration: {
|
||||
readonly input: DeviceRegistrationInput;
|
||||
operation: Promise<void>;
|
||||
} | null = null;
|
||||
let pendingDeviceRegistration: {
|
||||
readonly input: DeviceRegistrationInput;
|
||||
readonly context: string;
|
||||
} | null = null;
|
||||
|
||||
interface DeviceRegistrationInput {
|
||||
readonly pushToStartToken?: string;
|
||||
readonly observedPushToken?: string;
|
||||
}
|
||||
|
||||
export function normalizeAgentAwarenessRelayBaseUrl(
|
||||
value: string | null | undefined,
|
||||
@@ -88,11 +68,6 @@ export function setAgentAwarenessRelayTokenProvider(
|
||||
const isExistingIdentity =
|
||||
provider !== null &&
|
||||
!shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
|
||||
if (!isExistingIdentity) {
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
}
|
||||
relayTokenProvider = provider;
|
||||
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
|
||||
if (!provider) {
|
||||
@@ -115,7 +90,7 @@ export function setAgentAwarenessRelayTokenProvider(
|
||||
if (isExistingIdentity) {
|
||||
return;
|
||||
}
|
||||
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
|
||||
runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed");
|
||||
}
|
||||
|
||||
function iosMajorVersion(): number {
|
||||
@@ -174,41 +149,20 @@ const relayToken = Effect.gen(function* () {
|
||||
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
expectedGeneration: number,
|
||||
): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled before relay request", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* relayToken;
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled after auth lookup", {
|
||||
expectedGeneration,
|
||||
currentGeneration: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay device registration skipped; user is not signed in");
|
||||
return;
|
||||
}
|
||||
|
||||
const client = yield* ManagedRelayClient;
|
||||
logRegistrationDebug("relay device registration request started", {
|
||||
expectedGeneration,
|
||||
});
|
||||
yield* client.registerDevice({
|
||||
clerkToken: token,
|
||||
payload: body,
|
||||
});
|
||||
logRegistrationDebug("relay device registration request completed", {
|
||||
expectedGeneration,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -259,11 +213,10 @@ function logRegistrationError(context: string, error: unknown): void {
|
||||
if (!__DEV__) {
|
||||
return;
|
||||
}
|
||||
console.warn(`[agent-awareness] ${context}`, {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
traceId: findErrorTraceId(error),
|
||||
error,
|
||||
});
|
||||
console.warn(
|
||||
`[agent-awareness] ${context}`,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
function logRegistrationDebug(context: string, details?: unknown): void {
|
||||
@@ -277,107 +230,20 @@ function runRegistrationInBackground(
|
||||
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
|
||||
context: string,
|
||||
): void {
|
||||
void (async () => {
|
||||
const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
logRegistrationError(context, squashAtomCommandFailure(result));
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function mergeDeviceRegistrationInput(
|
||||
current: DeviceRegistrationInput,
|
||||
next: DeviceRegistrationInput,
|
||||
): DeviceRegistrationInput {
|
||||
return {
|
||||
...((next.pushToStartToken ?? current.pushToStartToken)
|
||||
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
|
||||
: {}),
|
||||
...((next.observedPushToken ?? current.observedPushToken)
|
||||
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function registrationAddsInformation(
|
||||
current: DeviceRegistrationInput,
|
||||
next: DeviceRegistrationInput,
|
||||
): boolean {
|
||||
return (
|
||||
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
|
||||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
|
||||
);
|
||||
}
|
||||
|
||||
function startPendingDeviceRegistration(): void {
|
||||
if (activeDeviceRegistration || !pendingDeviceRegistration) {
|
||||
return;
|
||||
}
|
||||
|
||||
const next = pendingDeviceRegistration;
|
||||
pendingDeviceRegistration = null;
|
||||
const generation = deviceRegistrationGeneration;
|
||||
logRegistrationDebug("device registration started", {
|
||||
generation,
|
||||
hasObservedPushToken: next.input.observedPushToken !== undefined,
|
||||
hasPushToStartToken: next.input.pushToStartToken !== undefined,
|
||||
void mobileRuntime.runPromise(operation).catch((error: unknown) => {
|
||||
logRegistrationError(context, error);
|
||||
});
|
||||
const registration = {
|
||||
input: next.input,
|
||||
operation: Promise.resolve(),
|
||||
};
|
||||
activeDeviceRegistration = registration;
|
||||
registration.operation = (async () => {
|
||||
const result = await settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(registerDevice(next.input, generation)),
|
||||
);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
logRegistrationError(next.context, squashAtomCommandFailure(result));
|
||||
}
|
||||
logRegistrationDebug("device registration finished", { generation });
|
||||
if (activeDeviceRegistration === registration) {
|
||||
activeDeviceRegistration = null;
|
||||
}
|
||||
startPendingDeviceRegistration();
|
||||
})();
|
||||
}
|
||||
|
||||
function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
|
||||
if (
|
||||
activeDeviceRegistration &&
|
||||
!registrationAddsInformation(activeDeviceRegistration.input, input)
|
||||
) {
|
||||
logRegistrationDebug("device registration coalesced with active request", {
|
||||
generation: deviceRegistrationGeneration,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
logRegistrationDebug("device registration enqueued", {
|
||||
generation: deviceRegistrationGeneration,
|
||||
hasActiveRegistration: activeDeviceRegistration !== null,
|
||||
hasPendingRegistration: pendingDeviceRegistration !== null,
|
||||
});
|
||||
pendingDeviceRegistration = pendingDeviceRegistration
|
||||
? {
|
||||
input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
|
||||
context,
|
||||
}
|
||||
: { input, context };
|
||||
startPendingDeviceRegistration();
|
||||
}
|
||||
|
||||
function registerDevice(
|
||||
input: DeviceRegistrationInput = {},
|
||||
expectedGeneration = deviceRegistrationGeneration,
|
||||
): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
function registerDevice(input?: {
|
||||
readonly pushToStartToken?: string;
|
||||
readonly observedPushToken?: string;
|
||||
}): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!canRegisterRemoteLiveActivities()) {
|
||||
logRegistrationDebug("device registration skipped; platform does not support it");
|
||||
return;
|
||||
}
|
||||
|
||||
logRegistrationDebug("device registration loading local state", { expectedGeneration });
|
||||
const [deviceId, preferences] = yield* Effect.all([
|
||||
Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
@@ -389,10 +255,6 @@ function registerDevice(
|
||||
}),
|
||||
]);
|
||||
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
|
||||
logRegistrationDebug("device registration local state ready", {
|
||||
expectedGeneration,
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
});
|
||||
yield* registerDeviceWithRelay(
|
||||
makeRelayDeviceRegistrationRequest({
|
||||
deviceId,
|
||||
@@ -404,7 +266,6 @@ function registerDevice(
|
||||
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
|
||||
preferences,
|
||||
}),
|
||||
expectedGeneration,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -416,7 +277,10 @@ function registerDeviceForCurrentUser(
|
||||
}
|
||||
|
||||
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
|
||||
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
|
||||
runRegistrationInBackground(
|
||||
registerDeviceForCurrentUser(pushToStartToken),
|
||||
"push-to-start token registration failed",
|
||||
);
|
||||
}
|
||||
|
||||
function ensurePushToStartListener(): void {
|
||||
@@ -439,8 +303,8 @@ function ensurePushTokenListener(): void {
|
||||
|
||||
pushTokenSubscription = Notifications.addPushTokenListener((token) => {
|
||||
if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
|
||||
enqueueDeviceRegistration(
|
||||
{ observedPushToken: token.data.trim() },
|
||||
runRegistrationInBackground(
|
||||
registerDevice({ observedPushToken: token.data.trim() }),
|
||||
"native APNs token rotation registration failed",
|
||||
);
|
||||
}
|
||||
@@ -455,7 +319,7 @@ export function registerAgentAwarenessConnection(connection: SavedRemoteConnecti
|
||||
environmentConnections.set(connection.environmentId, connection);
|
||||
ensurePushToStartListener();
|
||||
ensurePushTokenListener();
|
||||
enqueueDeviceRegistration({}, "device registration failed");
|
||||
runRegistrationInBackground(registerDevice(), "device registration failed");
|
||||
runRegistrationInBackground(
|
||||
refreshActiveLiveActivityRemoteRegistration(),
|
||||
"active live activity registration after environment connection failed",
|
||||
@@ -508,9 +372,6 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
|
||||
}
|
||||
relayTokenProvider = null;
|
||||
relayTokenProviderIdentity = null;
|
||||
deviceRegistrationGeneration++;
|
||||
activeDeviceRegistration = null;
|
||||
pendingDeviceRegistration = null;
|
||||
}
|
||||
|
||||
export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
type ArchivedThreadsHeaderEnvironment,
|
||||
} from "./ArchivedThreadsScreen";
|
||||
import { buildArchivedThreadGroups, type ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
import {
|
||||
refreshArchivedThreadsForEnvironment,
|
||||
useArchivedThreadSnapshots,
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const [sortOrder, setSortOrder] = useState<ArchivedThreadSortOrder>("newest");
|
||||
const environments = useMemo<ReadonlyArray<ArchivedThreadsHeaderEnvironment>>(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(Order.String, (environment: ArchivedThreadsHeaderEnvironment) =>
|
||||
environment.label.toLocaleLowerCase(),
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const environmentIds = useMemo(
|
||||
() => environments.map((environment) => environment.environmentId),
|
||||
[environments],
|
||||
);
|
||||
const environmentLabels = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
environments.map((environment) => [environment.environmentId, environment.label]),
|
||||
),
|
||||
[environments],
|
||||
);
|
||||
const { error, isLoading, refresh, snapshots } = useArchivedThreadSnapshots(environmentIds);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildArchivedThreadGroups({
|
||||
snapshots,
|
||||
environmentLabels,
|
||||
environmentId: selectedEnvironmentId,
|
||||
searchQuery,
|
||||
sortOrder,
|
||||
}),
|
||||
[environmentLabels, searchQuery, selectedEnvironmentId, snapshots, sortOrder],
|
||||
);
|
||||
const refreshChangedEnvironment = useCallback(
|
||||
(thread: { readonly environmentId: EnvironmentId }) => {
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const { unarchiveThread, confirmDeleteThread } =
|
||||
useArchivedThreadListActions(refreshChangedEnvironment);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [expand, refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
<ArchivedThreadsScreen
|
||||
environments={environments}
|
||||
error={error}
|
||||
groups={groups}
|
||||
isLoading={isLoading}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onRefresh={refresh}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSortOrderChange={setSortOrder}
|
||||
onUnarchiveThread={unarchiveThread}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
sortOrder={sortOrder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,434 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Stack } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useRef } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "../home/thread-swipe-actions";
|
||||
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
const THREAD_ACTIONS: MenuAction[] = [
|
||||
{
|
||||
id: "unarchive",
|
||||
title: "Unarchive",
|
||||
image: "arrow.uturn.backward",
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
title: "Delete",
|
||||
image: "trash",
|
||||
attributes: { destructive: true },
|
||||
},
|
||||
];
|
||||
|
||||
function ArchivedThreadsHeader(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
}) {
|
||||
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Archived Threads",
|
||||
headerSearchBarOptions: {
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
placement: "stacked",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort by archived date">
|
||||
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectGroupLabel(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly project: EnvironmentProject;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
projectTitle={props.project.title}
|
||||
size={18}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
>
|
||||
{props.project.title}
|
||||
</Text>
|
||||
{props.environmentLabel ? (
|
||||
<Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ArchivedThreadRow(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isLast: boolean;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onUnarchive: () => void;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
|
||||
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
const handleMenuAction = useCallback(
|
||||
(event: { nativeEvent: { event: string } }) => {
|
||||
if (event.nativeEvent.event === "unarchive") {
|
||||
props.onUnarchive();
|
||||
} else if (event.nativeEvent.event === "delete") {
|
||||
props.onDelete();
|
||||
}
|
||||
},
|
||||
[props.onDelete, props.onUnarchive],
|
||||
);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) return;
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-[12px] text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-[11px] text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
</ReanimatedSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
|
||||
return (
|
||||
<View className="rounded-[20px] border border-danger-border bg-danger p-4">
|
||||
<Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
|
||||
<Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ArchivedThreadsScreen(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
readonly error: string | null;
|
||||
readonly groups: ReadonlyArray<ArchivedThreadGroup>;
|
||||
readonly isLoading: boolean;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const refreshTint = useThemeColor("--color-icon");
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
|
||||
openSwipeableRef.current.close();
|
||||
}
|
||||
openSwipeableRef.current = methods;
|
||||
}, []);
|
||||
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current === methods) {
|
||||
openSwipeableRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
|
||||
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<ArchivedThreadsHeader
|
||||
environments={props.environments}
|
||||
onEnvironmentChange={props.onEnvironmentChange}
|
||||
onSearchQueryChange={props.onSearchQueryChange}
|
||||
onSortOrderChange={props.onSortOrderChange}
|
||||
selectedEnvironmentId={props.selectedEnvironmentId}
|
||||
sortOrder={props.sortOrder}
|
||||
/>
|
||||
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
|
||||
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
) : (
|
||||
props.groups.map((group) => {
|
||||
const environmentLabel =
|
||||
props.environments.find(
|
||||
(environment) => environment.environmentId === group.project.environmentId,
|
||||
)?.label ?? null;
|
||||
|
||||
return (
|
||||
<View key={group.key} collapsable={false}>
|
||||
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{group.threads.map((thread, index) => (
|
||||
<ArchivedThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
environmentLabel={environmentLabel}
|
||||
isLast={index === group.threads.length - 1}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => props.onUnarchiveThread(thread)}
|
||||
thread={thread}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeProject(
|
||||
input: Partial<OrchestrationProjectShell> & Pick<OrchestrationProjectShell, "id" | "title">,
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildArchivedThreadGroups", () => {
|
||||
it("groups archived threads by project and sorts newest first", () => {
|
||||
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const older = makeThread({
|
||||
id: ThreadId.make("thread-older"),
|
||||
projectId: project.id,
|
||||
title: "Older",
|
||||
});
|
||||
const newer = makeThread({
|
||||
archivedAt: "2026-06-03T00:00:00.000Z",
|
||||
id: ThreadId.make("thread-newer"),
|
||||
projectId: project.id,
|
||||
title: "Newer",
|
||||
});
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots: [makeSnapshot([project], [older, newer])],
|
||||
environmentLabels: { [environmentId]: "Julius's MacBook Pro" },
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
sortOrder: "newest",
|
||||
});
|
||||
|
||||
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-newer", "thread-older"]);
|
||||
});
|
||||
|
||||
it("filters by environment and matches project, thread, and branch text", () => {
|
||||
const secondEnvironmentId = EnvironmentId.make("environment-2");
|
||||
const firstProject = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const secondProject = makeProject({ id: ProjectId.make("project-2"), title: "Website" });
|
||||
const firstThread = makeThread({
|
||||
branch: "fix/archive-screen",
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: firstProject.id,
|
||||
title: "Build settings route",
|
||||
});
|
||||
const secondThread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: secondProject.id,
|
||||
title: "Unrelated",
|
||||
});
|
||||
const snapshots = [
|
||||
makeSnapshot([firstProject], [firstThread]),
|
||||
makeSnapshot([secondProject], [secondThread], secondEnvironmentId),
|
||||
];
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots,
|
||||
environmentLabels: {
|
||||
[environmentId]: "Local",
|
||||
[secondEnvironmentId]: "Remote",
|
||||
},
|
||||
environmentId,
|
||||
searchQuery: "archive-screen",
|
||||
sortOrder: "oldest",
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.project.environmentId).toBe(environmentId);
|
||||
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-1"]);
|
||||
});
|
||||
|
||||
it("ignores non-archived entries returned in a snapshot", () => {
|
||||
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const active = makeThread({
|
||||
archivedAt: null,
|
||||
id: ThreadId.make("thread-active"),
|
||||
projectId: project.id,
|
||||
title: "Active",
|
||||
});
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots: [makeSnapshot([project], [active])],
|
||||
environmentLabels: {},
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
sortOrder: "newest",
|
||||
});
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
scopeProject,
|
||||
scopeThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
|
||||
export type ArchivedThreadSortOrder = "newest" | "oldest";
|
||||
|
||||
export interface ArchivedThreadGroup {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}
|
||||
|
||||
function archiveTimestamp(thread: EnvironmentThreadShell): number {
|
||||
const timestamp = Date.parse(thread.archivedAt ?? thread.updatedAt);
|
||||
return Number.isNaN(timestamp) ? 0 : timestamp;
|
||||
}
|
||||
|
||||
function matchesQuery(value: string | null, query: string): boolean {
|
||||
return value?.toLocaleLowerCase().includes(query) ?? false;
|
||||
}
|
||||
|
||||
export function buildArchivedThreadGroups(input: {
|
||||
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
|
||||
readonly environmentLabels: Readonly<Record<string, string>>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
}): ReadonlyArray<ArchivedThreadGroup> {
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const groups: ArchivedThreadGroup[] = [];
|
||||
|
||||
for (const entry of input.snapshots) {
|
||||
if (input.environmentId !== null && input.environmentId !== entry.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const environmentLabel = input.environmentLabels[entry.environmentId] ?? null;
|
||||
const threadsByProjectId = new Map<string, EnvironmentThreadShell[]>();
|
||||
for (const thread of entry.snapshot.threads) {
|
||||
if (thread.archivedAt === null) {
|
||||
continue;
|
||||
}
|
||||
const threads = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
threads.push(scopeThreadShell(entry.environmentId, thread));
|
||||
threadsByProjectId.set(thread.projectId, threads);
|
||||
}
|
||||
|
||||
for (const rawProject of entry.snapshot.projects) {
|
||||
const project = scopeProject(entry.environmentId, rawProject);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
matchesQuery(project.title, query) ||
|
||||
matchesQuery(project.workspaceRoot, query) ||
|
||||
matchesQuery(environmentLabel, query);
|
||||
const matchingThreads = groupMatches
|
||||
? projectThreads
|
||||
: projectThreads.filter(
|
||||
(thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
|
||||
);
|
||||
|
||||
if (matchingThreads.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
|
||||
groups.push({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
project,
|
||||
threads: Arr.sort(
|
||||
matchingThreads,
|
||||
Order.mapInput(
|
||||
Order.Struct({ timestamp: timestampOrder, title: Order.String, id: Order.String }),
|
||||
(thread: EnvironmentThreadShell) => ({
|
||||
timestamp: archiveTimestamp(thread),
|
||||
title: thread.title,
|
||||
id: thread.id,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
|
||||
return Arr.sort(
|
||||
groups,
|
||||
Order.mapInput(
|
||||
Order.Struct({ timestamp: timestampOrder, title: Order.String, key: Order.String }),
|
||||
(group: ArchivedThreadGroup) => ({
|
||||
timestamp: group.threads[0] ? archiveTimestamp(group.threads[0]) : 0,
|
||||
title: group.project.title,
|
||||
key: group.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ArchivedSnapshotEntry,
|
||||
createArchivedThreadSnapshotsAtomFamily,
|
||||
makeArchivedThreadsEnvironmentKey,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { orchestrationEnvironment } from "../../state/orchestration";
|
||||
|
||||
function archivedSnapshotAtom(environmentId: EnvironmentId) {
|
||||
return orchestrationEnvironment.archivedShellSnapshot({
|
||||
environmentId,
|
||||
input: {},
|
||||
});
|
||||
}
|
||||
|
||||
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
|
||||
getSnapshotAtom: archivedSnapshotAtom,
|
||||
labelPrefix: "mobile:archived-thread-snapshots",
|
||||
});
|
||||
|
||||
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
|
||||
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
|
||||
}
|
||||
|
||||
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
|
||||
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
|
||||
readonly error: string | null;
|
||||
readonly isLoading: boolean;
|
||||
readonly refresh: () => void;
|
||||
} {
|
||||
const environmentKey = useMemo(
|
||||
() => makeArchivedThreadsEnvironmentKey(environmentIds),
|
||||
[environmentIds],
|
||||
);
|
||||
const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
|
||||
const refresh = useCallback(() => {
|
||||
for (const environmentId of environmentIds) {
|
||||
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
|
||||
}
|
||||
}, [environmentIds]);
|
||||
|
||||
return { ...result, refresh };
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
|
||||
import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
|
||||
|
||||
vi.mock("@clerk/expo", () => ({
|
||||
ClerkProvider: vi.fn(),
|
||||
useAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/expo/token-cache", () => ({
|
||||
tokenCache: {},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/runtime", () => ({
|
||||
runtime: {
|
||||
runPromiseExit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../connection/catalog", () => ({
|
||||
environmentCatalog: {
|
||||
removeRelayEnvironments: {},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./publicConfig", () => ({
|
||||
resolveCloudPublicConfig: vi.fn(() => ({
|
||||
clerk: { publishableKey: null },
|
||||
relay: { url: null },
|
||||
})),
|
||||
resolveRelayClerkTokenOptions: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../agent-awareness/remoteRegistration", () => ({
|
||||
setAgentAwarenessRelayTokenProvider: vi.fn(),
|
||||
unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
deactivateCloudRelayAccount();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("CloudAuthProvider relay account isolation", () => {
|
||||
it("clears relay and agent-awareness credentials before cleanup can fail", async () => {
|
||||
const tokenProvider = async () => "account-1-token";
|
||||
activateCloudRelayAccount("account-1", tokenProvider);
|
||||
expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");
|
||||
|
||||
deactivateCloudRelayAccount();
|
||||
const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);
|
||||
|
||||
expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
|
||||
expect(vi.mocked(setAgentAwarenessRelayTokenProvider)).toHaveBeenLastCalledWith(null);
|
||||
await cleanup;
|
||||
});
|
||||
});
|
||||
@@ -1,149 +1,63 @@
|
||||
import { ClerkProvider, useAuth } from "@clerk/expo";
|
||||
import { tokenCache } from "@clerk/expo/token-cache";
|
||||
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
unregisterAgentAwarenessDeviceForCurrentUser,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
|
||||
|
||||
function resetManagedRelayTokenCache() {
|
||||
return settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function deactivateCloudRelayAccount(): void {
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
}
|
||||
|
||||
export function activateCloudRelayAccount(
|
||||
accountId: string,
|
||||
tokenProvider: () => Promise<string | null>,
|
||||
): void {
|
||||
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
|
||||
setManagedRelaySession(appAtomRegistry, {
|
||||
accountId,
|
||||
readClerkToken: tokenProvider,
|
||||
});
|
||||
}
|
||||
|
||||
function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
|
||||
reportFailure: false,
|
||||
reportDefect: false,
|
||||
});
|
||||
const previousTokenProviderRef = useRef<{
|
||||
readonly userId: string;
|
||||
readonly provider: () => Promise<string | null>;
|
||||
} | null>(null);
|
||||
const observedAccountRef = useRef<string | null | undefined>(undefined);
|
||||
const accountTransitionRef = useRef<Promise<void> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!isLoaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previousObservedAccount = observedAccountRef.current;
|
||||
const nextAccount = isSignedIn && userId ? userId : null;
|
||||
observedAccountRef.current = nextAccount;
|
||||
|
||||
const queueAccountCleanup = (
|
||||
previous: {
|
||||
readonly userId: string;
|
||||
readonly provider: () => Promise<string | null>;
|
||||
} | null,
|
||||
) => {
|
||||
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
|
||||
accountTransitionRef.current = previousTransition.then(async () => {
|
||||
const cleanup = [
|
||||
resetManagedRelayTokenCache(),
|
||||
removeRelayEnvironments(),
|
||||
...(previous
|
||||
? [
|
||||
settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
|
||||
),
|
||||
),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const results = await Promise.all(cleanup);
|
||||
for (const result of results) {
|
||||
reportAtomCommandResult(result, { label: "cloud account cleanup" });
|
||||
}
|
||||
});
|
||||
return accountTransitionRef.current;
|
||||
};
|
||||
|
||||
if (!isSignedIn || !userId) {
|
||||
const previous = previousTokenProviderRef.current;
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
if (previousObservedAccount !== null) {
|
||||
void queueAccountCleanup(previous);
|
||||
if (previous) {
|
||||
void mobileRuntime
|
||||
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
return;
|
||||
}
|
||||
|
||||
const previous = previousTokenProviderRef.current;
|
||||
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
|
||||
const activateSession = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
previousTokenProviderRef.current = { userId, provider: tokenProvider };
|
||||
activateCloudRelayAccount(userId, tokenProvider);
|
||||
};
|
||||
const activateAfterTransition = (transition: Promise<void>) => {
|
||||
void (async () => {
|
||||
const result = await settlePromise(async () => {
|
||||
await transition;
|
||||
activateSession();
|
||||
});
|
||||
reportAtomCommandResult(result, { label: "cloud account activation" });
|
||||
})();
|
||||
};
|
||||
if (
|
||||
previousObservedAccount !== undefined &&
|
||||
previousObservedAccount !== null &&
|
||||
previousObservedAccount !== userId
|
||||
) {
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
activateAfterTransition(queueAccountCleanup(previous));
|
||||
} else {
|
||||
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
|
||||
if (previous && previous.userId !== userId) {
|
||||
void mobileRuntime
|
||||
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
|
||||
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
|
||||
previousTokenProviderRef.current = { userId, provider: tokenProvider };
|
||||
setAgentAwarenessRelayTokenProvider(tokenProvider, userId);
|
||||
setManagedRelaySession(
|
||||
appAtomRegistry,
|
||||
createManagedRelaySession({
|
||||
accountId: userId,
|
||||
readClerkToken: tokenProvider,
|
||||
}),
|
||||
);
|
||||
}, [getToken, isLoaded, isSignedIn, userId]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
},
|
||||
[],
|
||||
);
|
||||
@@ -158,7 +72,8 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!publishableKey || !relayUrl) {
|
||||
deactivateCloudRelayAccount();
|
||||
setAgentAwarenessRelayTokenProvider(null);
|
||||
setManagedRelaySession(appAtomRegistry, null);
|
||||
}
|
||||
}, [publishableKey, relayUrl]);
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
export function isCloudDebugEnabled(): boolean {
|
||||
return (
|
||||
(typeof __DEV__ !== "undefined" && __DEV__) ||
|
||||
(typeof globalThis !== "undefined" &&
|
||||
(globalThis as { __T3_CLOUD_DEBUG__?: boolean }).__T3_CLOUD_DEBUG__ === true)
|
||||
);
|
||||
}
|
||||
|
||||
export function cloudDebugLog(event: string, data?: Record<string, unknown>): void {
|
||||
if (!isCloudDebugEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (data) {
|
||||
console.log(`[t3-cloud] ${event}`, data);
|
||||
} else {
|
||||
console.log(`[t3-cloud] ${event}`);
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { availableCloudEnvironmentPresentation } from "./cloudEnvironmentPresentation";
|
||||
|
||||
function relayStatus(
|
||||
status: RelayEnvironmentStatusResponse["status"],
|
||||
error?: string,
|
||||
traceId?: string,
|
||||
): RelayEnvironmentStatusResponse {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment-cloud"),
|
||||
endpoint: {
|
||||
httpBaseUrl: "https://cloud.example.test/",
|
||||
wsBaseUrl: "wss://cloud.example.test/ws",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
status,
|
||||
checkedAt: "2026-06-05T16:49:11.000Z",
|
||||
...(error ? { error } : {}),
|
||||
...(traceId ? { traceId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("available cloud environment presentation", () => {
|
||||
it("presents an online unsaved environment as available, not connected", () => {
|
||||
expect(
|
||||
availableCloudEnvironmentPresentation({
|
||||
isStatusPending: false,
|
||||
status: relayStatus("online"),
|
||||
statusError: null,
|
||||
statusErrorTraceId: null,
|
||||
}),
|
||||
).toEqual({
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
connectionState: "available",
|
||||
statusText: "Available · Relay online",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps relay status checks distinct from connection attempts", () => {
|
||||
expect(
|
||||
availableCloudEnvironmentPresentation({
|
||||
isStatusPending: true,
|
||||
status: null,
|
||||
statusError: null,
|
||||
statusErrorTraceId: null,
|
||||
}),
|
||||
).toEqual({
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
connectionState: "available",
|
||||
statusText: "Available · Checking relay status...",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces an offline relay as an error", () => {
|
||||
expect(
|
||||
availableCloudEnvironmentPresentation({
|
||||
isStatusPending: false,
|
||||
status: relayStatus("offline", "Tunnel is unavailable.", "trace-offline"),
|
||||
statusError: null,
|
||||
statusErrorTraceId: null,
|
||||
}),
|
||||
).toEqual({
|
||||
connectionError: "Tunnel is unavailable.",
|
||||
connectionErrorTraceId: "trace-offline",
|
||||
connectionState: "error",
|
||||
statusText: "Tunnel is unavailable.",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves trace metadata for relay request failures", () => {
|
||||
expect(
|
||||
availableCloudEnvironmentPresentation({
|
||||
isStatusPending: false,
|
||||
status: null,
|
||||
statusError: "Could not get relay environment status.",
|
||||
statusErrorTraceId: "trace-status",
|
||||
}),
|
||||
).toMatchObject({
|
||||
connectionError: "Could not get relay environment status.",
|
||||
connectionErrorTraceId: "trace-status",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
|
||||
export interface AvailableCloudEnvironmentPresentation {
|
||||
readonly connectionError: string | null;
|
||||
readonly connectionErrorTraceId: string | null;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
readonly statusText: string;
|
||||
}
|
||||
|
||||
export function availableCloudEnvironmentPresentation(input: {
|
||||
readonly isStatusPending: boolean;
|
||||
readonly status: RelayEnvironmentStatusResponse | null;
|
||||
readonly statusError: string | null;
|
||||
readonly statusErrorTraceId: string | null;
|
||||
}): AvailableCloudEnvironmentPresentation {
|
||||
if (input.status?.status === "online") {
|
||||
return {
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
connectionState: "available",
|
||||
statusText: "Available · Relay online",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.status?.status === "offline") {
|
||||
const connectionError = input.status.error ?? "Relay is offline.";
|
||||
return {
|
||||
connectionError,
|
||||
connectionErrorTraceId: input.status.traceId ?? null,
|
||||
connectionState: "error",
|
||||
statusText: connectionError,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.statusError) {
|
||||
return {
|
||||
connectionError: input.statusError,
|
||||
connectionErrorTraceId: input.statusErrorTraceId,
|
||||
connectionState: "error",
|
||||
statusText: input.statusError,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
connectionState: "available",
|
||||
statusText: input.isStatusPending
|
||||
? "Available · Checking relay status..."
|
||||
: "Available · Relay status unknown",
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
createDpopProof,
|
||||
generateDpopProofKeyPair,
|
||||
loadOrCreateDpopProofKeyPair,
|
||||
cryptoLayer,
|
||||
mobileCryptoLayer,
|
||||
} from "./dpop";
|
||||
|
||||
vi.mock("expo-crypto", () => ({
|
||||
@@ -75,7 +75,7 @@ describe("mobile DPoP", () => {
|
||||
expect(Buffer.from(digest).toString("hex")).toBe(
|
||||
NodeCrypto.createHash("sha256").update("typed-array").digest("hex"),
|
||||
);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
}).pipe(Effect.provide(mobileCryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("persists and reuses the installation proof key", () =>
|
||||
@@ -86,7 +86,7 @@ describe("mobile DPoP", () => {
|
||||
|
||||
expect(second.thumbprint).toBe(first.thumbprint);
|
||||
expect(second.privateJwk).toEqual(first.privateJwk);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
}).pipe(Effect.provide(mobileCryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects malformed persisted proof keys", () =>
|
||||
@@ -96,7 +96,7 @@ describe("mobile DPoP", () => {
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toBe("Stored DPoP proof key is invalid.");
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
}).pipe(Effect.provide(mobileCryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
|
||||
@@ -135,7 +135,7 @@ describe("mobile DPoP", () => {
|
||||
nowEpochSeconds: proofIat(bootstrap.proof),
|
||||
}),
|
||||
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
}).pipe(Effect.provide(mobileCryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
|
||||
@@ -161,6 +161,6 @@ describe("mobile DPoP", () => {
|
||||
nowEpochSeconds: proofIat(proof.proof),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
}).pipe(Effect.provide(mobileCryptoLayer)),
|
||||
);
|
||||
});
|
||||
@@ -70,7 +70,7 @@ function toExpoDigestAlgorithm(
|
||||
}
|
||||
}
|
||||
|
||||
export const cryptoLayer = Layer.succeed(
|
||||
export const mobileCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: ExpoCrypto.getRandomBytes,
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
managedRelayClientLayer,
|
||||
ManagedRelayClient,
|
||||
ManagedRelayDpopSigner,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
remoteHttpClientLayer,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
@@ -55,8 +55,6 @@ const savedConnection = {
|
||||
bearerToken: "local-bearer",
|
||||
};
|
||||
|
||||
const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";
|
||||
|
||||
const createProofMock = vi.fn(
|
||||
(input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
|
||||
Effect.succeed(`dpop:${input.method}:${input.url}`),
|
||||
@@ -354,7 +352,7 @@ describe("mobile cloud link environment client", () => {
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));
|
||||
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }));
|
||||
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
|
||||
@@ -427,11 +425,9 @@ describe("mobile cloud link environment client", () => {
|
||||
|
||||
yield* withCloudServices(
|
||||
Effect.gen(function* () {
|
||||
const records = yield* listCloudEnvironmentsWithStatus({
|
||||
clerkToken: stableClerkToken,
|
||||
});
|
||||
const records = yield* listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" });
|
||||
yield* connectCloudEnvironment({
|
||||
clerkToken: stableClerkToken,
|
||||
clerkToken: "clerk-token",
|
||||
environment: records[0]!.environment,
|
||||
});
|
||||
}),
|
||||
@@ -662,7 +658,6 @@ describe("mobile cloud link environment client", () => {
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
|
||||
traceId: "trace-test",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
@@ -1008,7 +1003,6 @@ describe("mobile cloud link environment client", () => {
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
|
||||
traceId: "trace-connect",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -16,23 +16,22 @@ import {
|
||||
type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
RelayProtectedError,
|
||||
type RelayDpopAccessTokenScope,
|
||||
type RelayProtectedError as RelayProtectedErrorType,
|
||||
type RelayClientEnvironmentRecord,
|
||||
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
|
||||
type RelayManagedEndpointProviderKind,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
exchangeRemoteDpopAccessToken,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
makeEnvironmentHttpApiClient,
|
||||
ManagedRelayClient,
|
||||
type ManagedRelayClientError,
|
||||
ManagedRelayDpopSigner,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
} from "@t3tools/client-runtime";
|
||||
|
||||
import { authClientMetadata } from "../../lib/authClientMetadata";
|
||||
import { mobileAuthClientMetadata } from "../../lib/authClientMetadata";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
|
||||
import { resolveCloudPublicConfig } from "./publicConfig";
|
||||
@@ -57,7 +56,6 @@ function readRelayUrl(): string | null {
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly traceId?: string;
|
||||
}> {}
|
||||
|
||||
export interface CloudEnvironmentRecordWithStatus {
|
||||
@@ -66,6 +64,7 @@ export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly statusError: string | null;
|
||||
}
|
||||
|
||||
const isRelayProtectedError = Schema.is(RelayProtectedError);
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
@@ -83,13 +82,11 @@ const MANAGED_ENDPOINT_PROVIDER_KIND =
|
||||
function cloudEnvironmentLinkError(message: string) {
|
||||
return (cause: unknown) => {
|
||||
const environmentError = findEnvironmentCloudApiError(cause);
|
||||
const traceId = findErrorTraceId(cause);
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: environmentError
|
||||
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
|
||||
: withDevCause(message, cause),
|
||||
cause,
|
||||
...(traceId === null ? {} : { traceId }),
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -151,22 +148,31 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
case "RelayAgentActivityPublishProofInvalidError":
|
||||
return `Relay rejected the agent activity publish proof (${error.reason}).`;
|
||||
case "RelayInternalError":
|
||||
return `Relay encountered an internal error (${error.reason}).`;
|
||||
return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function decodedRelayClientError(message: string) {
|
||||
return (cause: ManagedRelayClientError) => {
|
||||
const relayError = cause.relayError;
|
||||
return (cause: unknown) => {
|
||||
const relayError = findRelayProtectedError(cause);
|
||||
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: detail ? `${message}: ${detail}` : message,
|
||||
cause,
|
||||
...(cause.traceId ? { traceId: cause.traceId } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null {
|
||||
if (isRelayProtectedError(cause)) {
|
||||
return cause;
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return "cause" in cause ? findRelayProtectedError(cause.cause) : null;
|
||||
}
|
||||
|
||||
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
|
||||
if (isEnvironmentCloudApiError(cause)) {
|
||||
return cause;
|
||||
@@ -456,26 +462,23 @@ export function listCloudEnvironmentsWithStatus(input: {
|
||||
});
|
||||
}
|
||||
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
|
||||
function* () {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
|
||||
function* (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
|
||||
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
|
||||
}) {
|
||||
yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });
|
||||
function connectRelayManagedEnvironment(input: {
|
||||
readonly clerkToken: string;
|
||||
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
|
||||
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
|
||||
}): Effect.Effect<
|
||||
SavedRemoteConnection,
|
||||
CloudEnvironmentLinkError,
|
||||
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId();
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
const connect = yield* relayClient
|
||||
.connectEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -525,7 +528,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
clientMetadata: mobileAuthClientMetadata(),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
@@ -545,9 +548,9 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
authenticationMethod: "dpop",
|
||||
dpopAccessToken: bootstrap.access_token,
|
||||
relayManaged: true,
|
||||
} satisfies SavedRemoteConnection;
|
||||
},
|
||||
);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function connectCloudEnvironment(input: {
|
||||
readonly clerkToken: string;
|
||||
|
||||
@@ -1,46 +1,42 @@
|
||||
import {
|
||||
managedRelayClientLayer as makeManagedRelayClientLayer,
|
||||
managedRelayClientLayer,
|
||||
ManagedRelayDpopSigner,
|
||||
ManagedRelayDpopSignerError,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
} from "@t3tools/client-runtime";
|
||||
import { RelayMobileClientId } from "@t3tools/contracts/relay";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
|
||||
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
|
||||
|
||||
const relayDpopSignerLayer = Layer.effect(
|
||||
const mobileRelayDpopSignerLayer = Layer.effect(
|
||||
ManagedRelayDpopSigner,
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const loadProofKey = yield* Effect.cached(
|
||||
loadOrCreateDpopProofKeyPair().pipe(Effect.provideService(Crypto.Crypto, crypto)),
|
||||
);
|
||||
return ManagedRelayDpopSigner.of({
|
||||
thumbprint: loadProofKey.pipe(
|
||||
Effect.map((proofKey) => proofKey.thumbprint),
|
||||
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
|
||||
Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),
|
||||
thumbprint: Effect.suspend(() =>
|
||||
loadOrCreateDpopProofKeyPair().pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proofKey) => proofKey.thumbprint),
|
||||
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
|
||||
),
|
||||
),
|
||||
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(
|
||||
function* (input) {
|
||||
const proofKey = yield* loadProofKey;
|
||||
createProof: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* loadOrCreateDpopProofKeyPair().pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
);
|
||||
return yield* createDpopProof({ ...input, proofKey }).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proof) => proof.proof),
|
||||
);
|
||||
},
|
||||
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
|
||||
),
|
||||
}).pipe(Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause }))),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const managedRelayClientLayer = (relayUrl: string) =>
|
||||
makeManagedRelayClientLayer({
|
||||
relayUrl,
|
||||
clientId: RelayMobileClientId,
|
||||
accessTokenStore: managedRelayAccessTokenStore,
|
||||
}).pipe(Layer.provideMerge(relayDpopSignerLayer));
|
||||
export const mobileManagedRelayClientLayer = (relayUrl: string) =>
|
||||
managedRelayClientLayer({ relayUrl, clientId: RelayMobileClientId }).pipe(
|
||||
Layer.provideMerge(mobileRelayDpopSignerLayer),
|
||||
);
|
||||
@@ -3,24 +3,20 @@ import {
|
||||
createManagedRelayQueryManager,
|
||||
managedRelaySessionAtom,
|
||||
readManagedRelaySnapshotState,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
RelayClientEnvironmentRecord,
|
||||
RelayEnvironmentStatusResponse,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { runtimeContextLayer } from "../../lib/runtime";
|
||||
import { mobileRuntimeContextLayer } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { cloudDebugLog } from "./cloudDebugLog";
|
||||
|
||||
const managedRelayAtomRuntime = Atom.runtime(runtimeContextLayer);
|
||||
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
|
||||
|
||||
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime, {
|
||||
onQueryEvent: (event) =>
|
||||
cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),
|
||||
});
|
||||
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
|
||||
|
||||
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
|
||||
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
|
||||
@@ -37,15 +33,6 @@ export function useManagedRelayEnvironments() {
|
||||
? managedRelayQueryManager.environmentsAtom(accountId)
|
||||
: EMPTY_ENVIRONMENTS_ATOM;
|
||||
const result = useAtomValue(atom);
|
||||
const snapshot = readManagedRelaySnapshotState(result);
|
||||
useEffect(() => {
|
||||
if (snapshot.error) {
|
||||
console.error("[t3-cloud] Relay environment listing failed", {
|
||||
message: snapshot.error,
|
||||
traceId: snapshot.errorTraceId,
|
||||
});
|
||||
}
|
||||
}, [snapshot.error, snapshot.errorTraceId]);
|
||||
const refresh = useCallback(() => {
|
||||
if (accountId) {
|
||||
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
|
||||
@@ -53,7 +40,7 @@ export function useManagedRelayEnvironments() {
|
||||
}, [accountId]);
|
||||
|
||||
return {
|
||||
...snapshot,
|
||||
...readManagedRelaySnapshotState(result),
|
||||
accountId,
|
||||
refresh,
|
||||
};
|
||||
@@ -66,16 +53,6 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
|
||||
? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })
|
||||
: EMPTY_ENVIRONMENT_STATUS_ATOM;
|
||||
const result = useAtomValue(atom);
|
||||
const snapshot = readManagedRelaySnapshotState(result);
|
||||
useEffect(() => {
|
||||
if (snapshot.error) {
|
||||
console.error("[t3-cloud] Relay environment status failed", {
|
||||
environmentId: environment.environmentId,
|
||||
message: snapshot.error,
|
||||
traceId: snapshot.errorTraceId,
|
||||
});
|
||||
}
|
||||
}, [environment.environmentId, snapshot.error, snapshot.errorTraceId]);
|
||||
const refresh = useCallback(() => {
|
||||
if (accountId) {
|
||||
managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {
|
||||
@@ -86,7 +63,7 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
|
||||
}, [accountId, environment]);
|
||||
|
||||
return {
|
||||
...snapshot,
|
||||
...readManagedRelaySnapshotState(result),
|
||||
accountId,
|
||||
refresh,
|
||||
};
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
|
||||
vi.mock("expo-secure-store", () => ({
|
||||
getItemAsync: vi.fn((key: string) => Promise.resolve(secureStore.get(key) ?? null)),
|
||||
setItemAsync: vi.fn((key: string, value: string) => {
|
||||
secureStore.set(key, value);
|
||||
return Promise.resolve();
|
||||
}),
|
||||
deleteItemAsync: vi.fn((key: string) => {
|
||||
secureStore.delete(key);
|
||||
return Promise.resolve();
|
||||
}),
|
||||
}));
|
||||
|
||||
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
|
||||
|
||||
it.effect("round-trips and clears persisted managed relay access tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
const entries = [
|
||||
{
|
||||
accountId: "user-1",
|
||||
clientId: "t3-mobile",
|
||||
relayUrl: "https://relay.example.test",
|
||||
thumbprint: "thumbprint",
|
||||
scopes: ["environment:connect"],
|
||||
accessToken: "access-token",
|
||||
expiresAtMillis: 1_800_000,
|
||||
},
|
||||
] as const;
|
||||
|
||||
yield* managedRelayAccessTokenStore.save(entries);
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual(entries);
|
||||
|
||||
yield* managedRelayAccessTokenStore.clear;
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to an empty cache when persisted data is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
secureStore.set("t3code.cloud.relay-access-tokens", "not-json");
|
||||
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
}),
|
||||
);
|
||||
@@ -1,107 +0,0 @@
|
||||
import {
|
||||
type ManagedRelayAccessTokenCacheEntry,
|
||||
type ManagedRelayAccessTokenStore,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
|
||||
const MANAGED_RELAY_TOKEN_CACHE_KEY = "t3code.cloud.relay-access-tokens";
|
||||
const MANAGED_RELAY_TOKEN_CACHE_VERSION = 1;
|
||||
|
||||
const ManagedRelayAccessTokenCacheEntrySchema = Schema.Struct({
|
||||
accountId: Schema.String,
|
||||
clientId: Schema.Literals(["t3-mobile", "t3-web"]),
|
||||
relayUrl: Schema.String,
|
||||
thumbprint: Schema.String,
|
||||
scopes: Schema.Array(
|
||||
Schema.Literals(["environment:connect", "environment:status", "mobile:registration"]),
|
||||
),
|
||||
accessToken: Schema.String,
|
||||
expiresAtMillis: Schema.Number,
|
||||
});
|
||||
|
||||
const ManagedRelayAccessTokenCacheSchema = Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(MANAGED_RELAY_TOKEN_CACHE_VERSION),
|
||||
entries: Schema.Array(ManagedRelayAccessTokenCacheEntrySchema),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
|
||||
ManagedRelayAccessTokenCacheSchema,
|
||||
);
|
||||
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
|
||||
|
||||
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
const storeError =
|
||||
(message: string) =>
|
||||
(cause: unknown): ManagedRelayTokenStoreError =>
|
||||
new ManagedRelayTokenStoreError({ message, cause });
|
||||
|
||||
function logStoreFailure(operation: string) {
|
||||
return (error: ManagedRelayTokenStoreError) =>
|
||||
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
|
||||
Effect.annotateLogs({
|
||||
errorTag: error._tag,
|
||||
message: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const loadManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: storeError("Could not read persisted relay access tokens."),
|
||||
}).pipe(
|
||||
Effect.flatMap((encoded) =>
|
||||
encoded === null
|
||||
? Effect.succeed<ReadonlyArray<ManagedRelayAccessTokenCacheEntry>>([])
|
||||
: decodeManagedRelayAccessTokenCache(encoded).pipe(
|
||||
Effect.map((cache) => cache.entries),
|
||||
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const saveManagedRelayAccessTokens = (entries: ReadonlyArray<ManagedRelayAccessTokenCacheEntry>) =>
|
||||
encodeManagedRelayAccessTokenCache({
|
||||
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
|
||||
entries,
|
||||
}).pipe(
|
||||
Effect.mapError(storeError("Could not encode relay access tokens.")),
|
||||
Effect.flatMap((encoded) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
|
||||
catch: storeError("Could not persist relay access tokens."),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const clearManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: storeError("Could not clear persisted relay access tokens."),
|
||||
});
|
||||
|
||||
export const managedRelayAccessTokenStore: ManagedRelayAccessTokenStore = {
|
||||
load: loadManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure("load")),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.load"),
|
||||
),
|
||||
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
|
||||
saveManagedRelayAccessTokens(entries).pipe(
|
||||
Effect.tapError(logStoreFailure("save")),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
clear: clearManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure("clear")),
|
||||
Effect.ignore,
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
|
||||
),
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -94,9 +94,9 @@ describe("resolveCloudPublicConfig", () => {
|
||||
});
|
||||
|
||||
it("keeps tracing disabled unless every public tracing value is configured", () => {
|
||||
expect(hasTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
|
||||
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
|
||||
expect(
|
||||
hasTracingPublicConfig(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
@@ -106,7 +106,7 @@ describe("resolveCloudPublicConfig", () => {
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
hasTracingPublicConfig(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
|
||||
@@ -70,13 +70,13 @@ type Configured<T> = {
|
||||
readonly [Key in keyof T]: NonNullable<T[Key]>;
|
||||
};
|
||||
|
||||
type TracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
|
||||
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
|
||||
readonly observability: Configured<CloudPublicConfig["observability"]>;
|
||||
};
|
||||
|
||||
export function hasTracingPublicConfig(
|
||||
export function hasMobileTracingPublicConfig(
|
||||
config: CloudPublicConfig = resolveCloudPublicConfig(),
|
||||
): config is TracingPublicConfig {
|
||||
): config is MobileTracingPublicConfig {
|
||||
return Boolean(
|
||||
config.observability.tracesUrl &&
|
||||
config.observability.tracesDataset &&
|
||||
|
||||
@@ -1,26 +1,31 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { connectionStatusText } from "@t3tools/client-runtime/connection";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Alert, Pressable, View } from "react-native";
|
||||
import { Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
|
||||
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
|
||||
return connectionStatusText({
|
||||
phase: environment.connectionState,
|
||||
error: environment.connectionError,
|
||||
traceId: environment.connectionErrorTraceId,
|
||||
});
|
||||
if (environment.connectionError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (environment.connectionState) {
|
||||
case "ready":
|
||||
return "Connected";
|
||||
case "connecting":
|
||||
return "Connecting";
|
||||
case "reconnecting":
|
||||
return "Reconnecting";
|
||||
case "disconnected":
|
||||
return null;
|
||||
case "idle":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function ConnectionEnvironmentRow(props: {
|
||||
@@ -32,7 +37,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
readonly onUpdate: (
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => Promise<AtomCommandResult<unknown, unknown>>;
|
||||
) => void;
|
||||
}) {
|
||||
const [label, setLabel] = useState(props.environment.environmentLabel);
|
||||
const [url, setUrl] = useState(props.environment.displayUrl);
|
||||
@@ -42,25 +47,13 @@ export function ConnectionEnvironmentRow(props: {
|
||||
const primaryFg = useThemeColor("--color-primary-foreground");
|
||||
const dangerFg = useThemeColor("--color-danger-foreground");
|
||||
const statusLabel = connectionStatusLabel(props.environment);
|
||||
const statusTraceId = props.environment.connectionErrorTraceId;
|
||||
const hasConnectionFailure = props.environment.connectionError !== null;
|
||||
const isRetrying =
|
||||
props.environment.connectionState === "connecting" ||
|
||||
props.environment.connectionState === "reconnecting";
|
||||
const handleSave = useCallback(async () => {
|
||||
const result = await props.onUpdate(props.environment.environmentId, {
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
props.onUpdate(props.environment.environmentId, {
|
||||
label: label.trim(),
|
||||
displayUrl: url.trim(),
|
||||
});
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
props.onToggle();
|
||||
return;
|
||||
}
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not update environment",
|
||||
error instanceof Error ? error.message : "The environment could not be updated.",
|
||||
);
|
||||
props.onToggle();
|
||||
}, [label, url, props]);
|
||||
|
||||
return (
|
||||
@@ -71,7 +64,10 @@ export function ConnectionEnvironmentRow(props: {
|
||||
>
|
||||
<ConnectionStatusDot
|
||||
state={props.environment.connectionState}
|
||||
pulse={isRetrying}
|
||||
pulse={
|
||||
props.environment.connectionState === "connecting" ||
|
||||
props.environment.connectionState === "reconnecting"
|
||||
}
|
||||
size={8}
|
||||
/>
|
||||
|
||||
@@ -86,35 +82,16 @@ export function ConnectionEnvironmentRow(props: {
|
||||
{props.environment.displayUrl}
|
||||
</Text>
|
||||
{statusLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[12px] leading-[16px]",
|
||||
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={props.expanded ? undefined : 1}
|
||||
selectable={props.expanded}
|
||||
>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{statusLabel}
|
||||
{statusTraceId ? (
|
||||
<>
|
||||
{" Trace ID: "}
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className="underline"
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(statusTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
style={{ textDecorationStyle: "dotted" }}
|
||||
>
|
||||
{statusTraceId}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.environment.connectionError ? (
|
||||
<Text
|
||||
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
|
||||
numberOfLines={2}
|
||||
>
|
||||
{props.environment.connectionError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -11,19 +11,12 @@ import Animated, {
|
||||
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
|
||||
export type ConnectionStatusDotState = RemoteClientConnectionState;
|
||||
|
||||
function statusDotTone(state: ConnectionStatusDotState): {
|
||||
function statusDotTone(state: RemoteClientConnectionState): {
|
||||
readonly dotColor: string;
|
||||
readonly haloColor: string;
|
||||
} {
|
||||
switch (state) {
|
||||
case "available":
|
||||
return {
|
||||
dotColor: "#9ca3af",
|
||||
haloColor: "rgba(156,163,175,0.42)",
|
||||
};
|
||||
case "connected":
|
||||
case "ready":
|
||||
return {
|
||||
dotColor: "#34d399",
|
||||
haloColor: "rgba(52,211,153,0.48)",
|
||||
@@ -34,8 +27,8 @@ function statusDotTone(state: ConnectionStatusDotState): {
|
||||
dotColor: "#f59e0b",
|
||||
haloColor: "rgba(245,158,11,0.5)",
|
||||
};
|
||||
case "offline":
|
||||
case "error":
|
||||
case "idle":
|
||||
case "disconnected":
|
||||
return {
|
||||
dotColor: "#ef4444",
|
||||
haloColor: "rgba(239,68,68,0.48)",
|
||||
@@ -70,7 +63,7 @@ function usePulseAnimation(pulse: boolean) {
|
||||
}
|
||||
|
||||
export function ConnectionStatusDot(props: {
|
||||
readonly state: ConnectionStatusDotState;
|
||||
readonly state: RemoteClientConnectionState;
|
||||
readonly pulse: boolean;
|
||||
readonly size?: number;
|
||||
}) {
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import {
|
||||
type EnvironmentConnectionPhase,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { ActivityIndicator, Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
function noticeTitle(phase: EnvironmentConnectionPhase, environmentLabel: string): string {
|
||||
switch (phase) {
|
||||
case "offline":
|
||||
return "You are offline";
|
||||
case "connecting":
|
||||
return `Connecting to ${environmentLabel}...`;
|
||||
case "reconnecting":
|
||||
return `Reconnecting to ${environmentLabel}...`;
|
||||
case "error":
|
||||
return `${environmentLabel} is unavailable`;
|
||||
case "available":
|
||||
return `${environmentLabel} is disconnected`;
|
||||
case "connected":
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function noticeDetail(
|
||||
phase: EnvironmentConnectionPhase,
|
||||
resourceName: string,
|
||||
error: string | null,
|
||||
): string {
|
||||
if (error) {
|
||||
return `The app will keep retrying automatically. ${error}`;
|
||||
}
|
||||
|
||||
switch (phase) {
|
||||
case "offline":
|
||||
return `Cached data remains available. The ${resourceName} will load when your connection returns.`;
|
||||
case "connecting":
|
||||
case "reconnecting":
|
||||
return `The ${resourceName} will load as soon as the environment is ready.`;
|
||||
case "available":
|
||||
case "error":
|
||||
return `Reconnect the environment to load the ${resourceName}.`;
|
||||
case "connected":
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function EnvironmentConnectionNotice(props: {
|
||||
readonly environmentLabel: string;
|
||||
readonly connection: EnvironmentConnectionPresentation;
|
||||
readonly resourceName: string;
|
||||
readonly onRetry: () => void;
|
||||
}) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const isRetrying =
|
||||
props.connection.phase === "connecting" || props.connection.phase === "reconnecting";
|
||||
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center px-8">
|
||||
<View className="max-w-[320px] items-center gap-3">
|
||||
{isRetrying ? (
|
||||
<ActivityIndicator size="small" color={iconColor} />
|
||||
) : (
|
||||
<SymbolView
|
||||
name={props.connection.phase === "offline" ? "wifi.slash" : "bolt.horizontal.circle"}
|
||||
size={24}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Text className="text-center text-[17px] font-t3-bold leading-[22px] text-foreground">
|
||||
{noticeTitle(props.connection.phase, props.environmentLabel)}
|
||||
</Text>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
|
||||
{props.connection.traceId ? (
|
||||
<>
|
||||
{" Trace ID: "}
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className="underline decoration-dotted"
|
||||
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
|
||||
>
|
||||
{props.connection.traceId}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
{props.connection.phase !== "offline" ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
className="mt-1 rounded-full bg-subtle px-4 py-2.5 active:opacity-70"
|
||||
onPress={props.onRetry}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Retry now</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
|
||||
export function connectionTone(state: RemoteClientConnectionState): StatusTone {
|
||||
switch (state) {
|
||||
case "connected":
|
||||
case "ready":
|
||||
return {
|
||||
label: "Connected",
|
||||
pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
|
||||
@@ -21,21 +21,15 @@ export function connectionTone(state: RemoteClientConnectionState): StatusTone {
|
||||
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
|
||||
textClassName: "text-sky-700 dark:text-sky-300",
|
||||
};
|
||||
case "error":
|
||||
case "disconnected":
|
||||
return {
|
||||
label: "Connection failed",
|
||||
label: "Disconnected",
|
||||
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
|
||||
textClassName: "text-rose-700 dark:text-rose-300",
|
||||
};
|
||||
case "offline":
|
||||
case "idle":
|
||||
return {
|
||||
label: "Offline",
|
||||
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
|
||||
textClassName: "text-rose-700 dark:text-rose-300",
|
||||
};
|
||||
case "available":
|
||||
return {
|
||||
label: "Available",
|
||||
label: "Idle",
|
||||
pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
|
||||
textClassName: "text-neutral-600 dark:text-neutral-300",
|
||||
};
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { splitEnvironmentSections } from "./environmentSections";
|
||||
|
||||
function connectedEnvironment(
|
||||
input: Omit<Partial<ConnectedEnvironmentSummary>, "environmentId"> & {
|
||||
readonly environmentId: string;
|
||||
readonly isRelayManaged: boolean;
|
||||
},
|
||||
): ConnectedEnvironmentSummary {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(input.environmentId),
|
||||
environmentLabel: input.environmentLabel ?? input.environmentId,
|
||||
displayUrl: input.displayUrl ?? `https://${input.environmentId}.example.test/`,
|
||||
isRelayManaged: input.isRelayManaged,
|
||||
connectionState: input.connectionState ?? "connected",
|
||||
connectionError: input.connectionError ?? null,
|
||||
connectionErrorTraceId: input.connectionErrorTraceId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
label: environmentId,
|
||||
endpoint: {
|
||||
httpBaseUrl: `https://${environmentId}.cloud.example.test/`,
|
||||
wsBaseUrl: `wss://${environmentId}.cloud.example.test/ws`,
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
linkedAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("mobile environment settings sections", () => {
|
||||
it("keeps saved relay-managed connections under T3 Cloud", () => {
|
||||
const local = connectedEnvironment({
|
||||
environmentId: "environment-local",
|
||||
isRelayManaged: false,
|
||||
});
|
||||
const cloud = connectedEnvironment({
|
||||
environmentId: "environment-cloud",
|
||||
isRelayManaged: true,
|
||||
});
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [cloud, local],
|
||||
cloudEnvironments: [
|
||||
cloudEnvironment("environment-cloud"),
|
||||
cloudEnvironment("environment-new"),
|
||||
],
|
||||
});
|
||||
|
||||
expect(sections.localEnvironments).toEqual([local]);
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(
|
||||
sections.availableCloudEnvironments.map((environment) => environment.environmentId),
|
||||
).toEqual([EnvironmentId.make("environment-new")]);
|
||||
});
|
||||
|
||||
it("keeps saved relay-managed connections visible when cloud listing is unavailable", () => {
|
||||
const cloud = connectedEnvironment({
|
||||
environmentId: "environment-cloud",
|
||||
isRelayManaged: true,
|
||||
connectionState: "reconnecting",
|
||||
connectionError: "Environment did not respond before the connection timeout.",
|
||||
});
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [cloud],
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
|
||||
expect(sections.localEnvironments).toEqual([]);
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(sections.availableCloudEnvironments).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an available saved relay environment as a fallback when listing is unavailable", () => {
|
||||
const cloud = connectedEnvironment({
|
||||
environmentId: "environment-cloud",
|
||||
isRelayManaged: true,
|
||||
connectionState: "available",
|
||||
});
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [cloud],
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(sections.availableCloudEnvironments).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not duplicate a saved relay environment in the available cloud listing", () => {
|
||||
const cloud = connectedEnvironment({
|
||||
environmentId: "environment-cloud",
|
||||
isRelayManaged: true,
|
||||
connectionState: "available",
|
||||
});
|
||||
const listedCloud = cloudEnvironment("environment-cloud");
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [cloud],
|
||||
cloudEnvironments: [listedCloud],
|
||||
});
|
||||
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(sections.availableCloudEnvironments).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps failed relay environments in the local connection row", () => {
|
||||
const cloud = connectedEnvironment({
|
||||
environmentId: "environment-cloud",
|
||||
isRelayManaged: true,
|
||||
connectionState: "error",
|
||||
connectionError: "Connection failed.",
|
||||
});
|
||||
|
||||
const sections = splitEnvironmentSections({
|
||||
connectedEnvironments: [cloud],
|
||||
cloudEnvironments: [cloudEnvironment("environment-cloud")],
|
||||
});
|
||||
|
||||
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
|
||||
expect(sections.availableCloudEnvironments).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
|
||||
export interface EnvironmentSectionsInput {
|
||||
readonly connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly cloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord> | null;
|
||||
}
|
||||
|
||||
export interface EnvironmentSections {
|
||||
readonly localEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly availableCloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord>;
|
||||
}
|
||||
|
||||
export function splitEnvironmentSections(input: EnvironmentSectionsInput): EnvironmentSections {
|
||||
const savedEnvironmentIds = new Set(
|
||||
input.connectedEnvironments.map((environment) => environment.environmentId),
|
||||
);
|
||||
|
||||
return {
|
||||
localEnvironments: input.connectedEnvironments.filter(
|
||||
(environment) => !environment.isRelayManaged,
|
||||
),
|
||||
connectedCloudEnvironments: input.connectedEnvironments.filter(
|
||||
(environment) => environment.isRelayManaged,
|
||||
),
|
||||
availableCloudEnvironments: (input.cloudEnvironments ?? []).filter(
|
||||
(environment) => !savedEnvironmentIds.has(environment.environmentId),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
RelayConnectionRegistration,
|
||||
RelayConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type {
|
||||
RelayClientEnvironmentRecord,
|
||||
RelayEnvironmentStatusResponse,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Option from "effect/Option";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import {
|
||||
connectPairingUrl as connectPairingUrlAtom,
|
||||
updateBearerConnection,
|
||||
} from "../../connection/onboarding";
|
||||
import { useEnvironments } from "../../state/environments";
|
||||
import { relayEnvironmentDiscovery } from "../../state/relay";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { projectWorkspaceEnvironment, type WorkspaceEnvironment } from "../../state/workspaceModel";
|
||||
|
||||
export interface RelayEnvironmentView {
|
||||
readonly environment: RelayClientEnvironmentRecord;
|
||||
readonly availability: "checking" | "online" | "offline" | "error";
|
||||
readonly status: RelayEnvironmentStatusResponse | null;
|
||||
readonly error: string | null;
|
||||
readonly traceId: string | null;
|
||||
}
|
||||
|
||||
export function useConnectionController() {
|
||||
const { environments } = useEnvironments();
|
||||
const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
|
||||
const connectPairingUrlMutation = useAtomCommand(connectPairingUrlAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });
|
||||
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
|
||||
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
|
||||
const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
|
||||
const refreshRelayEnvironments = useAtomCommand(
|
||||
relayEnvironmentDiscovery.refresh,
|
||||
"relay environment refresh",
|
||||
);
|
||||
|
||||
const connectedEnvironments = useMemo<ReadonlyArray<WorkspaceEnvironment>>(
|
||||
() => environments.map(projectWorkspaceEnvironment),
|
||||
[environments],
|
||||
);
|
||||
const registeredIds = useMemo(
|
||||
() => new Set(connectedEnvironments.map((environment) => environment.environmentId)),
|
||||
[connectedEnvironments],
|
||||
);
|
||||
const relayEnvironments = useMemo<ReadonlyArray<RelayEnvironmentView>>(
|
||||
() =>
|
||||
[...discovery.environments.values()].map((entry) => ({
|
||||
environment: entry.environment,
|
||||
availability: entry.availability,
|
||||
status: Option.getOrNull(entry.status),
|
||||
error: Option.getOrNull(entry.error)?.message ?? null,
|
||||
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
|
||||
})),
|
||||
[discovery.environments],
|
||||
);
|
||||
const availableRelayEnvironments = useMemo(
|
||||
() => relayEnvironments.filter((entry) => !registeredIds.has(entry.environment.environmentId)),
|
||||
[registeredIds, relayEnvironments],
|
||||
);
|
||||
|
||||
const connectPairingUrl = useCallback(
|
||||
(pairingUrl: string) => connectPairingUrlMutation(pairingUrl),
|
||||
[connectPairingUrlMutation],
|
||||
);
|
||||
const connectRelayEnvironment = useCallback(
|
||||
(environment: RelayClientEnvironmentRecord) =>
|
||||
registerEnvironment(
|
||||
new RelayConnectionRegistration({
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
[registerEnvironment],
|
||||
);
|
||||
const removeEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => removeEnvironmentMutation(environmentId),
|
||||
[removeEnvironmentMutation],
|
||||
);
|
||||
const retryEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId) => retryEnvironmentMutation(environmentId),
|
||||
[retryEnvironmentMutation],
|
||||
);
|
||||
const updateEnvironment = useCallback(
|
||||
(
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) =>
|
||||
updateBearer({
|
||||
environmentId,
|
||||
label: updates.label,
|
||||
httpBaseUrl: updates.displayUrl,
|
||||
}),
|
||||
[updateBearer],
|
||||
);
|
||||
|
||||
return {
|
||||
connectedEnvironments,
|
||||
relayEnvironments,
|
||||
availableRelayEnvironments,
|
||||
relayDiscovery: {
|
||||
isRefreshing: discovery.refreshing,
|
||||
isOffline: discovery.offline,
|
||||
error: Option.getOrNull(discovery.error)?.message ?? null,
|
||||
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
|
||||
},
|
||||
connectPairingUrl,
|
||||
connectRelayEnvironment,
|
||||
removeEnvironment,
|
||||
retryEnvironment,
|
||||
updateEnvironment,
|
||||
refreshRelayEnvironments,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user