Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56ee51fac3 |
No files matched your search
@@ -22,9 +22,6 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -34,9 +31,6 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -60,18 +54,12 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
test_browser:
|
||||
name: Test Browser
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
|
||||
@@ -180,46 +180,12 @@ jobs:
|
||||
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
relay_url: ${{ steps.public_config.outputs.relay_url }}
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- id: relay_state
|
||||
name: Read production relay tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
vp run --filter t3code-relay deploy \
|
||||
--stage prod \
|
||||
--read-state \
|
||||
--github-output \
|
||||
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
|
||||
|
||||
- name: Upload relay client tracing config
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing.env
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- id: public_config
|
||||
name: Resolve production relay public config
|
||||
shell: bash
|
||||
@@ -272,29 +238,21 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -314,25 +272,6 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -531,19 +470,6 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -551,13 +477,6 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -589,20 +508,6 @@ jobs:
|
||||
- --filter=@t3tools/web...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -612,24 +517,6 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
@@ -783,20 +670,6 @@ jobs:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -843,9 +716,6 @@ jobs:
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
|
||||
@@ -27,7 +27,6 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
@@ -34,8 +33,6 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -60,7 +57,7 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -68,7 +65,7 @@ function killChildTreeByPid(pid, signal) {
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (hostPlatform === "win32") {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -197,7 +194,7 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (hostPlatform === "win32") {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
@@ -31,11 +30,9 @@ 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 = 10;
|
||||
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);
|
||||
@@ -298,11 +295,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
@@ -315,7 +308,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (hostPlatform !== "linux") {
|
||||
if (process.platform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -345,7 +338,7 @@ export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
@@ -361,7 +354,7 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
if (process.platform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { arch, platform, tmpdir } from "node:os";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (hostPlatform) {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -21,12 +17,12 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (hostPlatform !== "win32") {
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
@@ -43,7 +39,7 @@ function repairPathFile(electronDir, platformPath) {
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (hostPlatform === "darwin") {
|
||||
if (process.platform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
@@ -62,7 +58,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (hostPlatform !== "darwin") {
|
||||
if (process.platform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -80,7 +76,7 @@ function missingRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (hostPlatform !== "darwin") {
|
||||
if (process.platform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -115,16 +111,16 @@ function runChecked(command, args) {
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (hostPlatform === "darwin") {
|
||||
if (process.platform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
|
||||
@@ -54,7 +54,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -49,7 +49,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
|
||||
@@ -54,7 +54,6 @@ function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarne
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -112,56 +112,41 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk(
|
||||
"stderr",
|
||||
new TextEncoder().encode("normal shutdown\n"),
|
||||
);
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
yield* Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
);
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -169,98 +154,6 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -21,10 +21,8 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -32,13 +30,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
@@ -114,84 +113,10 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [
|
||||
...session.chunks,
|
||||
{
|
||||
streamName,
|
||||
chunk: retainedChunk,
|
||||
},
|
||||
];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) {
|
||||
break;
|
||||
}
|
||||
if (first.chunk.byteLength <= overflow) {
|
||||
overflow -= first.chunk.byteLength;
|
||||
byteLength -= first.chunk.byteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
chunk: first.chunk.slice(overflow),
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
@@ -376,86 +301,45 @@ const backendOutputLogLayer = Layer.effect(
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
|
||||
return Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) => {
|
||||
return {
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn(
|
||||
"desktop.observability.backendOutput.writeSessionBoundary",
|
||||
)(function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
|
||||
function* ({ details }) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [
|
||||
current,
|
||||
Option.map(current, (value) => ({
|
||||
...value,
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
})),
|
||||
]);
|
||||
if (Option.isNone(session)) {
|
||||
return;
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "START",
|
||||
details: session.value.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.value.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
} satisfies DesktopBackendOutputLogShape;
|
||||
},
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -41,7 +41,6 @@ function makeEnvironmentLayer(
|
||||
options?: {
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
@@ -52,7 +51,7 @@ function makeEnvironmentLayer(
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -193,39 +192,4 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("passes the packaged resource monitor path to the backend", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -56,42 +56,6 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
BackendObservabilitySettings,
|
||||
never,
|
||||
@@ -125,7 +89,6 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -152,12 +115,6 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
@@ -199,14 +156,9 @@ export const layer = Layer.effect(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resourceMonitorPath,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
@@ -24,15 +23,11 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -48,8 +43,6 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
@@ -66,7 +59,6 @@ function makeProcess(options?: {
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -78,7 +70,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
getOutputFd: () => Stream.empty,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -115,7 +107,6 @@ function makeManagerLayer(input: {
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly desktopTelemetryPublisher?: Partial<DesktopTelemetryPublisher.DesktopTelemetryPublisherShape>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -129,21 +120,12 @@ function makeManagerLayer(input: {
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
: DesktopState.layer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -202,7 +184,8 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -225,8 +208,6 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
@@ -237,88 +218,6 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
|
||||
const outputDrainStarted = yield* Deferred.make<void>();
|
||||
const outputChunks = yield* Ref.make<Array<string>>([]);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.succeed(outputDrainStarted, void 0).pipe(
|
||||
Effect.andThen(Effect.sleep(Duration.millis(50))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
writeOutputChunk: (_streamName, chunk) =>
|
||||
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
|
||||
persistFailure: () =>
|
||||
Ref.get(outputChunks).pipe(
|
||||
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
@@ -356,7 +255,8 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -389,8 +289,6 @@ describe("DesktopBackendManager", () => {
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReady = yield* Ref.make(false);
|
||||
const quitting = yield* Ref.make(false);
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -422,15 +320,6 @@ describe("DesktopBackendManager", () => {
|
||||
desktopWindow: {
|
||||
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -450,8 +339,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.stop();
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
|
||||
const stoppedSnapshot = yield* manager.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReady));
|
||||
@@ -465,7 +352,6 @@ describe("DesktopBackendManager", () => {
|
||||
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -485,9 +371,6 @@ describe("DesktopBackendManager", () => {
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -495,7 +378,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(499));
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
@@ -552,13 +434,6 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* manager.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* manager.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -16,21 +16,17 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
@@ -39,7 +35,6 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
|
||||
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.millis(250);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
@@ -93,10 +88,6 @@ class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnErro
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
@@ -233,7 +224,6 @@ function drainBackendOutput(
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
@@ -243,23 +233,6 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
@@ -274,47 +247,23 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
|
||||
Stream.runForEach(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
if (options.captureOutput) {
|
||||
outputFibers.push(
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped),
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped),
|
||||
);
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
@@ -325,16 +274,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exit = describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
|
||||
yield* Effect.forEach(outputFibers, Fiber.interrupt, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.ignore);
|
||||
return exit;
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
@@ -343,7 +283,6 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -480,13 +419,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
if (isCurrentRun) {
|
||||
if (Option.isSome(pid)) {
|
||||
if (nextState.desiredRunning) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
@@ -500,14 +436,13 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
}));
|
||||
yield* backendOutputLog.beginSession({
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
@@ -540,16 +475,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
});
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -660,7 +589,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options).pipe(Effect.andThen(backendOutputLog.discardSession)),
|
||||
onSome: (run) => closeRun(run, options),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ export interface ElectronAppShape {
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -102,7 +101,6 @@ const make = ElectronApp.of({
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export interface ElectronMenuPosition {
|
||||
readonly x: number;
|
||||
@@ -80,113 +79,109 @@ const normalizePosition = (
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const layer = Layer.effect(
|
||||
ElectronMenu,
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
export const layer = Layer.sync(ElectronMenu, () => {
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
}
|
||||
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
template.push(itemOption);
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export interface ElectronPowerMonitorShape {
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
ElectronPowerMonitorShape
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -6,7 +6,6 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -38,7 +37,6 @@ export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWind
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
@@ -100,7 +98,7 @@ const make = Effect.gen(function* () {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
if (process.platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
@@ -19,7 +18,6 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -45,7 +43,6 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
@@ -56,13 +53,11 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
|
||||
Effect.flatMap((app) => app.metadata),
|
||||
);
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const processArch = yield* HostProcessArchitecture;
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: __dirname,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
platform,
|
||||
processArch,
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
...metadata,
|
||||
});
|
||||
}),
|
||||
@@ -105,7 +100,6 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
DesktopSecretStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -148,7 +142,6 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -189,55 +189,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps element picking active during subframe navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isFocused: () => true,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn(), removeListener: 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.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
|
||||
yield* Effect.yieldNow;
|
||||
expect(pick.pollUnsafe()).toBeUndefined();
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
|
||||
expect(yield* Fiber.join(pick)).toBeNull();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1344,14 +1344,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
};
|
||||
const onDestroyed = () => settle(null);
|
||||
const onNavigated = (
|
||||
_event: Electron.Event,
|
||||
_url: string,
|
||||
_isInPlace: boolean,
|
||||
isMainFrame: boolean,
|
||||
) => {
|
||||
if (isMainFrame) settle(null);
|
||||
};
|
||||
const onNavigated = () => settle(null);
|
||||
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
|
||||
yield* attempt("pickElement.register", () => {
|
||||
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,264 +0,0 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly suspended: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
DesktopTelemetryPublisherShape
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return { ...state, locked: booleanState(event.value) };
|
||||
case "suspended":
|
||||
return { ...state, suspended: event.value };
|
||||
case "onBattery":
|
||||
return { ...state, onBattery: booleanState(event.value) };
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
idleSeconds,
|
||||
locked,
|
||||
suspended: currentPower.suspended,
|
||||
onBattery: booleanState(onBattery),
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: currentPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: currentPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: metric.creationTime,
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
Ref.get(latest).pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.fromPubSub(changes),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -40,7 +40,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -68,7 +68,6 @@ function makeFakeBrowserWindow() {
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
setTitle: vi.fn(),
|
||||
setTitleBarOverlay: vi.fn(),
|
||||
show: vi.fn(),
|
||||
@@ -79,7 +78,6 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
}
|
||||
@@ -136,17 +134,10 @@ function makeTestLayer(input: {
|
||||
readonly window: Electron.BrowserWindow;
|
||||
readonly createCount: Ref.Ref<number>;
|
||||
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
|
||||
readonly openedExternalUrls?: unknown[];
|
||||
}) {
|
||||
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: (options) =>
|
||||
Effect.sync(() => {
|
||||
input.createdWindowOptions?.push(options);
|
||||
}).pipe(
|
||||
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
|
||||
Effect.as(input.window),
|
||||
),
|
||||
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
|
||||
main: Ref.get(input.mainWindow),
|
||||
currentMainOrFirst: Ref.get(input.mainWindow),
|
||||
focusedMainOrFirst: Ref.get(input.mainWindow),
|
||||
@@ -214,12 +205,10 @@ describe("DesktopWindow", () => {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
createdWindowOptions,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -229,8 +218,6 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
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.equal(fakeWindow.openDevTools.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
@@ -82,10 +82,9 @@ function resolveDesktopDevServerUrl(
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
platform: NodeJS.Platform,
|
||||
): { icon: string } | Record<string, never> {
|
||||
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = platform === "win32" ? "ico" : "png";
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
return Option.match(iconPaths[ext], {
|
||||
onNone: () => ({}),
|
||||
onSome: (icon) => ({ icon }),
|
||||
@@ -107,11 +106,8 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): WindowTitleBarOptions {
|
||||
if (platform === "darwin") {
|
||||
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
@@ -131,7 +127,6 @@ function getWindowTitleBarOptions(
|
||||
function syncWindowAppearance(
|
||||
window: Electron.BrowserWindow,
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
@@ -139,7 +134,7 @@ function syncWindowAppearance(
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
@@ -184,7 +179,7 @@ const make = Effect.gen(function* () {
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const iconOption = getIconOption(iconPaths);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const window = yield* electronWindow.create({
|
||||
width: 1100,
|
||||
@@ -193,11 +188,10 @@ const make = Effect.gen(function* () {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
...iconOption,
|
||||
title: environment.displayName,
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors),
|
||||
webPreferences: {
|
||||
preload: environment.preloadPath,
|
||||
contextIsolation: true,
|
||||
@@ -207,10 +201,6 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
window.setAutoHideCursor(false);
|
||||
}
|
||||
|
||||
yield* previewManager.setMainWindow(window);
|
||||
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
if (
|
||||
@@ -328,7 +318,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (environment.platform === "linux") {
|
||||
if (process.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
@@ -418,7 +408,7 @@ const make = Effect.gen(function* () {
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
yield* electronWindow.syncAllAppearance((window) =>
|
||||
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
|
||||
syncWindowAppearance(window, shouldUseDarkColors),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"neutral": "#F5F5F5",
|
||||
"border": "#E5E5EA",
|
||||
"ring": "#A3A3A3",
|
||||
"muted": "#F2F2F7",
|
||||
"muted": "#F5F5F5",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"darkColors": {
|
||||
@@ -30,7 +30,7 @@
|
||||
"neutral": "#1C1C1C",
|
||||
"border": "#2A2A2A",
|
||||
"ring": "#525252",
|
||||
"muted": "#0E0E0E",
|
||||
"muted": "#1C1C1C",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"design": {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
--color-foreground: #262626;
|
||||
--color-foreground-secondary: #525252;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #8e8e93;
|
||||
--color-foreground-tertiary: #a3a3a3;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(0, 0, 0, 0.08);
|
||||
@@ -28,9 +28,6 @@
|
||||
/* Subtle backgrounds (badges, pills, overlays) */
|
||||
--color-subtle: rgba(0, 0, 0, 0.04);
|
||||
--color-subtle-strong: rgba(0, 0, 0, 0.08);
|
||||
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
|
||||
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
|
||||
--color-inline-skill-foreground: #a21caf;
|
||||
|
||||
/* Primary action */
|
||||
--color-primary: #262626;
|
||||
@@ -61,8 +58,6 @@
|
||||
/* Header / glass chrome */
|
||||
--color-header: rgba(255, 255, 255, 0.97);
|
||||
--color-header-border: rgba(0, 0, 0, 0.06);
|
||||
--color-glass-surface: rgba(255, 255, 255, 0.72);
|
||||
--color-glass-tint: rgba(255, 255, 255, 0.18);
|
||||
|
||||
/* StatusBar */
|
||||
--color-status-bar: #f2f2f7;
|
||||
@@ -110,8 +105,8 @@
|
||||
/* Text */
|
||||
--color-foreground: #f5f5f5;
|
||||
--color-foreground-secondary: #a3a3a3;
|
||||
--color-foreground-muted: #8e8e93;
|
||||
--color-foreground-tertiary: #636366;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #525252;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(255, 255, 255, 0.06);
|
||||
@@ -121,9 +116,6 @@
|
||||
/* Subtle backgrounds (badges, pills, overlays) */
|
||||
--color-subtle: rgba(255, 255, 255, 0.04);
|
||||
--color-subtle-strong: rgba(255, 255, 255, 0.08);
|
||||
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
|
||||
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
|
||||
--color-inline-skill-foreground: #f0abfc;
|
||||
|
||||
/* Primary action */
|
||||
--color-primary: #f5f5f5;
|
||||
@@ -144,18 +136,16 @@
|
||||
/* Inputs */
|
||||
--color-input: #141414;
|
||||
--color-input-border: rgba(255, 255, 255, 0.08);
|
||||
--color-placeholder: #8e8e93;
|
||||
--color-placeholder: #737373;
|
||||
|
||||
/* Icons */
|
||||
--color-icon: #f5f5f5;
|
||||
--color-icon-muted: #a3a3a3;
|
||||
--color-icon-subtle: #8e8e93;
|
||||
--color-icon-subtle: #737373;
|
||||
|
||||
/* Header / glass chrome */
|
||||
--color-header: rgba(10, 10, 10, 0.97);
|
||||
--color-header-border: rgba(255, 255, 255, 0.06);
|
||||
--color-glass-surface: rgba(23, 23, 23, 0.78);
|
||||
--color-glass-tint: rgba(23, 23, 23, 0.24);
|
||||
|
||||
/* StatusBar */
|
||||
--color-status-bar: #0a0a0a;
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ComposerEditorModule"]
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3ComposerEditor'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'Native attributed composer editor for T3 Code mobile.'
|
||||
s.description = 'UIKit-backed rich text composer with atomic skill and file tokens.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '16.4',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
# Swift/Objective-C compatibility
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
|
||||
end
|
||||
@@ -1,71 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public class T3ComposerEditorModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3ComposerEditor")
|
||||
|
||||
View(T3ComposerEditorView.self) {
|
||||
Prop("value") { (view: T3ComposerEditorView, value: String) in
|
||||
view.setValue(value)
|
||||
}
|
||||
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
|
||||
view.setSelectionJson(selectionJson)
|
||||
}
|
||||
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
|
||||
view.setThemeJson(themeJson)
|
||||
}
|
||||
Prop("placeholder") { (view: T3ComposerEditorView, placeholder: String) in
|
||||
view.setPlaceholder(placeholder)
|
||||
}
|
||||
Prop("fontFamily") { (view: T3ComposerEditorView, fontFamily: String) in
|
||||
view.setFontFamily(fontFamily)
|
||||
}
|
||||
Prop("fontSize") { (view: T3ComposerEditorView, fontSize: Double) in
|
||||
view.setFontSize(CGFloat(fontSize))
|
||||
}
|
||||
Prop("lineHeight") { (view: T3ComposerEditorView, lineHeight: Double) in
|
||||
view.setLineHeight(CGFloat(lineHeight))
|
||||
}
|
||||
Prop("contentInsetVertical") { (view: T3ComposerEditorView, contentInsetVertical: Double) in
|
||||
view.setContentInsetVertical(CGFloat(contentInsetVertical))
|
||||
}
|
||||
Prop("editable") { (view: T3ComposerEditorView, editable: Bool) in
|
||||
view.setEditable(editable)
|
||||
}
|
||||
Prop("scrollEnabled") { (view: T3ComposerEditorView, scrollEnabled: Bool) in
|
||||
view.setScrollEnabled(scrollEnabled)
|
||||
}
|
||||
Prop("autoFocus") { (view: T3ComposerEditorView, autoFocus: Bool) in
|
||||
view.setAutoFocus(autoFocus)
|
||||
}
|
||||
Prop("autoCorrect") { (view: T3ComposerEditorView, autoCorrect: Bool) in
|
||||
view.setAutoCorrect(autoCorrect)
|
||||
}
|
||||
Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in
|
||||
view.setSpellCheck(spellCheck)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onComposerChange",
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange"
|
||||
)
|
||||
|
||||
AsyncFunction("focus") { (view: T3ComposerEditorView) in
|
||||
view.focusEditor()
|
||||
}
|
||||
AsyncFunction("blur") { (view: T3ComposerEditorView) in
|
||||
view.blurEditor()
|
||||
}
|
||||
AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
|
||||
view.setSelection(start: start, end: end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,819 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
private struct ComposerTokenPayload: Decodable {
|
||||
let type: String
|
||||
let source: String
|
||||
let label: String
|
||||
let iconUri: String?
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerSelectionPayload: Decodable {
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerThemePayload: Decodable {
|
||||
let text: String
|
||||
let placeholder: String
|
||||
let chipBackground: String
|
||||
let chipBorder: String
|
||||
let chipText: String
|
||||
let skillBackground: String
|
||||
let skillBorder: String
|
||||
let skillText: String
|
||||
let fileTint: String
|
||||
}
|
||||
|
||||
private struct ComposerChipStyle {
|
||||
let tint: UIColor
|
||||
let backgroundColor: UIColor
|
||||
let borderColor: UIColor
|
||||
let textColor: UIColor
|
||||
}
|
||||
|
||||
private final class ComposerTextAttachment: NSTextAttachment {
|
||||
let source: String
|
||||
|
||||
init(source: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
|
||||
self.source = source
|
||||
super.init(data: nil, ofType: nil)
|
||||
self.image = image
|
||||
bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
private final class ComposerTextView: UITextView {
|
||||
private static let pastedImageDirectoryName = "t3-composer-paste"
|
||||
private static let stalePastedImageAge: TimeInterval = 60 * 60
|
||||
|
||||
var onPasteImages: (([String]) -> Void)?
|
||||
var onAttributedMutation: (() -> Void)?
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
if action == #selector(paste(_:)) {
|
||||
let pasteboard = UIPasteboard.general
|
||||
if pasteboard.hasImages ||
|
||||
pasteboard.itemProviders.contains(where: {
|
||||
$0.canLoadObject(ofClass: UIImage.self)
|
||||
}) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.canPerformAction(action, withSender: sender)
|
||||
}
|
||||
|
||||
override func paste(_ sender: Any?) {
|
||||
let pasteboard = UIPasteboard.general
|
||||
let imageProviders = pasteboard.itemProviders.filter {
|
||||
$0.canLoadObject(ofClass: UIImage.self)
|
||||
}
|
||||
if !imageProviders.isEmpty {
|
||||
loadImages(from: imageProviders)
|
||||
return
|
||||
}
|
||||
|
||||
let images = pasteboard.images ?? []
|
||||
if !images.isEmpty {
|
||||
let urls = images.compactMap(Self.writeTemporaryImage)
|
||||
if !urls.isEmpty {
|
||||
onPasteImages?(urls)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.paste(sender)
|
||||
}
|
||||
|
||||
override func deleteBackward() {
|
||||
guard selectedRange.length == 0, selectedRange.location > 0 else {
|
||||
super.deleteBackward()
|
||||
return
|
||||
}
|
||||
|
||||
let previousOffset = selectedRange.location - 1
|
||||
if textStorage.attribute(.attachment, at: previousOffset, effectiveRange: nil)
|
||||
is ComposerTextAttachment {
|
||||
replaceDisplayRange(NSRange(location: previousOffset, length: 1))
|
||||
return
|
||||
}
|
||||
|
||||
super.deleteBackward()
|
||||
}
|
||||
|
||||
private func replaceDisplayRange(_ range: NSRange) {
|
||||
guard let start = position(from: beginningOfDocument, offset: range.location),
|
||||
let end = position(from: start, offset: range.length),
|
||||
let textRange = textRange(from: start, to: end) else {
|
||||
return
|
||||
}
|
||||
replace(textRange, withText: "")
|
||||
}
|
||||
|
||||
private func loadImages(from providers: [NSItemProvider]) {
|
||||
let group = DispatchGroup()
|
||||
let lock = NSLock()
|
||||
var images = [UIImage?](repeating: nil, count: providers.count)
|
||||
|
||||
for (index, provider) in providers.enumerated() {
|
||||
group.enter()
|
||||
provider.loadObject(ofClass: UIImage.self) { object, _ in
|
||||
defer { group.leave() }
|
||||
guard let image = object as? UIImage else {
|
||||
return
|
||||
}
|
||||
lock.lock()
|
||||
images[index] = image
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
group.notify(queue: .main) { [weak self] in
|
||||
let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
|
||||
if !urls.isEmpty {
|
||||
self?.onPasteImages?(urls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func copy(_ sender: Any?) {
|
||||
guard selectedRange.length > 0 else {
|
||||
return super.copy(sender)
|
||||
}
|
||||
UIPasteboard.general.string = serializedText(in: selectedRange)
|
||||
}
|
||||
|
||||
override func cut(_ sender: Any?) {
|
||||
guard isEditable, selectedRange.length > 0 else {
|
||||
return super.cut(sender)
|
||||
}
|
||||
copy(sender)
|
||||
textStorage.replaceCharacters(in: selectedRange, with: "")
|
||||
selectedRange = NSRange(location: selectedRange.location, length: 0)
|
||||
onAttributedMutation?()
|
||||
}
|
||||
|
||||
func serializedText() -> String {
|
||||
serializedText(in: NSRange(location: 0, length: attributedText.length))
|
||||
}
|
||||
|
||||
func serializedText(in range: NSRange) -> String {
|
||||
guard range.length > 0 else {
|
||||
return ""
|
||||
}
|
||||
|
||||
let source = NSMutableString()
|
||||
let nsString = attributedText.string as NSString
|
||||
var cursor = range.location
|
||||
let end = NSMaxRange(range)
|
||||
attributedText.enumerateAttribute(.attachment, in: range) { value, attachmentRange, _ in
|
||||
if attachmentRange.location > cursor {
|
||||
source.append(
|
||||
nsString.substring(
|
||||
with: NSRange(location: cursor, length: attachmentRange.location - cursor)
|
||||
)
|
||||
)
|
||||
}
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
source.append(attachment.source)
|
||||
} else {
|
||||
source.append(nsString.substring(with: attachmentRange))
|
||||
}
|
||||
cursor = NSMaxRange(attachmentRange)
|
||||
}
|
||||
if cursor < end {
|
||||
source.append(nsString.substring(with: NSRange(location: cursor, length: end - cursor)))
|
||||
}
|
||||
return source as String
|
||||
}
|
||||
|
||||
func sourceOffset(forDisplayOffset displayOffset: Int) -> Int {
|
||||
let boundedOffset = max(0, min(attributedText.length, displayOffset))
|
||||
if boundedOffset == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
var sourceOffset = 0
|
||||
let range = NSRange(location: 0, length: boundedOffset)
|
||||
attributedText.enumerateAttribute(.attachment, in: range) { value, attributeRange, _ in
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
sourceOffset += (attachment.source as NSString).length
|
||||
} else {
|
||||
sourceOffset += attributeRange.length
|
||||
}
|
||||
}
|
||||
return sourceOffset
|
||||
}
|
||||
|
||||
private static func writeTemporaryImage(_ image: UIImage) -> String? {
|
||||
guard let data = image.pngData() else {
|
||||
return nil
|
||||
}
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
removeStaleTemporaryImages(in: directory)
|
||||
let url = directory.appendingPathComponent("\(UUID().uuidString).png")
|
||||
try data.write(to: url, options: .atomic)
|
||||
return url.absoluteString
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func removeStaleTemporaryImages(in directory: URL) {
|
||||
let cutoff = Date().addingTimeInterval(-stalePastedImageAge)
|
||||
guard let urls = try? FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],
|
||||
options: [.skipsHiddenFiles]
|
||||
) else {
|
||||
return
|
||||
}
|
||||
|
||||
for url in urls {
|
||||
guard
|
||||
let values = try? url.resourceValues(
|
||||
forKeys: [.contentModificationDateKey, .isRegularFileKey]
|
||||
),
|
||||
values.isRegularFile == true,
|
||||
let modifiedAt = values.contentModificationDate,
|
||||
modifiedAt < cutoff
|
||||
else {
|
||||
continue
|
||||
}
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
private let textView = ComposerTextView()
|
||||
private let placeholderLabel = UILabel()
|
||||
private var value = ""
|
||||
private var tokensJson = "[]"
|
||||
private var tokens: [ComposerTokenPayload] = []
|
||||
private var requestedSelection: ComposerSelectionPayload?
|
||||
private var theme = ComposerThemePayload(
|
||||
text: "#262626",
|
||||
placeholder: "#8e8e93",
|
||||
chipBackground: "#f2f2f7",
|
||||
chipBorder: "#dedee3",
|
||||
chipText: "#262626",
|
||||
skillBackground: "#f9e8fb",
|
||||
skillBorder: "#e5a6eb",
|
||||
skillText: "#a21caf",
|
||||
fileTint: "#737373"
|
||||
)
|
||||
private var fontFamily = "DMSans_400Regular"
|
||||
private var fontSize: CGFloat = 15
|
||||
private var lineHeight: CGFloat = 22
|
||||
private var contentInsetVertical: CGFloat = 0
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
private var isApplyingControlledValue = false
|
||||
private var lastContentSize = CGSize.zero
|
||||
private var iconImages: [String: UIImage] = [:]
|
||||
private var pendingIconUris = Set<String>()
|
||||
private var tokensNeedRebuild = false
|
||||
|
||||
let onComposerChange = EventDispatcher()
|
||||
let onComposerSelectionChange = EventDispatcher()
|
||||
let onComposerFocus = EventDispatcher()
|
||||
let onComposerBlur = EventDispatcher()
|
||||
let onComposerPasteImages = EventDispatcher()
|
||||
let onComposerContentSizeChange = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
clipsToBounds = false
|
||||
textView.delegate = self
|
||||
textView.backgroundColor = .clear
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
textView.keyboardDismissMode = .interactive
|
||||
textView.alwaysBounceVertical = false
|
||||
textView.showsVerticalScrollIndicator = true
|
||||
textView.adjustsFontForContentSizeCategory = true
|
||||
textView.onPasteImages = { [weak self] urls in
|
||||
self?.onComposerPasteImages(["uris": urls])
|
||||
}
|
||||
textView.onAttributedMutation = { [weak self] in
|
||||
self?.emitTextChange()
|
||||
}
|
||||
addSubview(textView)
|
||||
|
||||
placeholderLabel.numberOfLines = 0
|
||||
placeholderLabel.adjustsFontForContentSizeCategory = true
|
||||
addSubview(placeholderLabel)
|
||||
applyTypography()
|
||||
applyTheme()
|
||||
}
|
||||
|
||||
public override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
textView.frame = bounds
|
||||
let placeholderX = textView.textContainerInset.left + textView.textContainer.lineFragmentPadding
|
||||
let placeholderY = textView.textContainerInset.top
|
||||
let placeholderWidth = max(
|
||||
0,
|
||||
bounds.width - placeholderX - textView.textContainerInset.right -
|
||||
textView.textContainer.lineFragmentPadding
|
||||
)
|
||||
placeholderLabel.frame = CGRect(
|
||||
x: placeholderX,
|
||||
y: placeholderY,
|
||||
width: placeholderWidth,
|
||||
height: max(lineHeight, placeholderLabel.font.lineHeight)
|
||||
)
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
guard window != nil, shouldAutoFocus, !didAutoFocus else {
|
||||
return
|
||||
}
|
||||
didAutoFocus = true
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.textView.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
func setValue(_ value: String) {
|
||||
self.value = value
|
||||
applyControlledDocument(force: tokensNeedRebuild)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard self.tokensJson != tokensJson else {
|
||||
return
|
||||
}
|
||||
self.tokensJson = tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
applyControlledDocument(force: true)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setSelectionJson(_ selectionJson: String) {
|
||||
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
func setThemeJson(_ themeJson: String) {
|
||||
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
|
||||
return
|
||||
}
|
||||
theme = nextTheme
|
||||
applyTheme()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setPlaceholder(_ placeholder: String) {
|
||||
placeholderLabel.text = placeholder
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
func setFontFamily(_ fontFamily: String) {
|
||||
self.fontFamily = fontFamily
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setFontSize(_ fontSize: CGFloat) {
|
||||
self.fontSize = fontSize
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setLineHeight(_ lineHeight: CGFloat) {
|
||||
self.lineHeight = lineHeight
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setContentInsetVertical(_ contentInsetVertical: CGFloat) {
|
||||
self.contentInsetVertical = contentInsetVertical
|
||||
textView.textContainerInset = UIEdgeInsets(
|
||||
top: contentInsetVertical,
|
||||
left: 0,
|
||||
bottom: contentInsetVertical,
|
||||
right: 0
|
||||
)
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
func setEditable(_ editable: Bool) {
|
||||
textView.isEditable = editable
|
||||
}
|
||||
|
||||
func setScrollEnabled(_ scrollEnabled: Bool) {
|
||||
textView.isScrollEnabled = scrollEnabled
|
||||
}
|
||||
|
||||
func setAutoFocus(_ autoFocus: Bool) {
|
||||
shouldAutoFocus = autoFocus
|
||||
}
|
||||
|
||||
func setAutoCorrect(_ autoCorrect: Bool) {
|
||||
textView.autocorrectionType = autoCorrect ? .yes : .no
|
||||
}
|
||||
|
||||
func setSpellCheck(_ spellCheck: Bool) {
|
||||
textView.spellCheckingType = spellCheck ? .yes : .no
|
||||
}
|
||||
|
||||
func focusEditor() {
|
||||
textView.becomeFirstResponder()
|
||||
}
|
||||
|
||||
func blurEditor() {
|
||||
textView.resignFirstResponder()
|
||||
}
|
||||
|
||||
func setSelection(start: Int, end: Int) {
|
||||
requestedSelection = ComposerSelectionPayload(start: start, end: end)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
public func textViewDidChange(_ textView: UITextView) {
|
||||
emitTextChange()
|
||||
}
|
||||
|
||||
public func textViewDidChangeSelection(_ textView: UITextView) {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
public func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
onComposerFocus()
|
||||
}
|
||||
|
||||
public func textViewDidEndEditing(_ textView: UITextView) {
|
||||
onComposerBlur()
|
||||
}
|
||||
|
||||
private func applyControlledDocument(force: Bool = false) {
|
||||
let currentSource = textView.serializedText()
|
||||
guard force || currentSource != value || !documentMatchesExpectedTokens() else {
|
||||
updatePlaceholderVisibility()
|
||||
return
|
||||
}
|
||||
|
||||
let previousSelection = sourceSelection()
|
||||
isApplyingControlledValue = true
|
||||
textView.attributedText = makeAttributedDocument()
|
||||
let targetSelection = requestedSelection ?? previousSelection
|
||||
requestedSelection = nil
|
||||
textView.selectedRange = displayRange(for: targetSelection)
|
||||
isApplyingControlledValue = false
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func makeAttributedDocument() -> NSAttributedString {
|
||||
let result = NSMutableAttributedString()
|
||||
let source = value as NSString
|
||||
var cursor = 0
|
||||
let validTokens = tokens.filter {
|
||||
$0.start >= cursor &&
|
||||
$0.end > $0.start &&
|
||||
$0.end <= source.length &&
|
||||
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
|
||||
}
|
||||
|
||||
for token in validTokens {
|
||||
if token.start < cursor {
|
||||
continue
|
||||
}
|
||||
if token.start > cursor {
|
||||
appendPlainText(
|
||||
source.substring(with: NSRange(location: cursor, length: token.start - cursor)),
|
||||
to: result
|
||||
)
|
||||
}
|
||||
result.append(makeAttachmentString(token))
|
||||
cursor = token.end
|
||||
}
|
||||
if cursor < source.length {
|
||||
appendPlainText(
|
||||
source.substring(with: NSRange(location: cursor, length: source.length - cursor)),
|
||||
to: result
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private func appendPlainText(_ text: String, to result: NSMutableAttributedString) {
|
||||
result.append(NSAttributedString(string: text, attributes: baseAttributes()))
|
||||
}
|
||||
|
||||
private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
|
||||
let isSkill = token.type == "skill"
|
||||
let tint = UIColor(composerHex: isSkill ? theme.skillText : theme.fileTint) ?? .secondaryLabel
|
||||
let iconName = isSkill ? "cube" : "doc"
|
||||
let iconImage = token.iconUri.flatMap(iconImage(for:))
|
||||
let style = ComposerChipStyle(
|
||||
tint: tint,
|
||||
backgroundColor: UIColor(
|
||||
composerHex: isSkill ? theme.skillBackground : theme.chipBackground
|
||||
) ?? .secondarySystemFill,
|
||||
borderColor: UIColor(
|
||||
composerHex: isSkill ? theme.skillBorder : theme.chipBorder
|
||||
) ?? .separator,
|
||||
textColor: UIColor(composerHex: isSkill ? theme.skillText : theme.chipText) ?? .label
|
||||
)
|
||||
let image = renderChip(
|
||||
label: token.label,
|
||||
iconName: iconName,
|
||||
iconImage: iconImage,
|
||||
style: style
|
||||
)
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
let baselineOffset = floor((font.capHeight - image.size.height) / 2)
|
||||
let attachment = ComposerTextAttachment(
|
||||
source: token.source,
|
||||
image: image,
|
||||
size: image.size,
|
||||
baselineOffset: baselineOffset
|
||||
)
|
||||
return NSAttributedString(attachment: attachment)
|
||||
}
|
||||
|
||||
private func renderChip(
|
||||
label: String,
|
||||
iconName: String,
|
||||
iconImage: UIImage?,
|
||||
style: ComposerChipStyle
|
||||
) -> UIImage {
|
||||
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
|
||||
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
|
||||
let fallbackIcon = UIImage(
|
||||
systemName: iconName,
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .medium)
|
||||
)
|
||||
let icon = iconImage ?? fallbackIcon
|
||||
let textSize = (label as NSString).size(withAttributes: [.font: font])
|
||||
let iconWidth = icon == nil ? 0 : 14
|
||||
let iconGap = icon == nil ? 0 : 5
|
||||
let height: CGFloat = 24
|
||||
let width = ceil(9 + CGFloat(iconWidth + iconGap) + textSize.width + 9)
|
||||
let format = UIGraphicsImageRendererFormat.preferred()
|
||||
format.opaque = false
|
||||
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
|
||||
return renderer.image { context in
|
||||
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
|
||||
let path = UIBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), cornerRadius: 7)
|
||||
style.backgroundColor.setFill()
|
||||
path.fill()
|
||||
style.borderColor.setStroke()
|
||||
path.lineWidth = 1
|
||||
path.stroke()
|
||||
|
||||
var x: CGFloat = 9
|
||||
if let icon {
|
||||
let renderedIcon = iconImage == nil
|
||||
? icon.withTintColor(style.tint, renderingMode: .alwaysOriginal)
|
||||
: icon
|
||||
renderedIcon.draw(
|
||||
in: CGRect(x: x, y: 5, width: 14, height: 14)
|
||||
)
|
||||
x += 19
|
||||
}
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.alignment = .left
|
||||
(label as NSString).draw(
|
||||
in: CGRect(x: x, y: 3, width: textSize.width + 1, height: 18),
|
||||
withAttributes: [
|
||||
.font: font,
|
||||
.foregroundColor: style.textColor,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
)
|
||||
context.cgContext.setAllowsAntialiasing(true)
|
||||
}
|
||||
}
|
||||
|
||||
private func iconImage(for uri: String) -> UIImage? {
|
||||
if let image = iconImages[uri] {
|
||||
return image
|
||||
}
|
||||
guard !pendingIconUris.contains(uri), let url = URL(string: uri) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {
|
||||
iconImages[uri] = image
|
||||
return image
|
||||
}
|
||||
|
||||
pendingIconUris.insert(uri)
|
||||
URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
|
||||
guard let self, let data, let image = UIImage(data: data) else {
|
||||
DispatchQueue.main.async {
|
||||
self?.pendingIconUris.remove(uri)
|
||||
}
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
self.pendingIconUris.remove(uri)
|
||||
self.iconImages[uri] = image
|
||||
self.applyControlledDocument(force: true)
|
||||
}
|
||||
}.resume()
|
||||
return nil
|
||||
}
|
||||
|
||||
private func baseAttributes() -> [NSAttributedString.Key: Any] {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.minimumLineHeight = lineHeight
|
||||
paragraph.maximumLineHeight = lineHeight
|
||||
return [
|
||||
.font: font,
|
||||
.foregroundColor: UIColor(composerHex: theme.text) ?? .label,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
}
|
||||
|
||||
private func applyTypography() {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
textView.font = font
|
||||
textView.typingAttributes = baseAttributes()
|
||||
placeholderLabel.font = font
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func applyTheme() {
|
||||
textView.textColor = UIColor(composerHex: theme.text) ?? .label
|
||||
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
|
||||
tintColor = UIColor.systemBlue
|
||||
}
|
||||
|
||||
private func emitTextChange() {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
value = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
onComposerChange([
|
||||
"value": value,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
])
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
let selection = sourceSelection()
|
||||
onComposerSelectionChange([
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
])
|
||||
}
|
||||
|
||||
private func sourceSelection() -> ComposerSelectionPayload {
|
||||
ComposerSelectionPayload(
|
||||
start: textView.sourceOffset(forDisplayOffset: textView.selectedRange.location),
|
||||
end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))
|
||||
)
|
||||
}
|
||||
|
||||
private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {
|
||||
let start = displayOffset(forSourceOffset: selection.start)
|
||||
let end = displayOffset(forSourceOffset: selection.end)
|
||||
return NSRange(location: start, length: max(0, end - start))
|
||||
}
|
||||
|
||||
private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
|
||||
let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
|
||||
var collapsedLength = 0
|
||||
for token in tokens where token.end <= boundedOffset {
|
||||
collapsedLength += max(0, token.end - token.start - 1)
|
||||
}
|
||||
if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
|
||||
return token.start - collapsedLength + 1
|
||||
}
|
||||
return boundedOffset - collapsedLength
|
||||
}
|
||||
|
||||
private func applyRequestedSelection() {
|
||||
guard let requestedSelection else {
|
||||
return
|
||||
}
|
||||
let nextRange = displayRange(for: requestedSelection)
|
||||
guard nextRange.location <= textView.attributedText.length,
|
||||
NSMaxRange(nextRange) <= textView.attributedText.length else {
|
||||
return
|
||||
}
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
placeholderLabel.isHidden = !value.isEmpty
|
||||
}
|
||||
|
||||
private func emitContentSizeIfNeeded() {
|
||||
let nextSize = textView.contentSize
|
||||
guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
|
||||
abs(nextSize.height - lastContentSize.height) > 0.5 else {
|
||||
return
|
||||
}
|
||||
lastContentSize = nextSize
|
||||
onComposerContentSizeChange(["width": nextSize.width, "height": nextSize.height])
|
||||
}
|
||||
|
||||
private func decode<T: Decodable>(_ type: T.Type, from json: String) -> T? {
|
||||
guard let data = json.data(using: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
return try? JSONDecoder().decode(type, from: data)
|
||||
}
|
||||
|
||||
private func tokensMatchCurrentValue() -> Bool {
|
||||
let source = value as NSString
|
||||
return tokens.allSatisfy {
|
||||
$0.start >= 0 &&
|
||||
$0.end > $0.start &&
|
||||
$0.end <= source.length &&
|
||||
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
|
||||
}
|
||||
}
|
||||
|
||||
private func documentMatchesExpectedTokens() -> Bool {
|
||||
let source = value as NSString
|
||||
let expectedSources = tokens.compactMap { token -> String? in
|
||||
guard token.start >= 0,
|
||||
token.end > token.start,
|
||||
token.end <= source.length,
|
||||
source.substring(
|
||||
with: NSRange(location: token.start, length: token.end - token.start)
|
||||
) == token.source else {
|
||||
return nil
|
||||
}
|
||||
return token.source
|
||||
}
|
||||
var renderedSources: [String] = []
|
||||
textView.attributedText.enumerateAttribute(
|
||||
.attachment,
|
||||
in: NSRange(location: 0, length: textView.attributedText.length)
|
||||
) { value, _, _ in
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
renderedSources.append(attachment.source)
|
||||
}
|
||||
}
|
||||
return renderedSources == expectedSources
|
||||
}
|
||||
}
|
||||
|
||||
private extension UIColor {
|
||||
convenience init?(composerHex hex: String?) {
|
||||
guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
if value.hasPrefix("#") {
|
||||
value.removeFirst()
|
||||
}
|
||||
guard value.count == 6 || value.count == 8,
|
||||
let raw = UInt64(value, radix: 16) else {
|
||||
return nil
|
||||
}
|
||||
if value.count == 8 {
|
||||
self.init(
|
||||
red: CGFloat((raw >> 24) & 0xff) / 255,
|
||||
green: CGFloat((raw >> 16) & 0xff) / 255,
|
||||
blue: CGFloat((raw >> 8) & 0xff) / 255,
|
||||
alpha: CGFloat(raw & 0xff) / 255
|
||||
)
|
||||
} else {
|
||||
self.init(
|
||||
red: CGFloat((raw >> 16) & 0xff) / 255,
|
||||
green: CGFloat((raw >> 8) & 0xff) / 255,
|
||||
blue: CGFloat(raw & 0xff) / 255,
|
||||
alpha: 1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024-25 Bluesky PBC
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,25 +0,0 @@
|
||||
require "json"
|
||||
|
||||
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
|
||||
new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
|
||||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "T3MarkdownText"
|
||||
s.version = package["version"]
|
||||
s.summary = "Native selectable markdown renderer for T3 Code mobile."
|
||||
s.description = "Fabric-backed attributed text and markdown rendering primitives owned by T3 Code."
|
||||
s.homepage = "https://t3tools.com"
|
||||
s.license = { :type => "MIT", :file => "LICENSE" }
|
||||
s.author = { "T3 Tools" => "[email protected]" }
|
||||
s.platforms = { :ios => min_ios_version_supported }
|
||||
s.source = { :path => "." }
|
||||
s.source_files = "ios/**/*.{h,m,mm,cpp}"
|
||||
|
||||
install_modules_dependencies(s)
|
||||
|
||||
if ENV["USE_FRAMEWORKS"] != nil && new_arch_enabled
|
||||
add_dependency(s, "React-FabricComponents", :additional_framework_paths => [
|
||||
"react/renderer/textlayoutmanager/platform/ios",
|
||||
])
|
||||
end
|
||||
end
|
||||
@@ -1,12 +0,0 @@
|
||||
# Upstream Attribution
|
||||
|
||||
The Fabric attributed-text component in this module originated from
|
||||
[`bluesky-social/react-native-uitextview`](https://github.com/bluesky-social/react-native-uitextview),
|
||||
version `2.2.0`, commit `addc08fea303608f070fe1eeba4bc075f181c4af`.
|
||||
|
||||
The upstream project is Copyright (c) 2024-25 Bluesky PBC and licensed under
|
||||
the MIT License included in this directory.
|
||||
|
||||
T3 Code has substantially modified and renamed the implementation, integrated
|
||||
its markdown renderer, and owns the resulting module going forward. This is not
|
||||
an upstream package dependency or a compatibility fork.
|
||||
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 870 B |
|
Before Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 534 B |
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 472 B |
|
Before Width: | Height: | Size: 620 B |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 497 B |
|
Before Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,27 +0,0 @@
|
||||
export { markdownFileIconSource } from "./src/markdownFileIcons";
|
||||
export {
|
||||
resolveMarkdownFileIcon,
|
||||
resolveMarkdownLinkPresentation,
|
||||
type MarkdownFileIcon,
|
||||
type MarkdownLinkPresentation,
|
||||
} from "./src/markdownLinks";
|
||||
export {
|
||||
nativeMarkdownChunkSpacing,
|
||||
nativeMarkdownDocumentChunks,
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
type NativeMarkdownDocumentChunk,
|
||||
type NativeMarkdownTextRun,
|
||||
} from "./src/nativeMarkdownText";
|
||||
export { MarkdownTextPrimitive } from "./src/MarkdownTextPrimitive";
|
||||
export {
|
||||
SelectableMarkdownText,
|
||||
type MarkdownCodeHighlighter,
|
||||
type MarkdownHighlightedToken,
|
||||
} from "./src/SelectableMarkdownText";
|
||||
export type {
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
SelectableMarkdownTextProps,
|
||||
} from "./src/SelectableMarkdownText.types";
|
||||
@@ -1,13 +0,0 @@
|
||||
#import <React/RCTViewComponentView.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
#ifndef T3MarkdownTextNativeComponent_h
|
||||
#define T3MarkdownTextNativeComponent_h
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
@interface T3MarkdownText : RCTViewComponentView
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* UitextviewViewNativeComponent_h */
|
||||
@@ -1,688 +0,0 @@
|
||||
#import "T3MarkdownText.h"
|
||||
#import "T3MarkdownTextShadowNode.h"
|
||||
#import "T3MarkdownTextComponentDescriptor.h"
|
||||
#import "T3MarkdownTextRun.h"
|
||||
#import <React/RCTConversions.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
|
||||
#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
|
||||
#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
|
||||
#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
|
||||
#import "RCTFabricComponentsPlugins.h"
|
||||
|
||||
using namespace facebook::react;
|
||||
|
||||
static void T3MarkdownTextApplyParagraphStyles(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
|
||||
{
|
||||
for (const auto &styleRange : styleRanges) {
|
||||
if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange markerRange = NSMakeRange(
|
||||
styleRange.location,
|
||||
MIN(styleRange.length, attributedString.length - styleRange.location));
|
||||
const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
|
||||
const NSParagraphStyle *existingStyle =
|
||||
[attributedString attribute:NSParagraphStyleAttributeName
|
||||
atIndex:paragraphRange.location
|
||||
effectiveRange:nil];
|
||||
NSMutableParagraphStyle *paragraphStyle =
|
||||
existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
|
||||
paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
|
||||
paragraphStyle.headIndent = styleRange.headIndent;
|
||||
paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
|
||||
paragraphStyle.tabStops = @[
|
||||
[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
|
||||
location:styleRange.headIndent
|
||||
options:@{}]
|
||||
];
|
||||
paragraphStyle.defaultTabInterval = styleRange.headIndent;
|
||||
[attributedString addAttribute:NSParagraphStyleAttributeName
|
||||
value:paragraphStyle
|
||||
range:paragraphRange];
|
||||
}
|
||||
}
|
||||
|
||||
static void T3MarkdownTextApplyAttachments(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges,
|
||||
NSDictionary<NSString *, UIImage *> *images)
|
||||
{
|
||||
for (const auto &attachmentRange : attachmentRanges) {
|
||||
if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
UIImage *image = images[imageUri];
|
||||
if ([imageUri hasPrefix:@"sf:"]) {
|
||||
NSString *symbolName = [imageUri substringFromIndex:3];
|
||||
UIColor *foregroundColor =
|
||||
[attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:attachmentRange.location
|
||||
effectiveRange:nil] ?: UIColor.labelColor;
|
||||
image = [[UIImage systemImageNamed:symbolName] imageWithTintColor:foregroundColor
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
}
|
||||
attachment.image = image ?: [[UIImage alloc] init];
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
NSAttributedString *attachmentString =
|
||||
[NSAttributedString attributedStringWithAttachment:attachment];
|
||||
[attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@interface T3MarkdownOutsideTapCoordinator : NSObject <UIGestureRecognizerDelegate>
|
||||
|
||||
- (instancetype)initWithWindow:(UIWindow *)window;
|
||||
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target;
|
||||
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target;
|
||||
|
||||
@end
|
||||
|
||||
static const void *T3MarkdownOutsideTapCoordinatorKey =
|
||||
&T3MarkdownOutsideTapCoordinatorKey;
|
||||
|
||||
@implementation T3MarkdownOutsideTapCoordinator {
|
||||
__weak UIWindow *_window;
|
||||
UITapGestureRecognizer *_recognizer;
|
||||
NSHashTable<id<T3MarkdownOutsideTapTarget>> *_targets;
|
||||
}
|
||||
|
||||
- (instancetype)initWithWindow:(UIWindow *)window
|
||||
{
|
||||
if (self = [super init]) {
|
||||
_window = window;
|
||||
_targets = [NSHashTable weakObjectsHashTable];
|
||||
_recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
|
||||
action:@selector(handleTap:)];
|
||||
_recognizer.cancelsTouchesInView = NO;
|
||||
_recognizer.delegate = self;
|
||||
[window addGestureRecognizer:_recognizer];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target
|
||||
{
|
||||
[_targets addObject:target];
|
||||
}
|
||||
|
||||
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target
|
||||
{
|
||||
[_targets removeObject:target];
|
||||
if (_targets.count > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
UIWindow *window = _window;
|
||||
[window removeGestureRecognizer:_recognizer];
|
||||
if (objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey) == self) {
|
||||
objc_setAssociatedObject(
|
||||
window,
|
||||
T3MarkdownOutsideTapCoordinatorKey,
|
||||
nil,
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)handleTap:(UITapGestureRecognizer *)sender
|
||||
{
|
||||
UIWindow *window = _window;
|
||||
if (window == nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
UIView *hitView = [window hitTest:[sender locationInView:window] withEvent:nil];
|
||||
if (hitView == nil) {
|
||||
return;
|
||||
}
|
||||
for (id<T3MarkdownOutsideTapTarget> target in _targets.allObjects) {
|
||||
[target clearSelectionForOutsideTapWithHitView:hitView];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
|
||||
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static T3MarkdownOutsideTapCoordinator *
|
||||
T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
{
|
||||
T3MarkdownOutsideTapCoordinator *coordinator =
|
||||
objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey);
|
||||
if (coordinator == nil) {
|
||||
coordinator = [[T3MarkdownOutsideTapCoordinator alloc] initWithWindow:window];
|
||||
objc_setAssociatedObject(
|
||||
window,
|
||||
T3MarkdownOutsideTapCoordinatorKey,
|
||||
coordinator,
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return coordinator;
|
||||
}
|
||||
|
||||
@interface T3MarkdownText () <RCTT3MarkdownTextViewProtocol, UIGestureRecognizerDelegate, UITextViewDelegate>
|
||||
|
||||
@end
|
||||
|
||||
@interface T3MarkdownText () <T3MarkdownOutsideTapTarget>
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownText {
|
||||
UIView * _view;
|
||||
T3MarkdownTextBackingView * _textView;
|
||||
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
|
||||
__weak UIWindow * _outsideTapWindow;
|
||||
BOOL _suppressSelectionChange;
|
||||
NSMutableDictionary<NSString *, UIImage *> * _attachmentImages;
|
||||
NSMutableSet<NSString *> * _pendingAttachmentUris;
|
||||
}
|
||||
|
||||
+ (ComponentDescriptorProvider)componentDescriptorProvider
|
||||
{
|
||||
return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
|
||||
}
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
|
||||
_props = defaultProps;
|
||||
|
||||
_view = [[UIView alloc] init];
|
||||
self.contentView = _view;
|
||||
self.clipsToBounds = true;
|
||||
|
||||
_textView = [[T3MarkdownTextBackingView alloc] init];
|
||||
_attachmentImages = [[NSMutableDictionary alloc] init];
|
||||
_pendingAttachmentUris = [[NSMutableSet alloc] init];
|
||||
_textView.scrollEnabled = false;
|
||||
_textView.editable = false;
|
||||
_textView.textContainerInset = UIEdgeInsetsZero;
|
||||
_textView.textContainer.lineFragmentPadding = 0;
|
||||
_textView.delegate = self;
|
||||
// Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
|
||||
_textView.layoutManager.usesFontLeading = NO;
|
||||
[self addSubview:_textView];
|
||||
|
||||
const auto longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
|
||||
action:@selector(handleLongPressIfNecessary:)];
|
||||
longPressGestureRecognizer.delegate = self;
|
||||
|
||||
const auto pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
|
||||
action:@selector(handlePressIfNecessary:)];
|
||||
pressGestureRecognizer.delegate = self;
|
||||
[pressGestureRecognizer requireGestureRecognizerToFail:longPressGestureRecognizer];
|
||||
|
||||
[_textView addGestureRecognizer:pressGestureRecognizer];
|
||||
[_textView addGestureRecognizer:longPressGestureRecognizer];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)didMoveToWindow
|
||||
{
|
||||
[super didMoveToWindow];
|
||||
if (_outsideTapWindow == self.window) {
|
||||
return;
|
||||
}
|
||||
if (_outsideTapWindow != nil) {
|
||||
T3MarkdownOutsideTapCoordinator *coordinator =
|
||||
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
|
||||
[coordinator removeTarget:self];
|
||||
}
|
||||
_outsideTapWindow = self.window;
|
||||
if (_outsideTapWindow != nil) {
|
||||
[T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
T3MarkdownOutsideTapCoordinator *coordinator =
|
||||
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
|
||||
[coordinator removeTarget:self];
|
||||
}
|
||||
|
||||
// See RCTParagraphComponentView
|
||||
- (void)prepareForRecycle
|
||||
{
|
||||
[super prepareForRecycle];
|
||||
T3MarkdownOutsideTapCoordinator *coordinator =
|
||||
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
|
||||
[coordinator removeTarget:self];
|
||||
_outsideTapWindow = nil;
|
||||
_state.reset();
|
||||
|
||||
// Reset the frame to zero so that when it properly lays out on the next use
|
||||
_textView.frame = CGRectZero;
|
||||
_textView.attributedText = nil;
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
// _textView's frame is assigned inside drawRect, which only fires when
|
||||
// state changes. Trigger a redraw whenever the host frame moves out from
|
||||
// under it (rotation, parent relayout) so the text view resizes and
|
||||
// onTextLayout re-fires with the new line wrapping.
|
||||
if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
|
||||
[self setNeedsDisplay];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
if (!_state) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
|
||||
|
||||
const auto attrString = _state->getData().attributedString;
|
||||
NSMutableAttributedString *convertedAttrString =
|
||||
[RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
|
||||
T3MarkdownTextApplyParagraphStyles(
|
||||
convertedAttrString,
|
||||
_state->getData().paragraphStyleRanges);
|
||||
T3MarkdownTextApplyAttachments(
|
||||
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
|
||||
// the frame triggers a layout flush that has the same effect. Bail out
|
||||
// entirely when nothing actually changed so a JS-side state update made in
|
||||
// response to onSelectionChange doesn't deselect what the user is selecting.
|
||||
const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
|
||||
const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
|
||||
if (!textChanged && !frameChanged) {
|
||||
return;
|
||||
}
|
||||
if (textChanged) {
|
||||
// Reassigning attributedText clears any active selection. Save it and
|
||||
// restore after, while suppressing the synthetic textViewDidChangeSelection
|
||||
// events the clear-then-restore would otherwise produce — those would
|
||||
// round-trip to JS and re-trigger this same path, causing a loop.
|
||||
const NSRange savedRange = _textView.selectedRange;
|
||||
_suppressSelectionChange = YES;
|
||||
_textView.attributedText = convertedAttrString;
|
||||
if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
|
||||
_textView.selectedRange = savedRange;
|
||||
}
|
||||
_suppressSelectionChange = NO;
|
||||
}
|
||||
if (frameChanged) {
|
||||
_textView.frame = _view.frame;
|
||||
}
|
||||
|
||||
__block std::vector<std::string> lines;
|
||||
const int maxLines = props.numberOfLines;
|
||||
[_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
|
||||
CGRect usedRect,
|
||||
NSTextContainer * _Nonnull textContainer,
|
||||
NSRange glyphRange,
|
||||
BOOL * _Nonnull stop) {
|
||||
const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
|
||||
const auto line = [self->_textView.text substringWithRange:charRange];
|
||||
lines.push_back(line.UTF8String);
|
||||
// enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
|
||||
// 18, so cap explicitly.
|
||||
if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
|
||||
*stop = YES;
|
||||
}
|
||||
}];
|
||||
|
||||
if (_eventEmitter != nullptr) {
|
||||
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
|
||||
->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
|
||||
};
|
||||
}
|
||||
|
||||
- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
|
||||
{
|
||||
for (const auto &attachmentRange : attachmentRanges) {
|
||||
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
|
||||
if ([imageUri hasPrefix:@"sf:"]) {
|
||||
continue;
|
||||
}
|
||||
if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSURL *url = [NSURL URLWithString:imageUri];
|
||||
if (url == nil) {
|
||||
continue;
|
||||
}
|
||||
if (url.isFileURL) {
|
||||
UIImage *image = [UIImage imageWithContentsOfFile:url.path];
|
||||
if (image != nil) {
|
||||
_attachmentImages[imageUri] = image;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self refreshDisplayedAttachments];
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
[_pendingAttachmentUris addObject:imageUri];
|
||||
[[[NSURLSession sharedSession] dataTaskWithURL:url
|
||||
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
|
||||
UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self->_pendingAttachmentUris removeObject:imageUri];
|
||||
if (image != nil) {
|
||||
self->_attachmentImages[imageUri] = image;
|
||||
[self refreshDisplayedAttachments];
|
||||
}
|
||||
});
|
||||
}] resume];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)refreshDisplayedAttachments
|
||||
{
|
||||
if (!_state || _textView.attributedText == nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
|
||||
T3MarkdownTextApplyAttachments(
|
||||
attributedText,
|
||||
_state->getData().attachmentRanges,
|
||||
_attachmentImages);
|
||||
|
||||
const NSRange savedRange = _textView.selectedRange;
|
||||
_suppressSelectionChange = YES;
|
||||
_textView.attributedText = attributedText;
|
||||
if (savedRange.location != NSNotFound &&
|
||||
NSMaxRange(savedRange) <= _textView.attributedText.length) {
|
||||
_textView.selectedRange = savedRange;
|
||||
}
|
||||
_suppressSelectionChange = NO;
|
||||
[_textView setNeedsDisplay];
|
||||
}
|
||||
|
||||
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
|
||||
{
|
||||
const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
|
||||
const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
|
||||
|
||||
if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
|
||||
_textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
|
||||
}
|
||||
|
||||
if (oldViewProps.selectable != newViewProps.selectable) {
|
||||
_textView.selectable = newViewProps.selectable;
|
||||
}
|
||||
|
||||
if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
|
||||
if (@available(iOS 11.0, *)) {
|
||||
_textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
|
||||
}
|
||||
}
|
||||
|
||||
if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
|
||||
if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
|
||||
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
|
||||
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
|
||||
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
|
||||
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
|
||||
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
|
||||
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
|
||||
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
|
||||
// is in will have this background color applied. To apply it just to a particular part of a string, you'd need
|
||||
// to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
|
||||
// This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
|
||||
if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
|
||||
_textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
|
||||
}
|
||||
|
||||
[super updateProps:props oldProps:oldProps];
|
||||
}
|
||||
|
||||
// See RCTParagraphComponentView
|
||||
- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
|
||||
{
|
||||
_state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
|
||||
[self setNeedsDisplay];
|
||||
}
|
||||
|
||||
// MARK: - UIGestureRecognizerDelegate
|
||||
|
||||
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
|
||||
{
|
||||
if ([hitView isDescendantOfView:self]) {
|
||||
return;
|
||||
}
|
||||
// Defer past the current event loop turn so any in-flight edit-menu action
|
||||
// (Copy / Define / Look Up / …) reads the live selection before we clear it.
|
||||
UITextView *textView = _textView;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
UITextRange *range = textView.selectedTextRange;
|
||||
if (range != nil && !range.isEmpty) {
|
||||
textView.selectedTextRange = nil;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// MARK: - Touch handling
|
||||
|
||||
- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
|
||||
{
|
||||
return [sender locationInView:_textView];
|
||||
}
|
||||
|
||||
- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
|
||||
{
|
||||
const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
|
||||
inTextContainer:_textView.textContainer
|
||||
fractionOfDistanceBetweenInsertionPoints:nil
|
||||
];
|
||||
|
||||
int currIndex = -1;
|
||||
for (UIView* child in self.subviews) {
|
||||
if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
|
||||
|
||||
// This is UTF16 code units!!
|
||||
currIndex += textChild.text.length;
|
||||
|
||||
if (charIndex <= currIndex) {
|
||||
return textChild;
|
||||
}
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
|
||||
{
|
||||
const auto location = [self getLocationOfPress:sender];
|
||||
const auto child = [self getTouchChild:location];
|
||||
|
||||
if (child) {
|
||||
[child onPress];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
|
||||
{
|
||||
const auto location = [self getLocationOfPress:sender];
|
||||
const auto child = [self getTouchChild:location];
|
||||
|
||||
if (child) {
|
||||
[child onLongPress];
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - UITextViewDelegate
|
||||
|
||||
- (void)textViewDidChangeSelection:(UITextView *)textView
|
||||
{
|
||||
if (_suppressSelectionChange) {
|
||||
return;
|
||||
}
|
||||
if (_eventEmitter == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const NSRange selectedRange = textView.selectedRange;
|
||||
if (selectedRange.location == NSNotFound) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fires on programmatic selection changes too (e.g. the outside-tap clear
|
||||
// in handleOutsideTap:), so JS will see a synthetic empty-range event then.
|
||||
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
|
||||
->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
|
||||
static_cast<int>(self.tag),
|
||||
static_cast<int>(selectedRange.location),
|
||||
static_cast<int>(selectedRange.location + selectedRange.length),
|
||||
});
|
||||
}
|
||||
|
||||
Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
|
||||
{
|
||||
return T3MarkdownText.class;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "T3MarkdownTextShadowNode.h"
|
||||
|
||||
#include <react/renderer/core/ConcreteComponentDescriptor.h>
|
||||
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
|
||||
|
||||
namespace facebook::react {
|
||||
using T3MarkdownTextComponentDescriptor = ConcreteComponentDescriptor<T3MarkdownTextShadowNode>;
|
||||
|
||||
void T3MarkdownTextSpec_registerComponentDescriptorsFromCodegen(
|
||||
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
#import <React/RCTViewManager.h>
|
||||
#import <React/RCTUIManager.h>
|
||||
#import "RCTBridge.h"
|
||||
#import "Utils.h"
|
||||
|
||||
@interface T3MarkdownTextManager : RCTViewManager
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownTextManager
|
||||
|
||||
RCT_EXPORT_MODULE(T3MarkdownText)
|
||||
|
||||
- (UIView *)view
|
||||
{
|
||||
return [[UIView alloc] init];
|
||||
}
|
||||
|
||||
RCT_CUSTOM_VIEW_PROPERTY(color, NSString, UIView)
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface T3MarkdownTextRunManager : RCTViewManager
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownTextRunManager
|
||||
|
||||
RCT_EXPORT_MODULE(T3MarkdownTextRun)
|
||||
|
||||
- (UIView *)view
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||