Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4501ba47ce | ||
|
|
22cb3451c4 | ||
|
|
9544e72d08 | ||
|
|
938b19a6bb | ||
|
|
3b56dc17a5 | ||
|
|
d2c0a6a48f | ||
|
|
1cf3647da6 | ||
|
|
53d0107759 | ||
|
|
60b16d1f28 | ||
|
|
ab0baaa886 | ||
|
|
753bc4672d | ||
|
|
e29ad7604b | ||
|
|
cdaba7fa8b | ||
|
|
fbf6263876 | ||
|
|
c08b968f4e | ||
|
|
d9f59be704 | ||
|
|
a4446e263d | ||
|
|
494350cc0b | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 |
No files matched your search
@@ -8,6 +8,13 @@
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
# returns a different RP ID or when multiple domains must be entitled.
|
||||
# T3CODE_APPLE_TEAM_ID=ABC1234567
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
test:
|
||||
name: Test
|
||||
|
||||
@@ -2,10 +2,12 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -425,6 +425,9 @@ jobs:
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
|
||||
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
|
||||
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
@@ -452,9 +455,21 @@ jobs:
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
|
||||
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
|
||||
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
|
||||
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
|
||||
security cms -D -i "$profile_path" >/dev/null
|
||||
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
|
||||
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
|
||||
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/electron": "catalog:",
|
||||
"@clerk/electron-passkeys": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
@@ -20,6 +22,7 @@
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
|
||||
@@ -31,20 +31,12 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 11;
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function resolveDevelopmentProtocolCallbackPort() {
|
||||
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
|
||||
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
|
||||
return configuredPort + 1;
|
||||
}
|
||||
return 13774;
|
||||
}
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
@@ -100,7 +92,6 @@ function shellSingleQuote(value) {
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
|
||||
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
@@ -109,23 +100,12 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
|
||||
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
'for arg in "$@"; do',
|
||||
' case "$arg" in',
|
||||
" t3code-dev://auth/callback*)",
|
||||
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
|
||||
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
|
||||
" fi",
|
||||
" ;;",
|
||||
" esac",
|
||||
"done",
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
@@ -163,6 +163,16 @@ const bootstrap = Effect.gen(function* () {
|
||||
}
|
||||
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
|
||||
const backendConfig = yield* serverExposure.backendConfig;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const rendererTarget = environment.isDevelopment
|
||||
? Option.getOrThrow(environment.devServerUrl)
|
||||
: backendConfig.httpBaseUrl;
|
||||
yield* electronProtocol.registerDesktopProtocol({
|
||||
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
|
||||
targetOrigin: rendererTarget,
|
||||
backendOrigin: backendConfig.httpBaseUrl,
|
||||
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
|
||||
});
|
||||
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
|
||||
baseUrl: backendConfig.httpBaseUrl.href,
|
||||
});
|
||||
@@ -189,9 +199,8 @@ const startup = Effect.gen(function* () {
|
||||
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
@@ -209,7 +218,7 @@ const startup = Effect.gen(function* () {
|
||||
|
||||
yield* appIdentity.configure;
|
||||
yield* lifecycle.register;
|
||||
yield* cloudAuth.configure;
|
||||
yield* clerk.configure;
|
||||
|
||||
yield* electronApp.whenReady.pipe(
|
||||
Effect.withSpan("desktop.electron.whenReady"),
|
||||
@@ -218,7 +227,6 @@ const startup = Effect.gen(function* () {
|
||||
yield* logStartupInfo("app ready");
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* electronProtocol.registerDesktopFileProtocol;
|
||||
yield* updates.configure;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
@@ -63,7 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
@@ -73,7 +73,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
png,
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none()),
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
|
||||
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
|
||||
const { env, ...environmentOverrides } = overrides;
|
||||
|
||||
@@ -18,14 +18,12 @@ const AppPackageMetadata = Schema.Struct({
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
export interface DesktopAppIdentityShape {
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
DesktopAppIdentityShape
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
|
||||
@@ -12,14 +12,13 @@ export interface DesktopIconPaths {
|
||||
readonly png: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface DesktopAssetsShape {
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
) {}
|
||||
export class DesktopAssets extends Context.Service<
|
||||
DesktopAssets,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
fileName: string,
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
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 output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -0,0 +1,94 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
storageAdapter: {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
storageMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron", () => ({
|
||||
createClerkBridge: createClerkBridgeMock,
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
describe("DesktopClerk", () => {
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(
|
||||
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
|
||||
"clerk.t3.codes",
|
||||
);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment: true,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(
|
||||
Layer.build(
|
||||
DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme: "t3code-dev", host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn() };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme, host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { createClerkBridge } from "@clerk/electron";
|
||||
import { storage } from "@clerk/electron/storage";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopClerk extends Context.Service<
|
||||
DesktopClerk,
|
||||
{
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopClerk") {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
if (!normalizedKey) return undefined;
|
||||
|
||||
try {
|
||||
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
|
||||
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? undefined
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
renderer: {
|
||||
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
|
||||
host: ElectronProtocol.DESKTOP_HOST,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
|
||||
(bridge) => Effect.sync(() => bridge.cleanup()),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
yield* electronApp.on("second-instance", () => {
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.clerk.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClerk, make);
|
||||
@@ -1,302 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthHarness {
|
||||
readonly app: ElectronApp.ElectronAppShape;
|
||||
readonly window: ElectronWindow.ElectronWindowShape;
|
||||
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
|
||||
readonly protocolRegistrations: {
|
||||
readonly protocol: string;
|
||||
readonly path?: string;
|
||||
readonly args?: readonly string[];
|
||||
}[];
|
||||
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
|
||||
readonly reveals: unknown[];
|
||||
readonly layer: Layer.Layer<
|
||||
| DesktopCloudAuth.DesktopCloudAuth
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronWindow.ElectronWindow
|
||||
>;
|
||||
}
|
||||
|
||||
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
|
||||
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
|
||||
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
|
||||
const sends: CloudAuthHarness["sends"] = [];
|
||||
const reveals: unknown[] = [];
|
||||
const mainWindow = { id: "main-window" };
|
||||
|
||||
const app = ElectronApp.ElectronApp.of({
|
||||
metadata: Effect.succeed({
|
||||
appVersion: "0.0.0-test",
|
||||
appPath: "/tmp/t3-code-test",
|
||||
isPackaged: !input.isDevelopment,
|
||||
resourcesPath: "/tmp/t3-code-test/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
protocolRegistrations.push({
|
||||
protocol,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(args === undefined ? {} : { args }),
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
const erasedListener = listener as (...args: readonly unknown[]) => void;
|
||||
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
|
||||
}),
|
||||
});
|
||||
|
||||
const window = ElectronWindow.ElectronWindow.of({
|
||||
create: () => Effect.die("not used"),
|
||||
main: Effect.succeed(Option.some(mainWindow as never)),
|
||||
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: (target) =>
|
||||
Effect.sync(() => {
|
||||
reveals.push(target);
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
sends.push({ channel, args });
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
});
|
||||
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
isDevelopment: input.isDevelopment,
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
|
||||
|
||||
return {
|
||||
app,
|
||||
window,
|
||||
listeners,
|
||||
protocolRegistrations,
|
||||
sends,
|
||||
reveals,
|
||||
layer: Layer.mergeAll(
|
||||
DesktopCloudAuth.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
Layer.succeed(ElectronApp.ElectronApp, app),
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, window),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function emitAppEvent(
|
||||
harness: CloudAuthHarness,
|
||||
eventName: string,
|
||||
...args: readonly unknown[]
|
||||
): void {
|
||||
for (const listener of harness.listeners.get(eventName) ?? []) {
|
||||
listener(...args);
|
||||
}
|
||||
}
|
||||
|
||||
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
|
||||
|
||||
describe("DesktopCloudAuth", () => {
|
||||
it("uses separate callback schemes for packaged and development builds", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
|
||||
"t3code",
|
||||
);
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
|
||||
"t3code-dev",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only the expected scheme, host, path, and state", () => {
|
||||
assert.isNotNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native development callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code-dev",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code-dev://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
let prevented = false;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => (prevented = true) },
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.isTrue(prevented);
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.isString(harness.protocolRegistrations[0]?.path);
|
||||
assert.isArray(harness.protocolRegistrations[0]?.args);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.lengthOf(harness.reveals, 1);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
|
||||
const harness = makeHarness({ isDevelopment: false });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const validCallback = new URL(redirectUrl);
|
||||
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
const invalidCallback = new URL(validCallback);
|
||||
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
invalidCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
assert.deepEqual(harness.sends, []);
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code"],
|
||||
);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [validCallback.toString()],
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"routes second-instance callbacks and reveals the window for non-callback launches",
|
||||
() => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
const revealCountAfterCallback = harness.reveals.length;
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.equal(revealCountAfterCallback, 1);
|
||||
assert.equal(harness.reveals.length, 2);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,330 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
|
||||
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
|
||||
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
|
||||
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
|
||||
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
|
||||
|
||||
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
|
||||
"DesktopCloudAuthCallbackServerError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to start the desktop cloud auth callback server.";
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingCloudAuthRequest {
|
||||
readonly state: string;
|
||||
readonly redirectUrl: string;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthShape {
|
||||
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
|
||||
"@t3tools/desktop/app/DesktopCloudAuth",
|
||||
) {}
|
||||
|
||||
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
|
||||
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
|
||||
}
|
||||
|
||||
export function buildCloudAuthCallbackUrl(input: {
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): string {
|
||||
const url = new URL(
|
||||
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
|
||||
);
|
||||
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function parseCloudAuthCallbackUrl(input: {
|
||||
readonly rawUrl: unknown;
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
if (typeof input.rawUrl !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(input.rawUrl);
|
||||
if (url.protocol !== `${input.scheme}:`) return null;
|
||||
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
|
||||
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
|
||||
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function findCloudAuthCallbackUrl(input: {
|
||||
readonly values: readonly unknown[];
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
for (const value of input.values) {
|
||||
const url = parseCloudAuthCallbackUrl({
|
||||
rawUrl: value,
|
||||
scheme: input.scheme,
|
||||
state: input.state,
|
||||
});
|
||||
if (url) return url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveProtocolClientLaunchArgs(input: {
|
||||
readonly argv: readonly string[];
|
||||
}): readonly string[] {
|
||||
return input.argv.slice(1);
|
||||
}
|
||||
|
||||
function resolveConfiguredProtocolClient(): {
|
||||
readonly path: string;
|
||||
readonly args: readonly string[];
|
||||
} | null {
|
||||
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
|
||||
if (!path) return null;
|
||||
|
||||
return {
|
||||
path,
|
||||
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
|
||||
.split("\n")
|
||||
.map((arg) => arg.trim())
|
||||
.filter((arg) => arg.length > 0),
|
||||
};
|
||||
}
|
||||
|
||||
function isProtocolRegistrationManagedExternally(): boolean {
|
||||
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
|
||||
}
|
||||
|
||||
function resolveProtocolCallbackForwardUrl(): URL | null {
|
||||
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
|
||||
if (!rawUrl) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "http:") return null;
|
||||
if (url.hostname !== "127.0.0.1") return null;
|
||||
if (url.pathname !== "/auth/callback") return null;
|
||||
if (!url.port) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
|
||||
request?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
|
||||
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function ignoreCloudAuthCallback(_rawUrl: string) {}
|
||||
|
||||
function startProtocolCallbackForwardServer(
|
||||
callbackUrl: URL,
|
||||
dispatch: (rawUrl: string) => void,
|
||||
): Effect.Effect<void, never, Scope.Scope> {
|
||||
const port = Number.parseInt(callbackUrl.port, 10);
|
||||
const routesLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/auth/callback",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const rawUrl = yield* request.text;
|
||||
yield* Effect.sync(() => {
|
||||
dispatch(rawUrl);
|
||||
});
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const NodeHttp = yield* Effect.promise(() => import("node:http"));
|
||||
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: callbackUrl.hostname,
|
||||
port,
|
||||
});
|
||||
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
|
||||
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
|
||||
const makeCloudAuthRequestState = Effect.gen(function* () {
|
||||
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
|
||||
return `${left}${right}`.replaceAll("-", "");
|
||||
});
|
||||
|
||||
return DesktopCloudAuth.of({
|
||||
createRequest: Effect.gen(function* () {
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
const state = yield* makeCloudAuthRequestState.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
|
||||
);
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
|
||||
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
|
||||
const timeout = createCloudAuthRequestTimeout(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
});
|
||||
pendingAuthRequest = {
|
||||
state,
|
||||
redirectUrl,
|
||||
close: () => clearTimeout(timeout),
|
||||
};
|
||||
return redirectUrl;
|
||||
}),
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const scope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
}),
|
||||
);
|
||||
|
||||
if (isProtocolRegistrationManagedExternally()) {
|
||||
// Development macOS launchers set the default URL handler before the stock Electron
|
||||
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
|
||||
} else if (environment.isDevelopment) {
|
||||
const configuredClient = resolveConfiguredProtocolClient();
|
||||
if (configuredClient) {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
configuredClient.path,
|
||||
configuredClient.args,
|
||||
);
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
process.execPath,
|
||||
resolveProtocolClientLaunchArgs({ argv: process.argv }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(scheme);
|
||||
}
|
||||
|
||||
dispatchCloudAuthCallback = (rawUrl: string) => {
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
|
||||
: null;
|
||||
if (!callbackUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* electronWindow.sendAll(
|
||||
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
|
||||
if (environment.isDevelopment && protocolCallbackForwardUrl) {
|
||||
yield* startProtocolCallbackForwardServer(
|
||||
protocolCallbackForwardUrl,
|
||||
dispatchCloudAuthCallback,
|
||||
);
|
||||
}
|
||||
|
||||
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
|
||||
if (!hasInstanceLock) {
|
||||
return yield* electronApp.quit;
|
||||
}
|
||||
|
||||
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
|
||||
event.preventDefault?.();
|
||||
dispatchCloudAuthCallback(rawUrl);
|
||||
});
|
||||
|
||||
yield* electronApp.on<[Electron.Event, readonly string[]]>(
|
||||
"second-instance",
|
||||
(_event, argv) => {
|
||||
const values = resolveProtocolClientLaunchArgs({ argv });
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
|
||||
: null;
|
||||
if (callbackUrl) {
|
||||
dispatchCloudAuthCallback(callbackUrl.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopCloudAuth, make);
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
function makeSafeStorageLayer(input: { readonly available: boolean }) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(input.available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
|
||||
decryptString: (value) => {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
return Effect.fail(
|
||||
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted token"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopCloudAuthTokenStore.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
const withTokenStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
|
||||
input?: { readonly encryptionAvailable?: boolean },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-cloud-auth-token-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopCloudAuthTokenStore", () => {
|
||||
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
|
||||
|
||||
yield* tokenStore.clear;
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
{ encryptionAvailable: false },
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthTokenDocument {
|
||||
readonly version: number;
|
||||
readonly encryptedClientJwt: string;
|
||||
}
|
||||
|
||||
const CloudAuthTokenDocumentSchema = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
encryptedClientJwt: Schema.String,
|
||||
});
|
||||
|
||||
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
|
||||
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
|
||||
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
|
||||
|
||||
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop cloud auth token.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthTokenStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopCloudAuthTokenStoreDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
token: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopCloudAuthTokenStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStore extends Context.Service<
|
||||
DesktopCloudAuthTokenStore,
|
||||
DesktopCloudAuthTokenStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
tokenPath: string,
|
||||
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
|
||||
fileSystem.readFileString(tokenPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
|
||||
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly tokenPath: string;
|
||||
readonly document: CloudAuthTokenDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.tokenPath);
|
||||
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.tokenPath);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopCloudAuthTokenStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
|
||||
|
||||
return DesktopCloudAuthTokenStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, tokenPath);
|
||||
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
|
||||
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
tokenPath,
|
||||
document: { version: 1, encryptedClientJwt },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -11,10 +11,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import {
|
||||
type DesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
} from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
@@ -30,55 +27,53 @@ export interface MakeDesktopEnvironmentInput {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopEnvironmentShape {
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
|
||||
export class DesktopEnvironment extends Context.Service<
|
||||
DesktopEnvironment,
|
||||
DesktopEnvironmentShape
|
||||
{
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
@@ -136,9 +131,9 @@ function resolveDesktopRuntimeInfo(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
const make = Effect.fn("desktop.environment.make")(function* (
|
||||
input: MakeDesktopEnvironmentInput,
|
||||
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
|
||||
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const homeDirectory = input.homeDirectory;
|
||||
@@ -208,7 +203,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
runtimeInfo: resolveDesktopRuntimeInfo({
|
||||
platform: input.platform,
|
||||
processArch: input.processArch,
|
||||
@@ -250,4 +245,4 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
});
|
||||
|
||||
export const layer = (input: MakeDesktopEnvironmentInput) =>
|
||||
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
|
||||
Layer.effect(DesktopEnvironment, make(input));
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -10,63 +9,34 @@ import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdownModule from "./DesktopShutdown.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
export interface DesktopShutdownShape {
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
|
||||
) {}
|
||||
|
||||
const makeShutdown = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
|
||||
export { DesktopShutdown, layer as layerShutdown } from "./DesktopShutdown.ts";
|
||||
|
||||
export type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdown
|
||||
| DesktopShutdownModule.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| DesktopWindow.DesktopWindow
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronTheme.ElectronTheme;
|
||||
|
||||
export interface DesktopLifecycleShape {
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
|
||||
*/
|
||||
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
) {}
|
||||
export class DesktopLifecycle extends Context.Service<
|
||||
DesktopLifecycle,
|
||||
{
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLifecycle") {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-lifecycle");
|
||||
@@ -93,8 +63,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown;
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdownModule.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdownModule.DesktopShutdown;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
@@ -154,83 +124,82 @@ function quitFromSignal(
|
||||
);
|
||||
}
|
||||
|
||||
export const layer = Layer.succeed(
|
||||
DesktopLifecycle,
|
||||
DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
}
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
const make = DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
);
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopLifecycle, make);
|
||||
@@ -1,52 +1,20 @@
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
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_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
DesktopBackendOutputLogShape
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -82,160 +50,6 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
)<{
|
||||
readonly option: "maxBytes" | "maxFiles";
|
||||
readonly value: number;
|
||||
}> {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const readPersistedOtlpTracesUrl: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
@@ -260,90 +74,6 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
|
||||
return yield* readPersistedOtlpTracesUrl;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const backendOutputLogLayer = Layer.effect(
|
||||
DesktopBackendOutputLog,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
return Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn(
|
||||
"desktop.observability.backendOutput.writeSessionBoundary",
|
||||
)(function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
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 output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopLoggerLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
@@ -356,8 +86,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -375,8 +105,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -387,7 +117,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
backendOutputLogLayer,
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export class DesktopShutdown extends Context.Service<
|
||||
DesktopShutdown,
|
||||
{
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopShutdown") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopShutdown, make);
|
||||
@@ -3,19 +3,17 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export interface DesktopStateShape {
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
|
||||
"@t3tools/desktop/app/DesktopState",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
export class DesktopState extends Context.Service<
|
||||
DesktopState,
|
||||
Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
}),
|
||||
);
|
||||
{
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopState") {}
|
||||
|
||||
const make = Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopState, make);
|
||||
@@ -104,9 +104,9 @@ function decodeBootstrap(raw: string) {
|
||||
function makeManagerLayer(input: {
|
||||
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -127,7 +127,7 @@ function makeManagerLayer(input: {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected createMain"),
|
||||
ensureMain: Effect.die("unexpected ensureMain"),
|
||||
@@ -138,7 +138,7 @@ function makeManagerLayer(input: {
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
...input.desktopWindow,
|
||||
} satisfies DesktopWindow.DesktopWindowShape),
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: {},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3773,
|
||||
t3Home: "/tmp/t3",
|
||||
host: "127.0.0.1",
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
};
|
||||
|
||||
describe("DesktopLocalEnvironmentAuth", () => {
|
||||
it.effect("exchanges the desktop bootstrap credential only once", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestCount = yield* Ref.make(0);
|
||||
const httpClientLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Ref.update(requestCount, (count) => count + 1).pipe(
|
||||
Effect.as(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
access_token: "desktop-bearer-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
scope: "orchestration:read",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
assert.strictEqual(first, "desktop-bearer-token");
|
||||
assert.strictEqual(second, "desktop-bearer-token");
|
||||
assert.strictEqual(yield* Ref.get(requestCount), 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export interface DesktopLocalEnvironmentAuthShape {
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
|
||||
"DesktopLocalEnvironmentAuthError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
DesktopLocalEnvironmentAuthShape
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopLocalEnvironmentAuth,
|
||||
Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthError({
|
||||
message: "Local backend is not configured.",
|
||||
});
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthError({
|
||||
message: "Failed to create the local desktop bearer session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
}),
|
||||
);
|
||||
@@ -1,105 +1,132 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
|
||||
vi.hoisted(() => ({
|
||||
registerFileProtocolMock: vi.fn(),
|
||||
registerSchemesAsPrivilegedMock: vi.fn(),
|
||||
unregisterProtocolMock: vi.fn(),
|
||||
}));
|
||||
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
netFetchMock: vi.fn(),
|
||||
unhandleMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
protocol: {
|
||||
registerFileProtocol: registerFileProtocolMock,
|
||||
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
|
||||
unregisterProtocol: unregisterProtocolMock,
|
||||
},
|
||||
net: { fetch: netFetchMock },
|
||||
protocol: { handle: handleMock, unhandle: unhandleMock },
|
||||
}));
|
||||
|
||||
import * as ElectronProtocol from "./ElectronProtocol.ts";
|
||||
|
||||
describe("ElectronProtocol", () => {
|
||||
beforeEach(() => {
|
||||
registerFileProtocolMock.mockReset();
|
||||
registerSchemesAsPrivilegedMock.mockReset();
|
||||
unregisterProtocolMock.mockReset();
|
||||
handleMock.mockReset();
|
||||
netFetchMock.mockReset();
|
||||
unhandleMock.mockReset();
|
||||
});
|
||||
|
||||
it("normalizes safe desktop protocol pathnames", () => {
|
||||
assert.equal(
|
||||
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
|
||||
"settings/general",
|
||||
);
|
||||
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
|
||||
});
|
||||
it.effect("proxies the stable renderer origin to the current app server", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock.mockResolvedValue(new Response("ok"));
|
||||
|
||||
it.effect("registers desktop scheme privileges through a layer", () =>
|
||||
Effect.scoped(
|
||||
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
|
||||
[
|
||||
[
|
||||
{
|
||||
scheme: "t3",
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"img-src 'self' t3code-dev: blob: data: http: https:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"font-src 'self' t3code-dev: data:",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
handleMock.mock.calls.map((call) => call[0]),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes registered file protocols", () =>
|
||||
it.effect("rejects custom protocol requests for another host", () =>
|
||||
Effect.gen(function* () {
|
||||
let capturedHandler:
|
||||
| ((
|
||||
request: Electron.ProtocolRequest,
|
||||
callback: (response: Electron.ProtocolResponse) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
|
||||
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
|
||||
capturedHandler = handler;
|
||||
return true;
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* electronProtocol.registerFileProtocol({
|
||||
scheme: "t3",
|
||||
handler: () => Effect.succeed({ path: "/app/index.html" }),
|
||||
});
|
||||
|
||||
assert.isDefined(capturedHandler);
|
||||
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
|
||||
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
|
||||
resume(Effect.succeed(response)),
|
||||
);
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(response, { path: "/app/index.html" });
|
||||
assert.deepEqual(
|
||||
registerFileProtocolMock.mock.calls.map((call) => call[0]),
|
||||
["t3"],
|
||||
);
|
||||
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
|
||||
assert.equal(response.status, 404);
|
||||
assert.equal(netFetchMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
const directives = Object.fromEntries(
|
||||
policy.split("; ").map((directive) => {
|
||||
const [name, ...sources] = directive.split(" ");
|
||||
return [name, sources];
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
|
||||
assert.deepEqual(directives["img-src"], [
|
||||
"'self'",
|
||||
"t3code:",
|
||||
"blob:",
|
||||
"data:",
|
||||
"http:",
|
||||
"https:",
|
||||
]);
|
||||
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,27 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
|
||||
export const DESKTOP_HOST = "app";
|
||||
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
|
||||
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
|
||||
|
||||
export const DESKTOP_SCHEME = "t3";
|
||||
export function getDesktopScheme(isDevelopment: boolean): string {
|
||||
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
|
||||
}
|
||||
|
||||
export function getDesktopOrigin(isDevelopment: boolean): string {
|
||||
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
|
||||
}
|
||||
|
||||
export function getDesktopUrl(isDevelopment: boolean): string {
|
||||
return `${getDesktopOrigin(isDevelopment)}/`;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
"ElectronProtocolRegistrationError",
|
||||
@@ -21,252 +30,117 @@ export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: file protocol.`;
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
|
||||
"ElectronProtocolStaticBundleMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
|
||||
}
|
||||
export interface DesktopProtocolRegistrationInput {
|
||||
readonly scheme: string;
|
||||
readonly targetOrigin: URL;
|
||||
readonly backendOrigin: URL;
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
export interface ElectronProtocolShape {
|
||||
readonly registerFileProtocol: <E, R>(input: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
|
||||
readonly registerDesktopFileProtocol: Effect.Effect<
|
||||
void,
|
||||
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
|
||||
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
|
||||
>;
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
|
||||
const segments: string[] = [];
|
||||
for (const segment of rawPath.split("/")) {
|
||||
if (segment.length === 0 || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
return Option.none();
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return Option.some(segments.join("/"));
|
||||
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
|
||||
const clerkOrigin = input.clerkFrontendApiHostname
|
||||
? `https://${input.clerkFrontendApiHostname}`
|
||||
: undefined;
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
// The renderer connects directly to user-configured environments in addition to
|
||||
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
|
||||
// origins are not known when this response policy is created, so restrict
|
||||
// connections by the network schemes the client supports instead of by host.
|
||||
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
|
||||
|
||||
return [
|
||||
"default-src 'self'",
|
||||
`script-src ${scriptSources.join(" ")}`,
|
||||
`connect-src ${connectSources.join(" ")}`,
|
||||
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`font-src 'self' ${input.scheme}: data:`,
|
||||
"worker-src 'self' blob:",
|
||||
"frame-src 'self' https://challenges.cloudflare.com",
|
||||
"form-action 'self'",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(() => {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
|
||||
function withContentSecurityPolicy(response: Response, policy: string): Response {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Content-Security-Policy", policy);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
const resolveDesktopStaticDir: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidates = [
|
||||
environment.path.join(environment.appRoot, "apps/server/dist/client"),
|
||||
environment.path.join(environment.appRoot, "apps/web/dist"),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const hasIndex = yield* fileSystem
|
||||
.exists(environment.path.join(candidate, "index.html"))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (hasIndex) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
contentSecurityPolicy: string,
|
||||
): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (requestUrl.host !== DESKTOP_HOST) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
|
||||
function* (
|
||||
staticRoot: string,
|
||||
requestUrl: string,
|
||||
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
|
||||
if (Option.isNone(normalizedPath)) {
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
|
||||
const resolvedPath = environment.path.join(staticRoot, requestedPath);
|
||||
|
||||
if (environment.path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = environment.path.join(resolvedPath, "index.html");
|
||||
const nestedIndexExists = yield* fileSystem
|
||||
.exists(nestedIndex)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (nestedIndexExists) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
},
|
||||
);
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return environment.path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
|
||||
function* <E, R>({
|
||||
scheme,
|
||||
handler,
|
||||
onFailure,
|
||||
}: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
|
||||
yield* Effect.annotateCurrentSpan({ scheme });
|
||||
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
|
||||
Effect.map((protocols) => protocols.has(scheme)),
|
||||
);
|
||||
if (alreadyRegistered) {
|
||||
return;
|
||||
}
|
||||
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
function* (input: DesktopProtocolRegistrationInput) {
|
||||
if (yield* Ref.get(registered)) return;
|
||||
|
||||
const context = yield* Effect.context<R>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const registered = Electron.protocol.registerFileProtocol(
|
||||
scheme,
|
||||
(request, callback) => {
|
||||
const response = handler(request).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
|
||||
),
|
||||
);
|
||||
|
||||
void runPromise(response).then(callback, () => callback({ error: -2 }));
|
||||
},
|
||||
Electron.protocol.handle(input.scheme, (request) =>
|
||||
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
|
||||
);
|
||||
if (!registered) {
|
||||
throw new ElectronProtocolRegistrationError({
|
||||
scheme,
|
||||
cause: "registerFileProtocol returned false",
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof ElectronProtocolRegistrationError
|
||||
? cause
|
||||
: new ElectronProtocolRegistrationError({ scheme, cause }),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unregisterProtocol(scheme);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => {
|
||||
const next = new Set(protocols);
|
||||
next.delete(scheme);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
),
|
||||
Electron.protocol.unhandle(input.scheme);
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const registerDesktopFileProtocol = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment;
|
||||
if (environment.isDevelopment) return;
|
||||
|
||||
const staticRoot = yield* resolveDesktopStaticDir;
|
||||
if (Option.isNone(staticRoot)) {
|
||||
return yield* new ElectronProtocolStaticBundleMissingError();
|
||||
}
|
||||
|
||||
const staticRootResolved = environment.path.resolve(staticRoot.value);
|
||||
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
|
||||
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
|
||||
|
||||
yield* registerFileProtocol({
|
||||
scheme: DESKTOP_SCHEME,
|
||||
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = environment.path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url, environment);
|
||||
const exists = yield* fileSystem
|
||||
.exists(resolvedCandidate)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
if (!isInRoot || !exists) {
|
||||
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
|
||||
}
|
||||
|
||||
return { path: resolvedCandidate } as const;
|
||||
}),
|
||||
onFailure: () => ({ path: fallbackIndex }),
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
|
||||
|
||||
return ElectronProtocol.of({
|
||||
registerFileProtocol,
|
||||
registerDesktopFileProtocol,
|
||||
});
|
||||
return ElectronProtocol.of({ registerDesktopProtocol });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronProtocol, make);
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
@@ -33,20 +34,19 @@ export interface DesktopSyncIpcMethod<E, R> {
|
||||
readonly handler: () => Effect.Effect<unknown, E, R>;
|
||||
}
|
||||
|
||||
export interface DesktopIpcShape {
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
export class DesktopIpc extends Context.Service<
|
||||
DesktopIpc,
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
DesktopIpc.of({
|
||||
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
|
||||
channel,
|
||||
@@ -97,6 +97,8 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
|
||||
|
||||
/**
|
||||
* Convenience helpers for creating IPC methods
|
||||
*/
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
import {
|
||||
clearCloudAuthToken,
|
||||
createCloudAuthRequest,
|
||||
fetchCloudAuth,
|
||||
getCloudAuthToken,
|
||||
setCloudAuthToken,
|
||||
} from "./methods/cloudAuth.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import {
|
||||
clearConnectionCatalog,
|
||||
@@ -40,6 +33,7 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
@@ -54,6 +48,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
yield* ipc.handle(setClientSettings);
|
||||
@@ -80,11 +75,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
yield* ipc.handle(createCloudAuthRequest);
|
||||
yield* ipc.handle(getCloudAuthToken);
|
||||
yield* ipc.handle(setCloudAuthToken);
|
||||
yield* ipc.handle(clearCloudAuthToken);
|
||||
yield* ipc.handle(fetchCloudAuth);
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
|
||||
@@ -3,12 +3,6 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
|
||||
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
|
||||
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
|
||||
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
|
||||
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
|
||||
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
@@ -18,6 +12,8 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
|
||||
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getClientSettings = makeIpcMethod({
|
||||
export const getClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(ClientSettingsSchema),
|
||||
@@ -17,7 +17,7 @@ export const getClientSettings = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setClientSettings = makeIpcMethod({
|
||||
export const setClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: ClientSettingsSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
|
||||
|
||||
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
|
||||
const calls: Array<FetchCall> = [];
|
||||
let responseIndex = 0;
|
||||
const fetchFn = ((input, init) => {
|
||||
calls.push([input, init ?? {}]);
|
||||
const response = responses[responseIndex++];
|
||||
if (!response) {
|
||||
return Promise.reject(new Error("Unexpected fetch call"));
|
||||
}
|
||||
return Promise.resolve(response);
|
||||
}) satisfies typeof fetch;
|
||||
|
||||
return { fetchFn, calls };
|
||||
};
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-mobile": "1",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
const [url, init] = forwardedRequest;
|
||||
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
|
||||
assert.equal(init.method, "POST");
|
||||
assert.equal(
|
||||
new Headers(init.headers).get("content-type"),
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://clerk.t3.codes/v1/client",
|
||||
method: "GET",
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
assert.throws(
|
||||
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
|
||||
/restricted to Clerk Frontend API HTTPS hosts/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,177 +0,0 @@
|
||||
import {
|
||||
DesktopCloudAuthFetchInputSchema,
|
||||
DesktopCloudAuthFetchResultSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
clerkFrontendApiHostnameFromPublishableKey,
|
||||
isAllowedClerkFrontendApiHostname,
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
|
||||
readonly reason: string;
|
||||
readonly cause?: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
function configuredClerkFrontendApiHostname(): string | null {
|
||||
const publishableKey =
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
|
||||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? ""
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
|
||||
if (!publishableKey) return null;
|
||||
|
||||
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
|
||||
}
|
||||
|
||||
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
|
||||
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
|
||||
|
||||
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
|
||||
throw new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
|
||||
});
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
|
||||
return Effect.gen(function* () {
|
||||
const method = (input.method ?? "GET") as "GET" | "POST";
|
||||
const headers = new Headers(input.headers);
|
||||
const response = yield* HttpClientRequest.make(method)(url).pipe(
|
||||
HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
|
||||
input.body === undefined
|
||||
? identity
|
||||
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
|
||||
HttpClient.execute,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed to execute.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const electronNetFetchLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const electronFetch = yield* Effect.promise(async () => {
|
||||
const electron = (await import("electron")) as {
|
||||
readonly net?: { readonly fetch?: typeof globalThis.fetch };
|
||||
};
|
||||
return typeof electron.net?.fetch === "function"
|
||||
? electron.net.fetch.bind(electron.net)
|
||||
: null;
|
||||
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
|
||||
|
||||
if (!electronFetch) {
|
||||
yield* Effect.logWarning(
|
||||
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
|
||||
);
|
||||
}
|
||||
|
||||
return FetchHttpClient.layer.pipe(
|
||||
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const createCloudAuthRequest = makeIpcMethod({
|
||||
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
return yield* cloudAuth.createRequest;
|
||||
}),
|
||||
});
|
||||
|
||||
export const getCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return Option.getOrNull(yield* tokenStore.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return yield* tokenStore.set(token);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
yield* tokenStore.clear;
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchCloudAuth = makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
|
||||
payload: DesktopCloudAuthFetchInputSchema,
|
||||
result: DesktopCloudAuthFetchResultSchema,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
|
||||
const url = yield* Effect.try({
|
||||
try: () => validateClerkFrontendApiUrl(input.url),
|
||||
catch: (cause) =>
|
||||
cause instanceof DesktopCloudAuthFetchError
|
||||
? cause
|
||||
: new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch received an invalid URL.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
|
||||
}),
|
||||
});
|
||||
@@ -4,9 +4,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = makeIpcMethod({
|
||||
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -16,7 +16,7 @@ export const getConnectionCatalog = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = makeIpcMethod({
|
||||
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
@@ -26,7 +26,7 @@ export const setConnectionCatalog = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = makeIpcMethod({
|
||||
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -27,7 +27,7 @@ import { pathToFileURL } from "node:url";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
@@ -52,7 +52,7 @@ export const installPreviewEventForwarding = Effect.fn(
|
||||
});
|
||||
});
|
||||
|
||||
export const createTab = makeIpcMethod({
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -62,7 +62,7 @@ export const createTab = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const closeTab = makeIpcMethod({
|
||||
export const closeTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -72,7 +72,7 @@ export const closeTab = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const registerWebview = makeIpcMethod({
|
||||
export const registerWebview = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -82,7 +82,7 @@ export const registerWebview = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = makeIpcMethod({
|
||||
export const navigate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -100,7 +100,7 @@ const tabMethod = (
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
makeIpcMethod({
|
||||
DesktopIpc.makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -166,7 +166,7 @@ export const stopRecording = tabMethod(
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = makeIpcMethod({
|
||||
export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
@@ -176,7 +176,7 @@ export const clearCookies = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = makeIpcMethod({
|
||||
export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
@@ -186,7 +186,7 @@ export const clearCache = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getPreviewConfig = makeIpcMethod({
|
||||
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
@@ -201,7 +201,7 @@ export const getPreviewConfig = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = makeIpcMethod({
|
||||
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -211,7 +211,7 @@ export const setAnnotationTheme = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickElement = makeIpcMethod({
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
@@ -221,7 +221,7 @@ export const pickElement = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const captureScreenshot = makeIpcMethod({
|
||||
export const captureScreenshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
@@ -231,7 +231,7 @@ export const captureScreenshot = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = makeIpcMethod({
|
||||
export const revealArtifact = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -241,7 +241,7 @@ export const revealArtifact = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = makeIpcMethod({
|
||||
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -251,7 +251,7 @@ export const copyArtifactToClipboard = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = makeIpcMethod({
|
||||
export const automationStatus = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
@@ -261,7 +261,7 @@ export const automationStatus = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = makeIpcMethod({
|
||||
export const automationSnapshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
@@ -271,7 +271,7 @@ export const automationSnapshot = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = makeIpcMethod({
|
||||
export const automationClick = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -281,7 +281,7 @@ export const automationClick = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = makeIpcMethod({
|
||||
export const automationType = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -291,7 +291,7 @@ export const automationType = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = makeIpcMethod({
|
||||
export const automationPress = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -301,7 +301,7 @@ export const automationPress = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = makeIpcMethod({
|
||||
export const automationScroll = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -311,7 +311,7 @@ export const automationScroll = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = makeIpcMethod({
|
||||
export const automationEvaluate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
@@ -321,7 +321,7 @@ export const automationEvaluate = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = makeIpcMethod({
|
||||
export const automationWaitFor = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
@@ -331,7 +331,7 @@ export const automationWaitFor = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = makeIpcMethod({
|
||||
export const saveRecording = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
|
||||
@@ -9,14 +9,14 @@ import * as Schema from "effect/Schema";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const SetTailscaleServeEnabledInput = Schema.Struct({
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.optionalKey(Schema.Number),
|
||||
});
|
||||
|
||||
export const getServerExposureState = makeIpcMethod({
|
||||
export const getServerExposureState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -26,7 +26,7 @@ export const getServerExposureState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setServerExposureMode = makeIpcMethod({
|
||||
export const setServerExposureMode = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
|
||||
payload: DesktopServerExposureModeSchema,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -41,7 +41,7 @@ export const setServerExposureMode = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTailscaleServeEnabled = makeIpcMethod({
|
||||
export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
|
||||
payload: SetTailscaleServeEnabledInput,
|
||||
result: DesktopServerExposureStateSchema,
|
||||
@@ -58,7 +58,7 @@ export const setTailscaleServeEnabled = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getAdvertisedEndpoints = makeIpcMethod({
|
||||
export const getAdvertisedEndpoints = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(AdvertisedEndpoint),
|
||||
|
||||
@@ -33,7 +33,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
|
||||
|
||||
@@ -107,7 +107,7 @@ const withLoopbackSshApi =
|
||||
),
|
||||
);
|
||||
|
||||
export const discoverSshHosts = makeIpcMethod({
|
||||
export const discoverSshHosts = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(DesktopDiscoveredSshHostSchema),
|
||||
@@ -117,7 +117,7 @@ export const discoverSshHosts = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const ensureSshEnvironment = makeIpcMethod({
|
||||
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentEnsureInputSchema,
|
||||
result: DesktopSshEnvironmentEnsureResultSchema,
|
||||
@@ -139,7 +139,7 @@ export const ensureSshEnvironment = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const disconnectSshEnvironment = makeIpcMethod({
|
||||
export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentTargetSchema,
|
||||
result: Schema.Void,
|
||||
@@ -149,7 +149,7 @@ export const disconnectSshEnvironment = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
|
||||
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
|
||||
payload: DesktopSshHttpBaseUrlInputSchema,
|
||||
result: ExecutionEnvironmentDescriptor,
|
||||
@@ -160,7 +160,7 @@ export const fetchSshEnvironmentDescriptor = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const bootstrapSshBearerSession = makeIpcMethod({
|
||||
export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
||||
payload: DesktopSshBearerBootstrapInputSchema,
|
||||
result: AuthAccessTokenResult,
|
||||
@@ -177,7 +177,7 @@ export const bootstrapSshBearerSession = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchSshSessionState = makeIpcMethod({
|
||||
export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthSessionState,
|
||||
@@ -194,7 +194,7 @@ export const fetchSshSessionState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const issueSshWebSocketTicket = makeIpcMethod({
|
||||
export const issueSshWebSocketTicket = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
||||
payload: DesktopSshBearerRequestInputSchema,
|
||||
result: AuthWebSocketTicketResult,
|
||||
@@ -211,7 +211,7 @@ export const issueSshWebSocketTicket = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const resolveSshPasswordPrompt = makeIpcMethod({
|
||||
export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
||||
payload: DesktopSshPasswordPromptResolutionInputSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -9,9 +9,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getUpdateState = makeIpcMethod({
|
||||
export const getUpdateState = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -21,7 +21,7 @@ export const getUpdateState = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setUpdateChannel = makeIpcMethod({
|
||||
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
|
||||
payload: DesktopUpdateChannelSchema,
|
||||
result: DesktopUpdateStateSchema,
|
||||
@@ -31,7 +31,7 @@ export const setUpdateChannel = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const downloadUpdate = makeIpcMethod({
|
||||
export const downloadUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -41,7 +41,7 @@ export const downloadUpdate = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const installUpdate = makeIpcMethod({
|
||||
export const installUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateActionResultSchema,
|
||||
@@ -51,7 +51,7 @@ export const installUpdate = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const checkForUpdate = makeIpcMethod({
|
||||
export const checkForUpdate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopUpdateCheckResultSchema,
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
@@ -17,7 +18,7 @@ import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -35,7 +36,7 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string {
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export const getAppBranding = makeSyncIpcMethod({
|
||||
export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
|
||||
result: Schema.NullOr(DesktopAppBrandingSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
|
||||
@@ -44,7 +45,7 @@ export const getAppBranding = makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
@@ -64,7 +65,17 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickFolder = makeIpcMethod({
|
||||
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
|
||||
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* localAuth.getBearerToken;
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PICK_FOLDER_CHANNEL,
|
||||
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -80,7 +91,7 @@ export const pickFolder = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = makeIpcMethod({
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
@@ -93,7 +104,7 @@ export const confirm = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = makeIpcMethod({
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
result: Schema.Void,
|
||||
@@ -103,7 +114,7 @@ export const setTheme = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const showContextMenu = makeIpcMethod({
|
||||
export const showContextMenu = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONTEXT_MENU_CHANNEL,
|
||||
payload: ContextMenuInput,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
@@ -124,7 +135,7 @@ export const showContextMenu = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const openExternal = makeIpcMethod({
|
||||
export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
|
||||
+22
-11
@@ -14,7 +14,6 @@ import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
|
||||
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
@@ -27,13 +26,13 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "./electron/ElectronWindow.ts";
|
||||
import * as DesktopApp from "./app/DesktopApp.ts";
|
||||
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
@@ -68,8 +67,8 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
);
|
||||
|
||||
const resolveDesktopSshCliRunner = (
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
settings: DesktopSettingsValue,
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
settings: DesktopAppSettings.DesktopSettings,
|
||||
): RemoteT3RunnerOptions => {
|
||||
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
|
||||
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
|
||||
@@ -110,7 +109,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronTheme.layer,
|
||||
ElectronUpdater.layer,
|
||||
ElectronWindow.layer,
|
||||
Layer.succeed(DesktopIpc.DesktopIpc, DesktopIpc.make(Electron.ipcMain)),
|
||||
DesktopIpc.layer(Electron.ipcMain),
|
||||
);
|
||||
|
||||
const desktopFoundationLayer = Layer.mergeAll(
|
||||
@@ -119,7 +118,6 @@ const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
DesktopCloudAuthTokenStore.layer,
|
||||
DesktopAssets.layer,
|
||||
DesktopObservability.layer,
|
||||
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
|
||||
@@ -149,17 +147,30 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopCloudAuth.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
|
||||
Layer.flatMap(() =>
|
||||
const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(desktopEnvironmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
|
||||
@@ -4,10 +4,13 @@ import type {
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
@@ -39,6 +42,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getLocalEnvironmentBearerToken: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
|
||||
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
|
||||
setClientSettings: (settings) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
|
||||
@@ -95,23 +100,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
...(position === undefined ? {} : { position }),
|
||||
}),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
|
||||
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
|
||||
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
|
||||
setCloudAuthToken: (token: string) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
|
||||
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
|
||||
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
|
||||
onCloudAuthCallback: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
|
||||
if (typeof rawUrl !== "string") return;
|
||||
listener(rawUrl);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
|
||||
@@ -59,7 +59,7 @@ const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape),
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
);
|
||||
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
@@ -82,7 +82,7 @@ const layer = PreviewManager.layer.pipe(
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -128,6 +128,58 @@ 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,26 +1195,103 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
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,
|
||||
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 (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,6 +272,26 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
});
|
||||
|
||||
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
|
||||
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats empty saved environment documents as empty", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -121,6 +121,9 @@ export interface DesktopSavedEnvironmentsShape {
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
@@ -293,6 +296,23 @@ export const layer = Layer.effect(
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
@@ -385,6 +405,18 @@ 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))),
|
||||
|
||||
@@ -64,7 +64,7 @@ function runShellEnvironment(input: {
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: input.platform,
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape),
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
|
||||
@@ -127,7 +127,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
|
||||
function createBaseUpdateState(
|
||||
channel: DesktopUpdateChannel,
|
||||
enabled: boolean,
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
|
||||
|
||||
@@ -91,7 +91,7 @@ const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
png: Option.none<string>(),
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none<string>()),
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
|
||||
const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
@@ -106,19 +106,19 @@ const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopSe
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.die("unexpected getAdvertisedEndpoints"),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
|
||||
setApplicationMenu: () => Effect.void,
|
||||
popupTemplate: () => Effect.void,
|
||||
showContextMenu: () => Effect.succeed(Option.none()),
|
||||
} satisfies ElectronMenu.ElectronMenuShape);
|
||||
} satisfies ElectronMenu.ElectronMenu["Service"]);
|
||||
|
||||
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
|
||||
shouldUseDarkColors: Effect.succeed(false),
|
||||
setSource: () => Effect.void,
|
||||
onUpdated: () => Effect.void,
|
||||
} satisfies ElectronTheme.ElectronThemeShape);
|
||||
} satisfies ElectronTheme.ElectronTheme["Service"]);
|
||||
|
||||
const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(
|
||||
@@ -156,7 +156,7 @@ function makeTestLayer(input: {
|
||||
sendAll: () => Effect.void,
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: (sync) => sync(input.window),
|
||||
} satisfies ElectronWindow.ElectronWindowShape);
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
return DesktopWindow.layer.pipe(
|
||||
Layer.provide(
|
||||
@@ -173,7 +173,7 @@ function makeTestLayer(input: {
|
||||
return true;
|
||||
}),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShellShape),
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
electronWindowLayer,
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
@@ -191,19 +191,19 @@ describe("DesktopWindow", () => {
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
navigationUrl: "http://127.0.0.1:3773/settings/connections",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "t3code://app/settings/connections",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "https://accounts.microsoft.com/oauth",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "not a url",
|
||||
}),
|
||||
);
|
||||
@@ -231,7 +231,7 @@ describe("DesktopWindow", () => {
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
|
||||
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -16,8 +15,8 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -32,7 +31,6 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopState.DesktopState
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
@@ -40,16 +38,7 @@ type DesktopWindowRuntimeServices =
|
||||
| ElectronWindow.ElectronWindow
|
||||
| PreviewManager.PreviewManager;
|
||||
|
||||
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
"DesktopWindowDevServerUrlMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "VITE_DEV_SERVER_URL is required in desktop development.";
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopWindowError =
|
||||
| DesktopWindowDevServerUrlMissingError
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
@@ -71,15 +60,6 @@ export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowS
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-window");
|
||||
|
||||
function resolveDesktopDevServerUrl(
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
|
||||
return Option.match(environment.devServerUrl, {
|
||||
onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
|
||||
onSome: (url) => Effect.succeed(url.href),
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -171,18 +151,16 @@ const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
|
||||
backendHttpUrl: URL,
|
||||
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
Electron.BrowserWindow,
|
||||
DesktopWindowError
|
||||
> {
|
||||
yield* previewManager.getBrowserSession();
|
||||
const applicationUrl = environment.isDevelopment
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
const applicationUrl = getDesktopUrl(environment.isDevelopment);
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
@@ -350,8 +328,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const createMain = Effect.gen(function* () {
|
||||
const backendConfig = yield* serverExposure.backendConfig;
|
||||
const window = yield* createWindow(backendConfig.httpBaseUrl);
|
||||
const window = yield* createWindow();
|
||||
yield* electronWindow.setMain(window);
|
||||
yield* logWindowInfo("main window created");
|
||||
return window;
|
||||
|
||||
@@ -56,6 +56,12 @@ export default defineConfig({
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
define: publicConfigDefine,
|
||||
entry: ["src/preload.ts"],
|
||||
deps: {
|
||||
// Sandboxed Electron preloads cannot reliably resolve package imports
|
||||
// from inside the packaged ASAR. Bundle Clerk's preload bridge into the
|
||||
// preload artifact instead of leaving a runtime require() behind.
|
||||
alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),
|
||||
},
|
||||
},
|
||||
{
|
||||
format: "cjs",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
included:
|
||||
- ios/T3Code
|
||||
- modules/t3-composer-editor/ios
|
||||
- modules/t3-terminal/ios
|
||||
- modules/t3-review-diff/ios
|
||||
|
||||
|
||||
+21
-1
@@ -192,11 +192,31 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ─── Font family ───────────────────────────────────────────────────── */
|
||||
/* ─── Typography ────────────────────────────────────────────────────── */
|
||||
@theme {
|
||||
--font-sans: "DMSans_400Regular";
|
||||
--font-medium: "DMSans_500Medium";
|
||||
--font-bold: "DMSans_700Bold";
|
||||
|
||||
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
|
||||
--text-3xs: 10px;
|
||||
--text-3xs--line-height: 13px;
|
||||
--text-2xs: 11px;
|
||||
--text-2xs--line-height: 15px;
|
||||
--text-xs: 12px;
|
||||
--text-xs--line-height: 16px;
|
||||
--text-sm: 13px;
|
||||
--text-sm--line-height: 18px;
|
||||
--text-base: 15px;
|
||||
--text-base--line-height: 22px;
|
||||
--text-lg: 17px;
|
||||
--text-lg--line-height: 22px;
|
||||
--text-xl: 20px;
|
||||
--text-xl--line-height: 26px;
|
||||
--text-2xl: 24px;
|
||||
--text-2xl--line-height: 30px;
|
||||
--text-3xl: 28px;
|
||||
--text-3xl--line-height: 34px;
|
||||
}
|
||||
|
||||
/* ─── Custom utilities ──────────────────────────────────────────────── */
|
||||
|
||||
@@ -275,8 +275,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
fileTint: "#737373"
|
||||
)
|
||||
private var fontFamily = "DMSans_400Regular"
|
||||
private var fontSize: CGFloat = 15
|
||||
private var lineHeight: CGFloat = 22
|
||||
private var fontSize: CGFloat = 14
|
||||
private var lineHeight: CGFloat = 20
|
||||
private var contentInsetVertical: CGFloat = 0
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
@@ -460,9 +460,19 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
restoreBaseTypingAttributes()
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
public func textView(
|
||||
_ textView: UITextView,
|
||||
shouldChangeTextIn range: NSRange,
|
||||
replacementText text: String
|
||||
) -> Bool {
|
||||
restoreBaseTypingAttributes()
|
||||
return true
|
||||
}
|
||||
|
||||
public func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
onComposerFocus()
|
||||
}
|
||||
@@ -484,6 +494,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let targetSelection = requestedSelection ?? previousSelection
|
||||
requestedSelection = nil
|
||||
textView.selectedRange = displayRange(for: targetSelection)
|
||||
restoreBaseTypingAttributes()
|
||||
isApplyingControlledValue = false
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
@@ -556,7 +567,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
size: image.size,
|
||||
baselineOffset: baselineOffset
|
||||
)
|
||||
return NSAttributedString(attachment: attachment)
|
||||
let attributedAttachment = NSMutableAttributedString(attachment: attachment)
|
||||
attributedAttachment.addAttributes(
|
||||
baseAttributes(),
|
||||
range: NSRange(location: 0, length: attributedAttachment.length)
|
||||
)
|
||||
return attributedAttachment
|
||||
}
|
||||
|
||||
private func renderChip(
|
||||
@@ -660,11 +676,18 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
textView.font = font
|
||||
textView.typingAttributes = baseAttributes()
|
||||
restoreBaseTypingAttributes()
|
||||
placeholderLabel.font = font
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func restoreBaseTypingAttributes() {
|
||||
guard textView.markedTextRange == nil else {
|
||||
return
|
||||
}
|
||||
textView.typingAttributes = baseAttributes()
|
||||
}
|
||||
|
||||
private func applyTheme() {
|
||||
textView.textColor = UIColor(composerHex: theme.text) ?? .label
|
||||
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
|
||||
|
||||
@@ -70,7 +70,12 @@ static void T3MarkdownTextApplyAttachments(
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
}
|
||||
attachment.image = image ?: [[UIImage alloc] init];
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -80,104 +85,6 @@ 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
|
||||
@@ -285,7 +192,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
|
||||
@implementation T3MarkdownText {
|
||||
UIView * _view;
|
||||
T3MarkdownTextBackingView * _textView;
|
||||
UITextView * _textView;
|
||||
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
|
||||
__weak UIWindow * _outsideTapWindow;
|
||||
BOOL _suppressSelectionChange;
|
||||
@@ -308,7 +215,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
self.contentView = _view;
|
||||
self.clipsToBounds = true;
|
||||
|
||||
_textView = [[T3MarkdownTextBackingView alloc] init];
|
||||
_textView = [[UITextView alloc] init];
|
||||
_attachmentImages = [[NSMutableDictionary alloc] init];
|
||||
_pendingAttachmentUris = [[NSMutableSet alloc] init];
|
||||
_textView.scrollEnabled = false;
|
||||
@@ -405,9 +312,6 @@ 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,18 +28,20 @@ struct T3MarkdownTextAttachmentRange {
|
||||
std::string imageUri;
|
||||
};
|
||||
|
||||
struct T3MarkdownTextChipRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
bool isSkill;
|
||||
};
|
||||
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
|
||||
return 14;
|
||||
}
|
||||
|
||||
inline Float T3MarkdownTextAttachmentBaselineOffset(
|
||||
const T3MarkdownTextAttachmentRange &) {
|
||||
return -2;
|
||||
}
|
||||
|
||||
class T3MarkdownTextStateReal final {
|
||||
public:
|
||||
AttributedString attributedString;
|
||||
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
|
||||
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
|
||||
std::vector<T3MarkdownTextChipRange> chipRanges;
|
||||
};
|
||||
|
||||
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
|
||||
@@ -72,6 +74,5 @@ private:
|
||||
mutable AttributedString _attributedString;
|
||||
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
|
||||
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
|
||||
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
|
||||
};
|
||||
} // namespace facebook::React
|
||||
@@ -9,9 +9,8 @@
|
||||
namespace facebook::react {
|
||||
|
||||
static constexpr Float ParagraphStyleEncodingOffset = 1000;
|
||||
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
|
||||
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
|
||||
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
|
||||
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
|
||||
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
|
||||
|
||||
static void applyParagraphStyles(
|
||||
NSMutableAttributedString *attributedString,
|
||||
@@ -58,7 +57,12 @@ static void applyAttachments(
|
||||
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
attachment.image = [[UIImage alloc] init];
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -91,7 +95,6 @@ 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++) {
|
||||
@@ -184,25 +187,19 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
props.shadowRadius - ParagraphStyleEncodingOffset,
|
||||
});
|
||||
}
|
||||
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) {
|
||||
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
utf16Offset,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
utf16Offset,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
|
||||
props.nativeId.substr(
|
||||
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
|
||||
});
|
||||
}
|
||||
utf16Offset += fragmentLength;
|
||||
@@ -213,7 +210,6 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
_attributedString = baseAttributedString;
|
||||
_paragraphStyleRanges = paragraphStyleRanges;
|
||||
_attachmentRanges = attachmentRanges;
|
||||
_chipRanges = chipRanges;
|
||||
|
||||
NSMutableAttributedString *convertedAttributedString =
|
||||
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
|
||||
@@ -263,7 +259,6 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
|
||||
_attributedString,
|
||||
_paragraphStyleRanges,
|
||||
_attachmentRanges,
|
||||
_chipRanges,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -40,11 +40,13 @@ 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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -312,6 +314,7 @@ 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 (
|
||||
@@ -351,6 +354,7 @@ function NativeTable(props: {
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
@@ -364,10 +368,17 @@ 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} />;
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -426,6 +437,7 @@ 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 }}>
|
||||
@@ -435,9 +447,15 @@ 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} />
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
@@ -448,6 +466,7 @@ 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;
|
||||
@@ -508,6 +527,7 @@ function NativeList(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={props.depth + 1}
|
||||
compact
|
||||
/>
|
||||
@@ -524,6 +544,7 @@ export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly depth?: number;
|
||||
readonly compact?: boolean;
|
||||
}) {
|
||||
@@ -538,6 +559,7 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
/>
|
||||
))}
|
||||
@@ -553,9 +575,21 @@ export function NativeMarkdownBlock(props: {
|
||||
/>
|
||||
);
|
||||
case "table":
|
||||
return <NativeTable node={props.node} textStyle={props.textStyle} />;
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
case "image":
|
||||
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
case "horizontal_rule":
|
||||
return (
|
||||
<View
|
||||
@@ -583,6 +617,7 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -595,14 +630,23 @@ 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} />
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
case "html_block":
|
||||
case "math_block":
|
||||
@@ -618,7 +662,11 @@ export function NativeMarkdownBlock(props: {
|
||||
: "transparent",
|
||||
}}
|
||||
>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
case "table_head":
|
||||
@@ -635,6 +683,7 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -642,6 +691,12 @@ export function NativeMarkdownBlock(props: {
|
||||
</View>
|
||||
);
|
||||
default:
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +1,15 @@
|
||||
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 FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
|
||||
const CHIP_SUFFIX = "\u00A0";
|
||||
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\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,
|
||||
@@ -81,13 +35,16 @@ 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 ? "underline" : "none";
|
||||
const textDecorationLine = run.strikethrough
|
||||
? "line-through"
|
||||
: run.href && !isFile
|
||||
? "underline"
|
||||
: "none";
|
||||
|
||||
return {
|
||||
color: isFile
|
||||
@@ -106,20 +63,23 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? textStyle.mutedColor
|
||||
: run.role === "list-marker"
|
||||
? textStyle.mutedColor
|
||||
: run.code || isFile
|
||||
: isCodeBlock
|
||||
? textStyle.codeColor
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily: isChip
|
||||
? "DMSans_500Medium"
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
: 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,
|
||||
fontSize:
|
||||
run.role === "spacer"
|
||||
? (run.spacing ?? 10)
|
||||
@@ -129,7 +89,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
: run.code || isChip || isCodeBlock
|
||||
: run.code || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
lineHeight:
|
||||
@@ -143,17 +103,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? 18
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
textDecorationLine,
|
||||
backgroundColor: isCodeBlock
|
||||
? textStyle.codeBlockBackgroundColor
|
||||
: isSkill
|
||||
? textStyle.skillBackgroundColor
|
||||
: run.code
|
||||
? textStyle.codeBackgroundColor
|
||||
: isFile
|
||||
? textStyle.fileBackgroundColor
|
||||
: undefined,
|
||||
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
|
||||
...(hasParagraphStyle
|
||||
? {
|
||||
shadowColor: "transparent",
|
||||
@@ -170,9 +122,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) => {
|
||||
@@ -182,9 +134,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
|
||||
let text = run.text;
|
||||
if (run.fileIcon) {
|
||||
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
|
||||
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
|
||||
} else if (run.skillName && run.skillLabel) {
|
||||
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
|
||||
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
|
||||
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
|
||||
prefixedExternalLinks.add(run.href);
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
@@ -200,12 +152,11 @@ 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,
|
||||
@@ -217,7 +168,8 @@ export function NativeMarkdownSelectableText(props: {
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
width: "100%",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
color: props.textStyle.color,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: props.textStyle.fontSize,
|
||||
@@ -231,19 +183,20 @@ export function NativeMarkdownSelectableText(props: {
|
||||
key={key}
|
||||
nativeID={
|
||||
run.fileIcon
|
||||
? `t3-chip-file:${
|
||||
fileIconUris.get(run.fileIcon) ??
|
||||
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
|
||||
}`
|
||||
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
|
||||
: run.skillName
|
||||
? "t3-chip-skill:sf:cube"
|
||||
? "t3-skill:sf:cube"
|
||||
: undefined
|
||||
}
|
||||
style={runStyle(run, props.textStyle)}
|
||||
onPress={
|
||||
href
|
||||
? () => {
|
||||
void Linking.openURL(href);
|
||||
if (props.onLinkPress) {
|
||||
props.onLinkPress(href);
|
||||
} else {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
nativeMarkdownChunkSpacing,
|
||||
nativeMarkdownDocumentChunks,
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
@@ -33,15 +34,20 @@ export function SelectableMarkdownText({
|
||||
skills = EMPTY_SKILLS,
|
||||
textStyle,
|
||||
highlightCode,
|
||||
preserveSoftBreaks = false,
|
||||
onLinkPress,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
const chunks = useMemo(() => {
|
||||
const document = parseMarkdownWithOptions(markdown, {
|
||||
const parsedDocument = parseMarkdownWithOptions(markdown, {
|
||||
gfm: true,
|
||||
html: true,
|
||||
math: false,
|
||||
});
|
||||
const document = preserveSoftBreaks
|
||||
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
|
||||
: parsedDocument;
|
||||
return nativeMarkdownDocumentChunks(document).map((chunk) =>
|
||||
chunk.kind === "selectable"
|
||||
? {
|
||||
@@ -50,10 +56,14 @@ export function SelectableMarkdownText({
|
||||
}
|
||||
: chunk,
|
||||
);
|
||||
}, [markdown, skills]);
|
||||
}, [markdown, preserveSoftBreaks, skills]);
|
||||
|
||||
return (
|
||||
<View style={{ width: "100%", marginTop, marginBottom }}>
|
||||
// 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 }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
@@ -61,9 +71,14 @@ export function SelectableMarkdownText({
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,12 +3,11 @@ 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;
|
||||
@@ -41,6 +40,8 @@ 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,8 +27,12 @@ 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";
|
||||
@@ -247,7 +251,7 @@ function normalizeDestination(value: string): string {
|
||||
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
|
||||
}
|
||||
|
||||
function fileUrlPath(href: string): string | null {
|
||||
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
|
||||
try {
|
||||
const parsed = new URL(href);
|
||||
if (parsed.protocol.toLowerCase() !== "file:") {
|
||||
@@ -256,15 +260,44 @@ function fileUrlPath(href: string): string | null {
|
||||
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
|
||||
? parsed.pathname.slice(1)
|
||||
: parsed.pathname;
|
||||
const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
|
||||
return `${safeDecode(path)}${
|
||||
lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
|
||||
}`;
|
||||
return { path, hash: parsed.hash };
|
||||
} 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;
|
||||
@@ -331,14 +364,31 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
|
||||
// Relative paths and non-URL link destinations are handled below.
|
||||
}
|
||||
|
||||
const fileTarget = normalized.toLowerCase().startsWith("file:")
|
||||
? fileUrlPath(normalized)
|
||||
: safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
|
||||
if (fileTarget && looksLikeFilePath(fileTarget)) {
|
||||
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)) {
|
||||
return {
|
||||
kind: "file",
|
||||
icon: resolveMarkdownFileIcon(fileTarget),
|
||||
label: fileLabel(fileTarget),
|
||||
href: normalized,
|
||||
icon: resolveMarkdownFileIcon(fileTarget.path),
|
||||
label: fileLabel(targetWithPosition),
|
||||
path: fileTarget.path,
|
||||
...(fileTarget.line ? { line: fileTarget.line } : {}),
|
||||
...(fileTarget.column ? { column: fileTarget.column } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -293,6 +293,7 @@ function appendNode(
|
||||
if (presentation.kind === "file") {
|
||||
return appendRun(runs, presentation.label, {
|
||||
...context,
|
||||
href: presentation.href,
|
||||
fileIcon: presentation.icon,
|
||||
});
|
||||
}
|
||||
@@ -319,6 +320,15 @@ 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,6 +57,10 @@ 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: metric(payload?.changeBarWidth, fallback: 4),
|
||||
changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
|
||||
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
|
||||
codePadding: metric(payload?.codePadding, fallback: 8),
|
||||
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
|
||||
@@ -243,6 +243,13 @@ 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":
|
||||
@@ -316,6 +323,8 @@ 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()
|
||||
@@ -394,6 +403,7 @@ 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",
|
||||
@@ -402,6 +412,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
} catch {
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
updateContentMetrics()
|
||||
emitDebug("rows-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
@@ -561,6 +572,7 @@ 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 {
|
||||
@@ -645,6 +657,19 @@ 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)
|
||||
@@ -662,6 +687,22 @@ 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 {
|
||||
@@ -820,6 +861,19 @@ 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] = []
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@callstack/liquid-glass": "^0.7.1",
|
||||
"@clerk/expo": "^3.4.1",
|
||||
"@clerk/expo": "catalog:",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
@@ -101,6 +101,7 @@
|
||||
"react-native-screens": "4.25.2",
|
||||
"react-native-shiki-engine": "^0.3.12",
|
||||
"react-native-svg": "15.15.4",
|
||||
"react-native-webview": "^13.16.1",
|
||||
"react-native-worklets": "0.8.3",
|
||||
"shiki": "4.2.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
|
||||
@@ -21,7 +21,7 @@ export default function NotFoundRoute() {
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-[28px] font-t3-bold text-foreground" selectable>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Link href="/" asChild>
|
||||
@@ -35,7 +35,7 @@ export default function NotFoundRoute() {
|
||||
primaryBgStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-[16px] font-t3-bold text-primary-foreground">Return home</Text>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</Link>
|
||||
</ScrollView>
|
||||
|
||||
@@ -30,10 +30,11 @@ import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
function AppNavigator() {
|
||||
const pathname = usePathname();
|
||||
const clerkRouteIsActive = pathname === "/settings/auth";
|
||||
const expandedSettingsRouteIsActive =
|
||||
pathname === "/settings/archive" || pathname === "/settings/auth";
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
|
||||
<AppNavigatorContent />
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
);
|
||||
|
||||
@@ -85,7 +85,7 @@ export default function ConnectionsRouteScreen() {
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
|
||||
@@ -171,7 +171,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
Camera permission is required to scan a QR code.
|
||||
</Text>
|
||||
<ConnectionSheetButton
|
||||
@@ -189,7 +189,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
|
||||
<View collapsable={false} className="gap-1.5">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Host
|
||||
@@ -202,13 +202,13 @@ export default function ConnectionsNewRouteScreen() {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={hostInput}
|
||||
onChangeText={handleHostChange}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View collapsable={false} className="gap-1.5">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Pairing code
|
||||
@@ -220,7 +220,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={codeInput}
|
||||
onChangeText={handleCodeChange}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
|
||||
/>
|
||||
</View>
|
||||
|
||||
|
||||
@@ -1,13 +1,33 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
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 { useProjects, useThreadShells } from "../state/entities";
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
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;
|
||||
}
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -18,103 +38,82 @@ export default function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
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 }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
hideNavigationBar: false,
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
setSearchQuery("");
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
},
|
||||
}}
|
||||
<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}
|
||||
/>
|
||||
|
||||
{/* 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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -129,10 +129,10 @@ export default function NewTaskRoute() {
|
||||
{items.length === 0 ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
|
||||
<Text className="text-center text-[17px] font-t3-bold text-foreground">
|
||||
<Text className="text-center text-lg font-t3-bold text-foreground">
|
||||
{projectEmptyState.title}
|
||||
</Text>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
{projectEmptyState.detail}
|
||||
</Text>
|
||||
{!catalogState.hasReadyEnvironment ? (
|
||||
@@ -140,7 +140,7 @@ export default function NewTaskRoute() {
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => router.push("/connections/new")}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
Add environment
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -149,7 +149,7 @@ export default function NewTaskRoute() {
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => router.push("/new/add-project")}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
Add new project
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -197,9 +197,7 @@ export default function NewTaskRoute() {
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<Text className="text-[16px] leading-[21px] font-t3-bold">
|
||||
{item.title}
|
||||
</Text>
|
||||
<Text className="text-base leading-[21px] font-t3-bold">{item.title}</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function SettingsLayout() {
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
const handleClerkRouteTransitionEnd = useCallback(
|
||||
const handleExpandedRouteTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
@@ -47,9 +47,14 @@ 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: handleClerkRouteTransitionEnd }}
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Sign in" }}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
|
||||
|
||||
export default ArchivedThreadsRouteScreen;
|
||||
@@ -111,7 +111,7 @@ export default function SettingsEnvironmentsRouteScreen() {
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
@@ -160,7 +160,7 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
return (
|
||||
<View collapsable={false} className="mt-5 gap-3">
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
@@ -204,16 +204,16 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
) : controller.relayDiscovery.isRefreshing ? (
|
||||
<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">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : controller.relayDiscovery.error ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
Could not load T3 Cloud environments
|
||||
</Text>
|
||||
<Text className="text-[13px] leading-[18px] text-foreground-muted">
|
||||
<Text className="text-sm leading-[18px] text-foreground-muted">
|
||||
{controller.relayDiscovery.error}
|
||||
</Text>
|
||||
{controller.relayDiscovery.errorTraceId ? (
|
||||
@@ -222,7 +222,7 @@ function ConfiguredCloudEnvironmentRows(props: {
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card p-5">
|
||||
<Text className="text-[14px] leading-[20px] text-foreground-muted">
|
||||
<Text className="text-sm leading-[20px] text-foreground-muted">
|
||||
No additional linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
@@ -361,7 +361,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
<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"
|
||||
className="min-w-0 flex-shrink text-base font-t3-bold leading-[21px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
@@ -370,7 +370,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
{props.connectionError ? (
|
||||
<Text
|
||||
aria-hidden
|
||||
className={cn("absolute left-0 right-0 text-[12px] leading-[16px]", statusClassName)}
|
||||
className={cn("absolute left-0 right-0 text-xs leading-[16px]", statusClassName)}
|
||||
onTextLayout={onMeasuredErrorTextLayout}
|
||||
style={{ opacity: 0, zIndex: -1 }}
|
||||
>
|
||||
@@ -384,7 +384,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
className="min-w-0 flex-row items-start gap-1"
|
||||
>
|
||||
<Text
|
||||
className={cn("min-w-0 flex-1 text-[12px] leading-[16px]", statusClassName)}
|
||||
className={cn("min-w-0 flex-1 text-xs leading-[16px]", statusClassName)}
|
||||
numberOfLines={isErrorExpanded ? undefined : 1}
|
||||
>
|
||||
{statusText}
|
||||
@@ -394,7 +394,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
<Text
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className={cn("text-[12px] leading-[16px] underline", statusClassName)}
|
||||
className={cn("text-xs leading-[16px] underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId);
|
||||
@@ -446,7 +446,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
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>
|
||||
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -65,6 +65,8 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -344,7 +346,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
onPress={openAccount}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-[13px] leading-[18px] text-foreground-muted">
|
||||
<Text className="px-2 text-sm leading-[18px] text-foreground-muted">
|
||||
T3 Code works locally without signing in. Cloud features are optional.
|
||||
</Text>
|
||||
</View>
|
||||
@@ -374,6 +376,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -385,7 +389,7 @@ type SymbolName = ComponentProps<typeof SymbolView>["name"];
|
||||
function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) {
|
||||
return (
|
||||
<View className="gap-2">
|
||||
<Text className="px-2 text-[13px] font-t3-medium text-foreground-muted">{props.title}</Text>
|
||||
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
|
||||
<View
|
||||
className="overflow-hidden rounded-[28px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
@@ -409,19 +413,27 @@ function AppSettingsSection() {
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
|
||||
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<Text className="text-lg text-foreground-muted">Alpha</Text>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
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/environments";
|
||||
readonly href?: "/settings/archive" | "/settings/environments";
|
||||
readonly onPress?: () => void;
|
||||
}) {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
@@ -432,13 +444,13 @@ 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}>
|
||||
<Text className="shrink-0 text-lg 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"
|
||||
className="max-w-[180px] text-right text-base text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -459,7 +471,9 @@ function SettingsRow(props: {
|
||||
if (props.href) {
|
||||
return (
|
||||
<Link href={props.href} asChild>
|
||||
<Pressable>{content}</Pressable>
|
||||
<Pressable accessibilityLabel={props.label} accessibilityRole="button">
|
||||
{content}
|
||||
</Pressable>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -488,7 +502,7 @@ function SettingsSwitchRow(props: {
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
|
||||
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
|
||||
@@ -55,6 +55,32 @@ 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={{
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFileRoute() {
|
||||
return <ThreadFileScreen />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFilesIndexRoute() {
|
||||
return <ThreadFilesTreeScreen />;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ export function AppTextInput({
|
||||
<RNTextInput
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
className,
|
||||
)}
|
||||
placeholderTextColor={placeholderTextColor ?? placeholderColor}
|
||||
|
||||
@@ -22,15 +22,12 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
/>
|
||||
<View className="gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="text-[17px] font-t3-bold text-foreground"
|
||||
style={{ letterSpacing: -0.4 }}
|
||||
>
|
||||
<Text className="text-lg font-t3-bold text-foreground" style={{ letterSpacing: -0.4 }}>
|
||||
T3 Code
|
||||
</Text>
|
||||
<View className="rounded-full bg-subtle px-2 py-1">
|
||||
<Text
|
||||
className="text-[10px] font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-3xs font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 1.1 }}
|
||||
>
|
||||
{stageLabel}
|
||||
@@ -38,7 +35,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
</View>
|
||||
</View>
|
||||
{!compact ? (
|
||||
<Text className="text-[12px] font-medium text-foreground-muted">
|
||||
<Text className="text-xs font-medium text-foreground-muted">
|
||||
Mobile control surface for your live coding environments
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
@@ -223,7 +223,7 @@ export function ComposerToolbarButton(props: {
|
||||
{props.label ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-center text-[13px] font-t3-bold",
|
||||
"shrink text-center text-sm font-t3-bold",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "text-foreground-muted"
|
||||
|
||||
@@ -48,7 +48,7 @@ export function ControlPill(props: {
|
||||
: "bg-subtle",
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-[12px] font-t3-bold",
|
||||
"text-center text-xs font-t3-bold",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "text-foreground-muted"
|
||||
|
||||
@@ -19,9 +19,7 @@ export function EmptyState(props: {
|
||||
className="mt-4 self-start rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={props.onAction}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
{props.actionLabel}
|
||||
</Text>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">{props.actionLabel}</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
|
||||
export function ErrorBanner(props: { readonly message: string }) {
|
||||
return (
|
||||
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
|
||||
<Text className="font-t3-medium text-[13px] leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
{props.message}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export function StatusPill(
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold",
|
||||
size === "compact" ? "text-[11px]" : "text-xs",
|
||||
size === "compact" ? "text-2xs" : "text-xs",
|
||||
props.textClassName,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
CloudSession,
|
||||
EnvironmentOwnedDataCleanup,
|
||||
PlatformConnectionSource,
|
||||
PrimaryEnvironmentAuth,
|
||||
RelayDeviceIdentity,
|
||||
SshEnvironmentGateway,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
@@ -119,6 +120,10 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
}),
|
||||
}),
|
||||
).pipe(
|
||||
Context.add(
|
||||
PrimaryEnvironmentAuth,
|
||||
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
|
||||
),
|
||||
Context.add(
|
||||
RelayDeviceIdentity,
|
||||
RelayDeviceIdentity.of({
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
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-xs 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-2xs 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-base font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs 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-2xs 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="text-base font-t3-bold text-danger-foreground">
|
||||
Could not load every archive
|
||||
</Text>
|
||||
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-sm 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-sm 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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 };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useWaitlist } from "@clerk/expo";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { useState } from "react";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
|
||||
@@ -141,12 +142,11 @@ function useCloudWaitlistColors() {
|
||||
const styles = StyleSheet.create({
|
||||
body: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 15,
|
||||
lineHeight: 21,
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
buttonText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 16,
|
||||
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
|
||||
},
|
||||
content: {
|
||||
gap: 18,
|
||||
@@ -156,8 +156,7 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
error: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 13,
|
||||
lineHeight: 18,
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
field: {
|
||||
gap: 8,
|
||||
@@ -167,15 +166,14 @@ const styles = StyleSheet.create({
|
||||
borderRadius: 16,
|
||||
borderWidth: 1,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 17,
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
minHeight: 54,
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
label: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 18,
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
primaryButton: {
|
||||
alignItems: "center",
|
||||
@@ -196,13 +194,11 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
signInText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 15,
|
||||
lineHeight: 21,
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
title: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 20,
|
||||
lineHeight: 26,
|
||||
...MOBILE_TYPOGRAPHY.title,
|
||||
textAlign: "center",
|
||||
},
|
||||
});
|
||||
@@ -76,19 +76,16 @@ export function ConnectionEnvironmentRow(props: {
|
||||
/>
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
<Text
|
||||
className="text-[16px] font-t3-bold leading-[21px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
<Text className="text-base font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
|
||||
{props.environment.environmentLabel}
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
<Text className="text-xs leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{props.environment.displayUrl}
|
||||
</Text>
|
||||
{statusLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[12px] leading-[16px]",
|
||||
"text-xs leading-[16px]",
|
||||
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={props.expanded ? undefined : 1}
|
||||
@@ -137,14 +134,14 @@ export function ConnectionEnvironmentRow(props: {
|
||||
className="gap-3 px-4 pb-4"
|
||||
>
|
||||
{props.environment.isRelayManaged ? (
|
||||
<Text className="text-[13px] leading-[18px] text-foreground-muted">
|
||||
<Text className="text-sm leading-[18px] text-foreground-muted">
|
||||
Managed by T3 Cloud. Tunnel details update automatically.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<View className="gap-1.5">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Label
|
||||
@@ -156,13 +153,13 @@ export function ConnectionEnvironmentRow(props: {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={label}
|
||||
onChangeText={setLabel}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-1.5">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
URL
|
||||
@@ -175,7 +172,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
placeholderTextColor={placeholderColor}
|
||||
value={url}
|
||||
onChangeText={setUrl}
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
|
||||
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
|
||||
/>
|
||||
</View>
|
||||
</>
|
||||
@@ -189,7 +186,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
>
|
||||
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
|
||||
<Text
|
||||
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
|
||||
className="text-xs font-t3-bold uppercase text-primary-foreground"
|
||||
style={{ letterSpacing: 0.8 }}
|
||||
>
|
||||
Save
|
||||
|
||||
@@ -104,7 +104,7 @@ export function ConnectionSheetButton(props: {
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="text-[12px] font-t3-bold uppercase"
|
||||
className="text-xs font-t3-bold uppercase"
|
||||
style={{ color: colors.textColor, letterSpacing: 0.8 }}
|
||||
>
|
||||
{props.label}
|
||||
|
||||
@@ -73,10 +73,10 @@ export function EnvironmentConnectionNotice(props: {
|
||||
/>
|
||||
)}
|
||||
|
||||
<Text className="text-center text-[17px] font-t3-bold leading-[22px] text-foreground">
|
||||
<Text className="text-center text-lg 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">
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
|
||||
{props.connection.traceId ? (
|
||||
<>
|
||||
@@ -99,7 +99,7 @@ export function EnvironmentConnectionNotice(props: {
|
||||
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>
|
||||
<Text className="text-sm font-t3-bold text-foreground">Retry now</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -110,6 +110,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly styleJson?: string;
|
||||
readonly rowHeight: number;
|
||||
readonly contentWidth: number;
|
||||
readonly initialRowIndex?: number;
|
||||
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
|
||||
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
type NodeStyleOverrides,
|
||||
type PartialMarkdownTheme,
|
||||
} from "react-native-nitro-markdown";
|
||||
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
type NativeMarkdownTextStyle,
|
||||
} from "../../native/SelectableMarkdownText";
|
||||
|
||||
interface MarkdownPreviewStyles {
|
||||
readonly theme: PartialMarkdownTheme;
|
||||
readonly styles: NodeStyleOverrides;
|
||||
readonly renderers: CustomRenderers;
|
||||
readonly nativeTextStyle: NativeMarkdownTextStyle;
|
||||
}
|
||||
|
||||
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
const body = String(useThemeColor("--color-md-body"));
|
||||
const strong = String(useThemeColor("--color-md-strong"));
|
||||
const link = String(useThemeColor("--color-md-link"));
|
||||
const blockquoteBorder = String(useThemeColor("--color-md-blockquote-border"));
|
||||
const blockquoteBackground = String(useThemeColor("--color-md-blockquote-bg"));
|
||||
const codeBackground = String(useThemeColor("--color-md-code-bg"));
|
||||
const codeText = String(useThemeColor("--color-md-code-text"));
|
||||
const horizontalRule = String(useThemeColor("--color-md-hr"));
|
||||
|
||||
return useMemo(() => {
|
||||
const renderers: CustomRenderers = {
|
||||
link: ({ href, children }) => (
|
||||
<NativeText
|
||||
onPress={() => {
|
||||
if (href) {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
color: link,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
textDecorationLine: "none",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</NativeText>
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
theme: {
|
||||
colors: {
|
||||
text: body,
|
||||
heading: strong,
|
||||
link,
|
||||
blockquote: blockquoteBorder,
|
||||
border: horizontalRule,
|
||||
surfaceLight: blockquoteBackground,
|
||||
accent: link,
|
||||
tableBorder: horizontalRule,
|
||||
tableHeader: blockquoteBackground,
|
||||
tableHeaderText: strong,
|
||||
code: codeText,
|
||||
codeBackground,
|
||||
},
|
||||
},
|
||||
styles: {
|
||||
text: {
|
||||
color: body,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
heading: {
|
||||
color: strong,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
},
|
||||
strong: {
|
||||
color: strong,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
},
|
||||
link: {
|
||||
color: link,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
},
|
||||
blockquote: {
|
||||
backgroundColor: blockquoteBackground,
|
||||
borderLeftColor: blockquoteBorder,
|
||||
borderLeftWidth: 3,
|
||||
paddingLeft: 12,
|
||||
},
|
||||
code: {
|
||||
backgroundColor: codeBackground,
|
||||
color: codeText,
|
||||
fontFamily: "ui-monospace",
|
||||
},
|
||||
codeBlock: {
|
||||
backgroundColor: codeBackground,
|
||||
borderRadius: 12,
|
||||
color: codeText,
|
||||
fontFamily: "ui-monospace",
|
||||
padding: 12,
|
||||
},
|
||||
hr: {
|
||||
backgroundColor: horizontalRule,
|
||||
},
|
||||
},
|
||||
renderers,
|
||||
nativeTextStyle: {
|
||||
color: body,
|
||||
strongColor: strong,
|
||||
mutedColor: body,
|
||||
linkColor: link,
|
||||
inlineCodeColor: codeText,
|
||||
codeColor: codeText,
|
||||
codeBackgroundColor: codeBackground,
|
||||
codeBlockBackgroundColor: codeBackground,
|
||||
fileTextColor: codeText,
|
||||
skillTextColor: codeText,
|
||||
quoteMarkerColor: blockquoteBorder,
|
||||
dividerColor: horizontalRule,
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
headingFontFamily: "DMSans_700Bold",
|
||||
boldFontFamily: "DMSans_700Bold",
|
||||
},
|
||||
};
|
||||
}, [
|
||||
blockquoteBackground,
|
||||
blockquoteBorder,
|
||||
body,
|
||||
codeBackground,
|
||||
codeText,
|
||||
horizontalRule,
|
||||
link,
|
||||
strong,
|
||||
]);
|
||||
}
|
||||
|
||||
export function FileMarkdownPreview(props: { readonly markdown: string }) {
|
||||
const styles = useMarkdownPreviewStyles();
|
||||
|
||||
return (
|
||||
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
|
||||
<View className="mx-auto w-full max-w-[760px]">
|
||||
{hasNativeSelectableMarkdownText() ? (
|
||||
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
|
||||
) : (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
renderers={styles.renderers}
|
||||
styles={styles.styles}
|
||||
theme={styles.theme}
|
||||
>
|
||||
{props.markdown}
|
||||
</Markdown>
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
buildFileTree,
|
||||
defaultExpandedTreePaths,
|
||||
flattenFileTree,
|
||||
type VisibleFileTreeNode,
|
||||
} from "./fileTree";
|
||||
|
||||
function ancestorPaths(path: string): ReadonlyArray<string> {
|
||||
const parts = path.split("/").filter(Boolean);
|
||||
const ancestors: string[] = [];
|
||||
for (let index = 1; index < parts.length; index += 1) {
|
||||
ancestors.push(parts.slice(0, index).join("/"));
|
||||
}
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
readonly item: VisibleFileTreeNode;
|
||||
readonly selectedPath: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly iconColor: string;
|
||||
readonly onPressDirectory: (path: string) => void;
|
||||
readonly onPressFile: (path: string) => void;
|
||||
}) {
|
||||
const { node, depth } = props.item;
|
||||
const selected = node.kind === "file" && node.path === props.selectedPath;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={node.path}
|
||||
onPress={() => {
|
||||
if (node.kind === "directory") {
|
||||
props.onPressDirectory(node.path);
|
||||
return;
|
||||
}
|
||||
props.onPressFile(node.path);
|
||||
}}
|
||||
className={cn(
|
||||
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
|
||||
selected && "bg-subtle-strong",
|
||||
)}
|
||||
style={{ paddingLeft: 8 + depth * 18 }}
|
||||
>
|
||||
{node.kind === "directory" ? (
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.down" : "chevron.right"}
|
||||
size={12}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : (
|
||||
<View className="w-3" />
|
||||
)}
|
||||
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
|
||||
<Text
|
||||
className={cn(
|
||||
"min-w-0 flex-1 text-sm leading-[19px]",
|
||||
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{node.name}
|
||||
</Text>
|
||||
{node.kind === "directory" ? (
|
||||
<Text className="text-2xs font-t3-medium text-foreground-tertiary">
|
||||
{node.children.length}
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
export function FileTreeBrowser(props: {
|
||||
readonly entries: ReadonlyArray<ProjectEntry>;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedPath: string | null;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
}) {
|
||||
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
|
||||
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
|
||||
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
|
||||
const visibleNodes = useMemo(
|
||||
() =>
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: expandedPaths,
|
||||
searchQuery: props.searchQuery,
|
||||
}),
|
||||
[expandedPaths, props.searchQuery, tree],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setExpandedPaths((current) => {
|
||||
if (current.size > 0 || defaultExpanded.size === 0) {
|
||||
return current;
|
||||
}
|
||||
return new Set(defaultExpanded);
|
||||
});
|
||||
}, [defaultExpanded]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.selectedPath) {
|
||||
return;
|
||||
}
|
||||
setExpandedPaths((current) => {
|
||||
const next = new Set(current);
|
||||
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
|
||||
next.add(ancestor);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [props.selectedPath]);
|
||||
|
||||
const toggleDirectory = useCallback((path: string) => {
|
||||
setExpandedPaths((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(path)) {
|
||||
next.delete(path);
|
||||
} else {
|
||||
next.add(path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
{props.error && props.entries.length === 0 ? (
|
||||
<View className="px-4 py-5">
|
||||
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
|
||||
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">{props.error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
contentContainerStyle={{ paddingVertical: 8 }}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<FileTreeRow
|
||||
item={item}
|
||||
selectedPath={props.selectedPath}
|
||||
expanded={expandedPaths.has(item.node.path)}
|
||||
iconColor={iconColor}
|
||||
onPressDirectory={toggleDirectory}
|
||||
onPressFile={props.onSelectFile}
|
||||
/>
|
||||
)}
|
||||
ListEmptyComponent={
|
||||
<View className="px-4 py-5">
|
||||
{props.isPending ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<>
|
||||
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
|
||||
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">
|
||||
{props.searchQuery.trim().length > 0
|
||||
? "Try a different search."
|
||||
: "The workspace file index is empty."}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { ComponentType } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { LoadingStrip } from "../../components/LoadingStrip";
|
||||
import {
|
||||
type NativeReviewDiffViewProps,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
|
||||
import {
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_MONO_FONT_FAMILY,
|
||||
renderVisibleWhitespace,
|
||||
} from "../review/reviewDiffRendering";
|
||||
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
|
||||
import {
|
||||
buildNativeSourceRows,
|
||||
buildNativeSourceTokens,
|
||||
NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
NATIVE_SOURCE_ROW_HEIGHT,
|
||||
NATIVE_SOURCE_STYLE,
|
||||
nativeSourceRowId,
|
||||
} from "./nativeSourceFileAdapter";
|
||||
import { sourceHighlightAtom } from "./sourceHighlightingState";
|
||||
|
||||
const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
|
||||
const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth;
|
||||
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
|
||||
|
||||
interface SourceFileSurfaceProps {
|
||||
readonly contents: string;
|
||||
readonly path: string;
|
||||
readonly initialLine?: number | null;
|
||||
}
|
||||
|
||||
type SourceHighlightStatus = "highlighting" | "ready" | "error";
|
||||
|
||||
function splitSourceLines(contents: string): ReadonlyArray<string> {
|
||||
return contents.replace(/\r\n?/g, "\n").split("\n");
|
||||
}
|
||||
|
||||
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
|
||||
readonly index: number;
|
||||
readonly line: string;
|
||||
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
|
||||
readonly highlighted: boolean;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className={cn("flex-row", props.highlighted && "bg-primary/10")}
|
||||
style={{ minHeight: SOURCE_LINE_HEIGHT }}
|
||||
>
|
||||
<NativeText
|
||||
className="select-none pr-3 text-right text-foreground-tertiary"
|
||||
style={{
|
||||
width: SOURCE_LINE_NUMBER_WIDTH,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
|
||||
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
|
||||
}}
|
||||
>
|
||||
{props.index + 1}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
selectable
|
||||
numberOfLines={1}
|
||||
className="font-normal text-foreground"
|
||||
style={{
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontSize: MOBILE_CODE_SURFACE.fontSize,
|
||||
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
|
||||
minWidth: 320,
|
||||
}}
|
||||
>
|
||||
{props.tokens && props.tokens.length > 0
|
||||
? (() => {
|
||||
let offset = 0;
|
||||
return props.tokens.map((token) => {
|
||||
const start = offset;
|
||||
offset += token.content.length;
|
||||
|
||||
const fontWeight =
|
||||
token.fontStyle !== null && (token.fontStyle & 2) === 2
|
||||
? ("700" as const)
|
||||
: ("400" as const);
|
||||
const fontStyle =
|
||||
token.fontStyle !== null && (token.fontStyle & 1) === 1
|
||||
? ("italic" as const)
|
||||
: ("normal" as const);
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
key={`${start}:${token.content.length}:${token.color ?? ""}`}
|
||||
selectable
|
||||
style={{
|
||||
color: token.color ?? undefined,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontWeight,
|
||||
fontStyle,
|
||||
}}
|
||||
>
|
||||
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
|
||||
</NativeText>
|
||||
);
|
||||
});
|
||||
})()
|
||||
: renderVisibleWhitespace(props.line || " ")}
|
||||
</NativeText>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function useSourceFileModel(props: SourceFileSurfaceProps) {
|
||||
const colorScheme = useColorScheme();
|
||||
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
|
||||
const normalizedContents = useMemo(
|
||||
() => props.contents.replace(/\r\n?/g, "\n"),
|
||||
[props.contents],
|
||||
);
|
||||
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
|
||||
const targetIndex =
|
||||
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
|
||||
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
|
||||
: null;
|
||||
const highlightAtom = useMemo(
|
||||
() => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
|
||||
[normalizedContents, props.path, theme],
|
||||
);
|
||||
const highlightResult = useAtomValue(highlightAtom);
|
||||
const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
|
||||
const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
|
||||
? "error"
|
||||
: AsyncResult.isSuccess(highlightResult)
|
||||
? "ready"
|
||||
: "highlighting";
|
||||
|
||||
return { lines, status, targetIndex, theme, tokens };
|
||||
}
|
||||
|
||||
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
|
||||
if (props.status === "highlighting") {
|
||||
return <LoadingStrip />;
|
||||
}
|
||||
if (props.status === "error") {
|
||||
return (
|
||||
<View className="border-b border-border bg-card px-4 py-2">
|
||||
<Text className="text-2xs font-t3-medium uppercase text-foreground-muted">Plain text</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function NativeSourceFileSurface(
|
||||
props: SourceFileSurfaceProps & {
|
||||
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
|
||||
},
|
||||
) {
|
||||
const { NativeView } = props;
|
||||
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
|
||||
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
|
||||
const selectedRowIdsJson = useMemo(
|
||||
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
|
||||
[targetIndex],
|
||||
);
|
||||
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<NativeView
|
||||
key={props.path}
|
||||
collapsable={false}
|
||||
testID="source-native-code-view"
|
||||
style={{ flex: 1 }}
|
||||
appearanceScheme={theme}
|
||||
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
|
||||
initialRowIndex={targetIndex ?? -1}
|
||||
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
|
||||
rowsJson={rowsJson}
|
||||
selectedRowIdsJson={selectedRowIdsJson}
|
||||
styleJson={NATIVE_SOURCE_STYLE_JSON}
|
||||
themeJson={themeJson}
|
||||
tokensJson={tokensJson}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
|
||||
const listRef = useRef<FlatList<string>>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (targetIndex === null) {
|
||||
return;
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [props.path, targetIndex]);
|
||||
|
||||
const renderLine = useCallback(
|
||||
({ item, index }: { item: string; index: number }) => (
|
||||
<HighlightedSourceLine
|
||||
index={index}
|
||||
line={item}
|
||||
tokens={tokens?.[index] ?? null}
|
||||
highlighted={index === targetIndex}
|
||||
/>
|
||||
),
|
||||
[targetIndex, tokens],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<ScrollView horizontal bounces={false} className="flex-1">
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={lines}
|
||||
keyExtractor={(_line, index) => String(index)}
|
||||
initialNumToRender={80}
|
||||
maxToRenderPerBatch={80}
|
||||
windowSize={12}
|
||||
getItemLayout={(_data, index) => ({
|
||||
length: SOURCE_LINE_HEIGHT,
|
||||
offset: SOURCE_LINE_HEIGHT * index,
|
||||
index,
|
||||
})}
|
||||
contentContainerStyle={{
|
||||
minWidth: "100%",
|
||||
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
renderItem={renderLine}
|
||||
/>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function SourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const NativeView = resolveNativeReviewDiffView();
|
||||
return NativeView ? (
|
||||
<NativeSourceFileSurface {...props} NativeView={NativeView} />
|
||||
) : (
|
||||
<JavaScriptSourceFileSurface {...props} />
|
||||
);
|
||||
}
|
||||
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user