Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f6f68359c |
No files matched your search
+45
-11
@@ -22,9 +22,6 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -34,9 +31,6 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -60,17 +54,57 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
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
|
||||
|
||||
@@ -272,29 +272,21 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -314,11 +306,6 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -531,19 +518,6 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -551,13 +525,6 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -612,24 +579,6 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -54,7 +54,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -54,7 +54,6 @@ function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarne
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -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"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -112,56 +112,41 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk(
|
||||
"stderr",
|
||||
new TextEncoder().encode("normal shutdown\n"),
|
||||
);
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
yield* Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
);
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -169,98 +154,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -21,10 +21,8 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -32,13 +30,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
@@ -114,84 +113,10 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [
|
||||
...session.chunks,
|
||||
{
|
||||
streamName,
|
||||
chunk: retainedChunk,
|
||||
},
|
||||
];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) {
|
||||
break;
|
||||
}
|
||||
if (first.chunk.byteLength <= overflow) {
|
||||
overflow -= first.chunk.byteLength;
|
||||
byteLength -= first.chunk.byteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
chunk: first.chunk.slice(overflow),
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
@@ -376,86 +301,45 @@ const backendOutputLogLayer = Layer.effect(
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
|
||||
return Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) => {
|
||||
return {
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn(
|
||||
"desktop.observability.backendOutput.writeSessionBoundary",
|
||||
)(function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
|
||||
function* ({ details }) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [
|
||||
current,
|
||||
Option.map(current, (value) => ({
|
||||
...value,
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
})),
|
||||
]);
|
||||
if (Option.isNone(session)) {
|
||||
return;
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "START",
|
||||
details: session.value.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.value.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
} satisfies DesktopBackendOutputLogShape;
|
||||
},
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -41,7 +41,6 @@ function makeEnvironmentLayer(
|
||||
options?: {
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
@@ -52,7 +51,7 @@ function makeEnvironmentLayer(
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -193,39 +192,4 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("passes the packaged resource monitor path to the backend", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -56,42 +56,6 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
BackendObservabilitySettings,
|
||||
never,
|
||||
@@ -125,7 +89,6 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -152,12 +115,6 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
@@ -199,14 +156,9 @@ export const layer = Layer.effect(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resourceMonitorPath,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
@@ -24,15 +23,11 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -48,8 +43,6 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
@@ -66,7 +59,6 @@ function makeProcess(options?: {
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -78,7 +70,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
getOutputFd: () => Stream.empty,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -115,7 +107,6 @@ function makeManagerLayer(input: {
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly desktopTelemetryPublisher?: Partial<DesktopTelemetryPublisher.DesktopTelemetryPublisherShape>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -129,21 +120,12 @@ function makeManagerLayer(input: {
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
: DesktopState.layer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -202,7 +184,8 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -225,8 +208,6 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
@@ -237,88 +218,6 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
|
||||
const outputDrainStarted = yield* Deferred.make<void>();
|
||||
const outputChunks = yield* Ref.make<Array<string>>([]);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.succeed(outputDrainStarted, void 0).pipe(
|
||||
Effect.andThen(Effect.sleep(Duration.millis(50))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
writeOutputChunk: (_streamName, chunk) =>
|
||||
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
|
||||
persistFailure: () =>
|
||||
Ref.get(outputChunks).pipe(
|
||||
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
@@ -356,7 +255,8 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -389,8 +289,6 @@ describe("DesktopBackendManager", () => {
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReady = yield* Ref.make(false);
|
||||
const quitting = yield* Ref.make(false);
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -422,15 +320,6 @@ describe("DesktopBackendManager", () => {
|
||||
desktopWindow: {
|
||||
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -450,8 +339,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.stop();
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
|
||||
const stoppedSnapshot = yield* manager.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReady));
|
||||
@@ -465,7 +352,6 @@ describe("DesktopBackendManager", () => {
|
||||
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -485,9 +371,6 @@ describe("DesktopBackendManager", () => {
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -495,7 +378,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(499));
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
@@ -552,13 +434,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* manager.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* manager.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -16,21 +16,17 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
@@ -39,7 +35,6 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
|
||||
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.millis(250);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
@@ -93,10 +88,6 @@ class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnErro
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
@@ -233,7 +224,6 @@ function drainBackendOutput(
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
@@ -243,23 +233,6 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
@@ -274,47 +247,23 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
|
||||
Stream.runForEach(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
if (options.captureOutput) {
|
||||
outputFibers.push(
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped),
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped),
|
||||
);
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
@@ -325,12 +274,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exit = describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
|
||||
return exit;
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
@@ -339,7 +283,6 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -476,13 +419,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
if (isCurrentRun) {
|
||||
if (Option.isSome(pid)) {
|
||||
if (nextState.desiredRunning) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
@@ -496,14 +436,13 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
}));
|
||||
yield* backendOutputLog.beginSession({
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
@@ -536,13 +475,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -653,7 +589,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options).pipe(Effect.andThen(backendOutputLog.discardSession)),
|
||||
onSome: (run) => closeRun(run, options),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ export interface ElectronAppShape {
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -102,7 +101,6 @@ const make = ElectronApp.of({
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
|
||||
@@ -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,89 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export interface ElectronPowerMonitorShape {
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
ElectronPowerMonitorShape
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -19,7 +19,6 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -30,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";
|
||||
@@ -46,7 +44,6 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
@@ -106,7 +103,6 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
DesktopSecretStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -121,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,
|
||||
@@ -149,7 +145,6 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -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,196 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,264 +0,0 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly suspended: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
DesktopTelemetryPublisherShape
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return { ...state, locked: booleanState(event.value) };
|
||||
case "suspended":
|
||||
return { ...state, suspended: event.value };
|
||||
case "onBattery":
|
||||
return { ...state, onBattery: booleanState(event.value) };
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
idleSeconds,
|
||||
locked,
|
||||
suspended: currentPower.suspended,
|
||||
onBattery: booleanState(onBattery),
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: currentPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: currentPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: metric.creationTime,
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
Ref.get(latest).pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.fromPubSub(changes),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -40,7 +40,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 778 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user