Compare commits

..
Author SHA1 Message Date
Theo Browne 120eab2e47 fix: avoid repeat mobile view commands 2026-08-14 21:12:06 -07:00
Theo Browne 5d1f1723bd fix: preserve thread view boundaries across clients 2026-08-14 21:05:10 -07:00
Theo Browne 222a8c1981 feat: sync thread unread state across clients 2026-08-14 20:53:12 -07:00
8c628f1499 fix(web): align pull request action menu rows (#6534)
Co-authored-by: Nickolas Kyryliuk <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-14 22:48:54 -04:00
Theo BrowneandClaude Fable 5 48ddb3d469 feat(web): older chat timestamps show the date, not just the time (#6654)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 22:48:08 -04:00
maria 804cba4305 revert: refresh workspace layouts and tool activity (#6657) 2026-08-15 02:00:02 +00:00
maria d7abd7f3bb feat(web): refresh workspace layouts and tool activity 2026-08-14 21:54:04 -04:00
Theo BrowneandClaude Fable 5 57a299a785 feat(web): open remote environments in your local editor over SSH (#6572)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 17:35:34 -07:00
SimoneandSimone 74f7b43486 fix(web): bound OKLCH gamut mapping (#6485)
Co-authored-by: Simone <[email protected]>
2026-08-14 19:32:33 -04:00
maria e25021af76 feat(packaging): maintain AUR packages in-repo (#4128) 2026-08-15 00:32:12 +02:00
SimoneandSimone f0719072a1 fix(server): handle files named HEAD in git status (#6397)
Co-authored-by: Simone <[email protected]>
2026-08-14 17:56:12 -04:00
9885a845c9 refactor(web): simplify global styling (#6381)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-14 23:30:13 +02:00
t3-code[bot]andUtkarsh Patil 196c8ea0d6 fix(web): style sidebar action tooltips (#6371)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-14 19:43:33 +00:00
Wout Stiens c9063f03ea perf(desktop): speed up Windows update installation (#6169) 2026-08-15 00:42:39 +05:30
Utkarsh Patil 1add47b322 fix(web): add copying terminal selection with ctrl+c in the web app (#5638) 2026-08-14 23:22:57 +05:30
Dara Adedeji 80991402dc fix(server): terminal subprocess polling no longer floods the PID space (#6377) 2026-08-14 23:02:25 +05:30
Wout Stiens 1a6599437b fix(web): clarify desktop update status (#6504) 2026-08-14 17:58:49 +02:00
Chris Deeming 184d8ef33b fix(mobile): steer active turns by default (#6543) 2026-08-14 13:35:10 +02:00
Julius MarmingeandClaude Fable 5 038560e580 fix(web): align every titlebar control cluster on one shared inset (#6592)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 11:22:05 +02:00
Julius MarmingeandClaude Fable 5 21a3669cee fix(mobile): prevent OTA update restart crashes (#6324)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:46:33 +02:00
Julius MarmingeandClaude Fable 5 b3b4b57794 fix(mobile): preserve keyboard suggestions while typing (#6323)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:45:43 +02:00
6ae44b418a refactor(mobile): name the iOS nav bar height fallback (#6589)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-14 08:29:09 +00:00
Michael Charles Aubrey 4a2f8b04bb fix(web): keep thread rename open during IME composition (#6281) 2026-08-14 08:27:29 +00:00
Pavlo TrinkoandClaude Fable 5 8f9ab0845d fix(mobile): add breathing room between the git progress overlay and the app bar (#6587)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:25:05 +02:00
Julius MarmingeandClaude Fable 5 baaeda305c fix: avoid stale Live Activities when publishing is disabled (#6325)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:00:25 +02:00
7e01d33f0e perf(build): stop unpacking node_modules wholesale from the Windows asar (#5877)
Co-authored-by: tsouth89 <[email protected]>
Co-authored-by: t3-code[bot] <t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Shivam Sharma <[email protected]>
2026-08-14 08:37:57 +05:30
Chris Deeming 9fd788b5a9 fix(preview): only show browser-ready local servers (#6021) 2026-08-13 22:10:41 -04:00
Chris Deeming 710fd0eeb3 feat(desktop): add favicons to the Browser panel (#5644) 2026-08-13 22:02:09 -04:00
David Hu e15f655ba4 fix(web): show background policy tooltips sooner (#6506) 2026-08-13 22:01:11 -04:00
Theo BrowneandClaude Fable 5 59be6f7846 fix(web): simplify the desktop-managed server update banner copy (#6549)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-13 21:45:51 -04:00
273 changed files with 14680 additions and 4616 deletions

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
name: Publish AUR package
# See packaging/aur/README.md.
on:
workflow_call:
inputs:
release_tag:
required: true
type: string
pkgrel:
required: false
default: "1"
type: string
secrets:
AUR_SSH_PRIVATE_KEY:
required: true
workflow_dispatch:
inputs:
release_tag:
description: "Release tag to publish"
required: true
type: string
pkgrel:
description: "Arch package release override"
required: false
default: "1"
type: string
permissions:
contents: read
concurrency:
group: publish-aur
cancel-in-progress: false
jobs:
publish:
name: Validate and publish
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 30
container:
image: archlinux:base-devel
steps:
- name: Install Arch packaging tools
run: pacman -Syu --noconfirm --needed git github-cli jq namcap openssh sudo
- name: Checkout packaging sources
uses: actions/checkout@v6
- name: Create unprivileged build user
run: |
useradd --create-home builder
install -Dm0440 /dev/stdin /etc/sudoers.d/builder <<'EOF'
builder ALL=(root) NOPASSWD: /usr/bin/pacman
EOF
- name: Validate and publish package sources
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.release_tag }}
PKGREL: ${{ inputs.pkgrel || '1' }}
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: packaging/aur/scripts/release.sh
+10
View File
@@ -856,6 +856,16 @@ jobs:
fail_on_unmatched_files: true
token: ${{ github.token }}
publish_aur:
name: Publish AUR package
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
uses: ./.github/workflows/publish-aur.yml
with:
release_tag: ${{ needs.preflight.outputs.tag }}
secrets:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
deploy_web:
name: Deploy hosted web app
needs: [preflight, relay_public_config, release]
@@ -0,0 +1,82 @@
---
title: UI Consistency
model: claude-opus-5
effort: high
input: full_diff
tools:
- browse_code
- git_tools
- github_api_read_only
- modify_pr
include:
- "apps/web/src/**/*.ts"
- "apps/web/src/**/*.tsx"
- "apps/web/src/**/*.css"
conclusion: failure
showToolCalls: true
---
# UI consistency review
Review changed web UI code and directly affected call sites for consistency with the shared component system, Tailwind ownership, and the behavioral constraints below. Apply these rules when a pull request creates, moves, or modifies controls or styling. Do not demand unrelated repository-wide cleanup.
The goal is not to minimize CSS or class counts at any cost. The goal is to put each behavior in the smallest correct owner while preserving interaction, theming, accessibility, layout, and browser behavior.
## Shared controls and variants
- Prefer the core UI primitives in `apps/web/src/components/ui` over native controls or locally reconstructed primitives. In ordinary product UI, a raw `<button>` that recreates `Button`, a raw input that recreates `Input` or `InputGroup`, or a local trigger that recreates `Select`, `Toggle`, or `Menu` is a concrete finding.
- Do not flag raw elements that intentionally implement a semantic row, tab, resize handle, swatch, image target, editor surface, or another interaction whose behavior or geometry differs from the core primitive.
- When multiple call sites repeat the same durable geometry or treatment, prefer a named primitive size or variant. Examples include compact controls, micro icon actions, muted ghost actions, and glass actions. Keep contextual layout, width, and color at the call site.
- Flag large call-site class strings that override a primitive's core height, radius, padding, focus ring, cursor, hit target, or base state colors. Prefer extending the primitive contract when the same pattern is genuinely shared.
- Preserve accessibility and interaction semantics during migrations: focus-visible rings, disabled behavior, loading state, keyboard behavior, pointer cursor, `aria-*`, Base UI or Radix render/close props, and coarse-pointer hit targets.
- Do not require tests for a tiny visual-only class migration. Require focused tests when primitive composition changes behavior, prop forwarding, state transitions, keyboard handling, or width/defaulting logic.
## CSS and Tailwind ownership
- Ordinary one-owner presentation belongs in the owning TS or TSX module as static Tailwind classes or owner-level CSS variables. Examples include local geometry, spacing, typography, backgrounds, borders, simple vendor pseudo-elements, and component-only positioning.
- Keep global CSS when it is genuinely reusable or behaviorally complex: generated markdown or imperative DOM, custom elements and shadow roots, masks, shared or complex pseudo-elements, animations, glass composition, runtime theme variables, safe-area calculations, scrollbar-lane preservation, Electron drag regions, and browser/vendor integration. Simple owner-local pseudo-elements may still belong in the owning module.
- Before calling a selector dead, trace literal, dynamic, generated, imperative, test, custom-element, and shadow-root consumers. Search both the emitted class string and any class-valued field names through their final DOM sink. A helper returning a class is not proof that it is rendered, and a missed downstream property read can make a deletion unsafe.
- Flag duplicate declarations only after comparing cascade layer, selector specificity, inheritance, runtime theme scope, media/variant scope, and the final owning element. Textually identical declarations are not necessarily behaviorally redundant.
- When moving CSS into Tailwind, preserve selector scope and cascade ownership. A utility at the owner is preferable to a fragile global override that depends on stylesheet order.
- Do not request moving complex global behavior into arbitrary Tailwind merely to reduce `index.css`. Do not preserve ordinary one-owner CSS merely because it already exists globally.
## Themes and generated CSS
- Use the project variants for theme-only declarations:
- dark-only declarations use `@variant dark`;
- light-only declarations use `@variant light`;
- raw `.dark` should remain only in the `dark` and `light` custom-variant definitions.
- Preserve custom themes and runtime token bridges. Removing a variable or selector is safe only when all runtime, inspector, generated, and theme-palette consumers are accounted for.
- Inspect emitted production CSS after unusual variants, arbitrary selectors, nested pseudo-elements, or attribute matching. Source syntax that looks valid is insufficient.
- Flag malformed or empty emitted selectors such as empty `:is()` or `:not(:is())`, selector branches that can never match their own class attribute, and transformations that silently drop the intended rule.
- Prefer source-level logic over clever selectors when behavior depends on consumer-provided class strings. Preserve `MenuPopup`'s current defaulting contract: a string `className` containing a `w-*`, `min-w-*`, or `max-w-*` utility after variant prefixes are stripped suppresses `min-w-32`; a string without one and a functional/non-string `className` keep the default. Arbitrary width values count as width utilities, and the consumer class must be merged last so it retains control. Do not replace this with a raw class-attribute substring selector.
- Do not fail solely because a valid emitted selector is verbose or because a source rule uses an intentional custom property.
## Scroll and virtualized lists
- `ScrollArea` owns and masks its Base UI viewport. A virtualized list usually owns a native scrolling element and cannot automatically reuse viewport-specific `ScrollArea` behavior.
- Repeated native or virtualized overflow fades should use the shared virtualized-scroll-fade contract rather than component-named mask selectors.
- Preserve runtime top and bottom overflow state. Do not replace dynamic fades with an always-on static mask.
- Preserve fade geometry and keep the native scrollbar lane opaque so the track and thumb stay visible and usable. A visually similar mask that fades the scrollbar is a regression.
- Verify actual scroll behavior when changing virtualizers, masks, overflow ownership, or scrollbar selectors. Source-level class comparison is not enough.
## Visual and layout preservation
- Preserve responsive geometry, titlebar insets, panel and inline-preview modes, desktop Electron layout, light and dark contrast, clipping, radius, and composable shadows.
- For meaningful visual changes, prefer available real-app evidence using the actual component and state. A mock recreation does not validate the real component. Light and dark evidence is useful when theme-sensitive styles change, but missing or inaccessible evidence alone is not a finding; report only a concrete regression supported by the diff, code, or available artifacts.
- Do not treat a screenshot as proof of keyboard, overflow, scrollbar, responsive, or runtime-theme behavior. Pair visual evidence with source, computed-style, emitted-CSS, or interaction checks as appropriate.
- Be alert to shared primitive color indirection. When a primitive routes icon color through a CSS variable, ensure migrated contextual icons retain their intended tone, including pressed and disabled states.
## Change discipline
- Review the pull request's changed scope and directly affected consumers. Do not turn a focused PR into a demand for unrelated legacy cleanup.
- Prefer the smallest durable contract over a component-specific workaround or a broad abstraction with one consumer.
- Preserve intentional exceptions and comments that explain browser, virtualizer, theme, or Electron constraints.
- If a proposed cleanup cannot prove ownership or semantic equivalence, ask for evidence or leave it unchanged rather than guessing.
- Select verification gates according to the changed behavior: typecheck or focused tests for typing and interaction contracts, production build and emitted-CSS inspection for Tailwind or selector transformations, and real-app evidence for meaningful visual behavior when available. These gates are complementary when applicable, but do not require every gate for tiny visual-only migrations or fail solely because an artifact the configured tools cannot produce is absent.
## Reporting
Report only concrete violations introduced by changed lines or behavior, plus pre-existing behavior that the patch directly makes relevant or worsens. Touching a large file does not make unrelated retained issues reportable. Prefer precise inline comments on the smallest relevant line range. Explain the broken behavior or ownership rule, not merely the preferred syntax, and state the smallest expected fix. A clear consistency or regression risk may fail the check. Do not fail for optional aesthetic preferences, harmless class ordering, or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
+10
View File
@@ -51,10 +51,20 @@ brew install --cask t3-code
#### Arch Linux (AUR)
Stable:
```bash
yay -S t3code-bin
```
Nightly:
```bash
yay -S t3code-nightly-bin
```
The AUR packaging is maintained in this repository under [`packaging/aur`](./packaging/aur).
## Some notes
We are very very early in this project. Expect bugs.
@@ -65,6 +65,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.serverRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
assert.equal(environment.backendCwd, "/repo");
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
@@ -98,6 +99,24 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("uses the packaged Windows server sidecar as the backend root", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment({
platform: "win32",
isPackaged: true,
appPath: "/install/resources/app.asar",
resourcesPath: "/install/resources",
});
assert.equal(environment.appRoot, "/install/resources/app.asar");
assert.equal(environment.serverRoot, "/install/resources/server.asar");
assert.equal(
environment.backendEntryPath,
"/install/resources/server.asar/apps/server/dist/bin.mjs",
);
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
+13 -1
View File
@@ -52,6 +52,13 @@ export class DesktopEnvironment extends Context.Service<
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
// Root of the tree containing apps/server/dist and node_modules for the
// backend. Equals appRoot everywhere except packaged Windows, where the
// server tree ships as the resources/server.asar sidecar (see
// scripts/build-desktop-artifact.ts) that the asar-aware
// ELECTRON_RUN_AS_NODE primary reads in place and the WSL backend
// extracts on demand (see DesktopWslServerTree).
readonly serverRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
@@ -157,6 +164,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
});
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const serverRoot =
input.isPackaged && input.platform === "win32"
? path.join(input.resourcesPath, "server.asar")
: appRoot;
const branding = resolveDesktopAppBranding({
isDevelopment,
appVersion: input.appVersion,
@@ -198,7 +209,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
serverRoot,
backendEntryPath: path.join(serverRoot, "apps/server/dist/bin.mjs"),
backendCwd: input.isPackaged ? homeDirectory : appRoot,
preloadPath: path.join(input.dirname, "preload.cjs"),
appUpdateYmlPath: input.isPackaged
@@ -17,6 +17,7 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
observability: Schema.Struct({
@@ -115,6 +116,7 @@ const withHarness = <A, E, R>(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
),
),
@@ -153,6 +155,47 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const resourcesPath = `${baseDir}/resources`;
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
Layer.succeed(
DesktopWslServerTree.DesktopWslServerTree,
DesktopWslServerTree.DesktopWslServerTree.of({
ensure: Effect.die("Windows primary must not extract the WSL server tree"),
}),
),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: `${resourcesPath}/app.asar`,
platform: "win32",
resourcesPath,
}),
),
),
),
);
assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);
assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
withHarness(
Effect.gen(function* () {
@@ -173,7 +216,7 @@ describe("DesktopBackendConfiguration", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
@@ -186,6 +229,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -234,7 +278,7 @@ describe("DesktopBackendConfiguration", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
@@ -250,6 +294,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -386,6 +431,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
@@ -427,6 +473,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -486,6 +533,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -536,6 +584,7 @@ describe("DesktopBackendConfiguration", () => {
wslOnly: true,
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -573,6 +622,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Removed-Distro",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -606,6 +656,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -640,6 +691,49 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isFalse(failure.fatal);
assert.equal(failure.retryLimit, 12);
assert.include(failure.reason, "could not be extracted");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslServerTree.layerTest({
result: {
ok: false,
reason: "WSL server files could not be extracted",
fatal: false,
},
}),
),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -672,6 +766,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -708,6 +803,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -748,6 +844,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -793,6 +890,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -843,6 +941,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -864,6 +963,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layer),
// isAvailable on win32 only touches the filesystem, never the spawner,
// so a die-stub is enough to satisfy the layer's deps.
@@ -19,6 +19,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
@@ -424,10 +425,12 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
never,
| DesktopEnvironment.DesktopEnvironment
| DesktopWslEnvironment.DesktopWslEnvironment
| DesktopWslServerTree.DesktopWslServerTree
| FileSystem.FileSystem
> {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
@@ -464,31 +467,31 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
...buildObservabilityFragment(input.observabilitySettings),
};
// In packaged builds environment.appRoot is .../resources/app.asar — an
// archive FILE. The Windows primary reads its entry through
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
// already a real directory, so this is a no-op.
const wslAppRoot = environment.isPackaged
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
: environment.appRoot;
// In packaged builds the server tree ships inside resources/server.asar —
// an archive FILE the Windows primary reads through ELECTRON_RUN_AS_NODE
// (asar-aware). The WSL backend launches plain `wsl.exe -- node`, which
// can't read an asar, so materialize (or reuse) the extracted copy of the
// sidecar before preflighting. In dev the server tree is the real checkout
// directory and ensure returns it unchanged.
const serverTree = yield* wslServerTree.ensure;
const wslAppRoot = serverTree.ok ? serverTree.root : environment.serverRoot;
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
const preflight = yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
});
const preflight = serverTree.ok
? yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
})
: ({ _tag: "Failed", reason: serverTree.reason, fatal: serverTree.fatal } as const);
// Every operation after preflight uses the same concrete distro. In
// default-tracking mode this closes the race where the system default
@@ -610,6 +613,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const crypto = yield* Crypto.Crypto;
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
@@ -665,6 +669,7 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
});
@@ -727,6 +732,7 @@ export const make = Effect.gen(function* () {
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
}).pipe(
+11 -1
View File
@@ -1,3 +1,4 @@
import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -5,7 +6,16 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
// must reach the OS handler; every other non-web scheme stays blocked.
const SAFE_EXTERNAL_PROTOCOLS = new Set([
"http:",
"https:",
...REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
const scheme = remoteSchemeForEditor(id);
return scheme === undefined ? [] : [`${scheme}:`];
}),
]);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
@@ -36,6 +36,7 @@ import {
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
probeRemoteEditors,
pickFolder,
pickThemeFiles,
setTheme,
@@ -83,6 +84,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(probeRemoteEditors);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
+1
View File
@@ -3,6 +3,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
+28
View File
@@ -3,12 +3,16 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
EDITORS,
EditorId,
PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
REMOTE_CAPABLE_EDITOR_IDS,
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
import { isCommandAvailable } from "@t3tools/shared/shell";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -261,6 +265,30 @@ export const openExternal = DesktopIpc.makeIpcMethod({
}),
});
export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
payload: Schema.Undefined,
result: Schema.Array(EditorId),
// Probes THIS machine (where the renderer runs) for remote-capable editor
// CLIs, unlike the server's probe which walks the environment host's PATH.
// A Finder-launched app can miss PATH entries; an empty result makes the
// renderer fall back to VS Code only, so that fails soft.
handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
const available: Array<EditorId> = [];
for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
const commands = EDITORS.find((editor) => editor.id === editorId)?.commands;
if (!commands) continue;
for (const command of commands) {
if (yield* isCommandAvailable(command, { env: process.env })) {
available.push(editorId);
break;
}
}
}
return available;
}),
});
/** Theme files are a few KB; anything larger returns empty text and lets the
* renderer reject it by size without the contents ever crossing the bridge. */
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
+2
View File
@@ -62,6 +62,7 @@ import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "./wsl/DesktopWslServerTree.ts";
const desktopEnvironmentLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -165,6 +166,7 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(DesktopWslServerTree.layer),
Layer.provideMerge(DesktopTelemetryPublisher.layer),
Layer.provideMerge(desktopWindowLayer),
);
+1
View File
@@ -105,6 +105,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
@@ -0,0 +1,999 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
MAX_FAVICON_CANDIDATES,
MAX_FAVICON_RESPONSE_BYTES,
captureFavicon,
selectFaviconCandidates,
} from "./FaviconCapture.ts";
const PNG = "data:image/png;base64,cG5n";
const SOURCE_PNG = Buffer.alloc(24);
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
SOURCE_PNG.writeUInt32BE(1, 16);
SOURCE_PNG.writeUInt32BE(1, 20);
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
function sourceGif(
width: number,
height: number,
frameWidth = width,
frameHeight = height,
additionalFrames: ReadonlyArray<{
readonly left?: number;
readonly top?: number;
readonly width: number;
readonly height: number;
}> = [],
): Buffer {
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
buffer.write("GIF89a", 0, "ascii");
buffer.writeUInt16LE(width, 6);
buffer.writeUInt16LE(height, 8);
let offset = 13;
for (const frame of frames) {
buffer[offset] = 0x2c;
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
buffer.writeUInt16LE(frame.width, offset + 5);
buffer.writeUInt16LE(frame.height, offset + 7);
offset += 10;
buffer[offset] = 2;
buffer[offset + 1] = 0;
offset += 2;
}
buffer[offset] = 0x3b;
return buffer;
}
function sourceJpeg(
width: number,
height: number,
orientations: number | ReadonlyArray<number> = [],
): Buffer {
const frame = Buffer.from([
0xff,
0xd8,
0xff,
0xc0,
0x00,
0x07,
0x08,
height >>> 8,
height & 0xff,
width >>> 8,
width & 0xff,
]);
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
(orientation) => sourceJpegExifSegment([orientation]),
);
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
}
function sourceJpegApp1Segment(payload: Buffer): Buffer {
const app1 = Buffer.alloc(4 + payload.byteLength);
app1[0] = 0xff;
app1[1] = 0xe1;
app1.writeUInt16BE(payload.byteLength + 2, 2);
payload.copy(app1, 4);
return app1;
}
function sourceJpegExifSegment(
orientations: ReadonlyArray<number>,
options?: {
readonly byteOrder?: "II" | "MM";
readonly magic?: number;
readonly padding?: number;
},
): Buffer {
const exif = Buffer.alloc(20 + orientations.length * 12);
exif.write("Exif\0\0", 0, "binary");
exif[5] = options?.padding ?? 0;
const littleEndian = options?.byteOrder !== "MM";
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
const writeUInt16 = (value: number, offset: number) =>
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
const writeUInt32 = (value: number, offset: number) =>
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
writeUInt16(options?.magic ?? 42, 8);
writeUInt32(8, 10);
writeUInt16(orientations.length, 14);
orientations.forEach((orientation, index) => {
const entryOffset = 16 + index * 12;
writeUInt16(0x0112, entryOffset);
writeUInt16(3, entryOffset + 2);
writeUInt32(1, entryOffset + 4);
writeUInt16(orientation, entryOffset + 8);
});
return sourceJpegApp1Segment(exif);
}
function sourceJpegWithApp1Segments(
width: number,
height: number,
segments: ReadonlyArray<Buffer>,
): Buffer {
const frame = sourceJpeg(width, height);
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
}
function sourceJpegWithOrientationEntries(
width: number,
height: number,
orientations: ReadonlyArray<number>,
): Buffer {
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
}
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
const exif = sourceJpegExifSegment([6], { byteOrder });
exif[10] = alias;
exif[11] = alias;
return sourceJpegWithApp1Segments(64, 32, [exif]);
}
function sourceJpegExifWithSubIfd(options: {
readonly rootOrientation?: number;
readonly subIfdFirst?: boolean;
readonly subIfdOrientation: number;
}): Buffer {
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
const rootIfdOffset = 14;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt16LE(42, 8);
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
const writeOrientation = (offset: number, orientation: number) => {
exif.writeUInt16LE(0x0112, offset);
exif.writeUInt16LE(3, offset + 2);
exif.writeUInt32LE(1, offset + 4);
exif.writeUInt16LE(orientation, offset + 8);
};
const writeSubIfdPointer = (offset: number) => {
exif.writeUInt16LE(0x8769, offset);
exif.writeUInt16LE(4, offset + 2);
exif.writeUInt32LE(1, offset + 4);
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
};
const firstRootEntryOffset = rootIfdOffset + 2;
if (options.rootOrientation === undefined) {
writeSubIfdPointer(firstRootEntryOffset);
} else if (options.subIfdFirst) {
writeSubIfdPointer(firstRootEntryOffset);
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
} else {
writeOrientation(firstRootEntryOffset, options.rootOrientation);
writeSubIfdPointer(firstRootEntryOffset + 12);
}
exif.writeUInt16LE(1, subIfdOffset);
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
return sourceJpegApp1Segment(exif);
}
function sourceJpegExifWithSubIfdPointers(options: {
readonly pointerCount: number;
readonly subIfdEntries: number;
}): Buffer {
const { pointerCount, subIfdEntries } = options;
const rootIfdOffset = 14;
const rootEntries = pointerCount + 1;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt16LE(42, 8);
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
for (let index = 0; index < pointerCount; index += 1) {
const entryOffset = rootIfdOffset + 2 + index * 12;
exif.writeUInt16LE(0x8769, entryOffset);
exif.writeUInt16LE(4, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
}
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
exif.writeUInt16LE(0x0112, orientationOffset);
exif.writeUInt16LE(3, orientationOffset + 2);
exif.writeUInt32LE(1, orientationOffset + 4);
exif.writeUInt16LE(6, orientationOffset + 8);
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
for (let index = 0; index < subIfdEntries; index += 1) {
const entryOffset = subIfdOffset + 2 + index * 12;
exif.writeUInt16LE(1, entryOffset);
exif.writeUInt16LE(3, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
}
return sourceJpegApp1Segment(exif);
}
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
const rootIfdOffset = 14;
const rootEntries = pointerCount + 1;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
for (let index = 0; index < pointerCount; index += 1) {
const entryOffset = rootIfdOffset + 2 + index * 12;
exif.writeUInt16LE(0x8769, entryOffset);
exif.writeUInt16LE(4, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
}
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
exif.writeUInt16LE(0x0112, orientationOffset);
exif.writeUInt16LE(3, orientationOffset + 2);
exif.writeUInt32LE(1, orientationOffset + 4);
exif.writeUInt16LE(6, orientationOffset + 8);
return sourceJpegApp1Segment(exif);
}
function sourceWebp(width: number, height: number): Buffer {
const buffer = Buffer.alloc(30);
buffer.write("RIFF", 0, "ascii");
buffer.write("WEBP", 8, "ascii");
buffer.write("VP8X", 12, "ascii");
buffer.writeUIntLE(width - 1, 24, 3);
buffer.writeUIntLE(height - 1, 27, 3);
return buffer;
}
function sourceIco(embedded: Buffer): Buffer {
const buffer = Buffer.alloc(22 + embedded.byteLength);
buffer.writeUInt16LE(1, 2);
buffer.writeUInt16LE(1, 4);
buffer.writeUInt32LE(embedded.byteLength, 14);
buffer.writeUInt32LE(22, 18);
embedded.copy(buffer, 22);
return buffer;
}
function makeUnsafePng(): Buffer {
const buffer = Buffer.from(SOURCE_PNG);
buffer.writeUInt32BE(4096, 16);
buffer.writeUInt32BE(4096, 20);
return buffer;
}
function sourcePng(width: number, height: number): Buffer {
const buffer = Buffer.from(SOURCE_PNG);
buffer.writeUInt32BE(width, 16);
buffer.writeUInt32BE(height, 20);
return buffer;
}
function makeUnsafeDib(): Buffer {
const buffer = Buffer.alloc(40);
buffer.writeUInt32LE(40, 0);
buffer.writeInt32LE(4096, 4);
buffer.writeInt32LE(4096, 8);
return buffer;
}
function makeWebContents(options?: {
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
readonly rasterize?: (code: string) => Promise<unknown>;
}) {
const fetch = vi.fn(
options?.fetch ??
(async () =>
new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
})),
);
const executeJavaScriptInIsolatedWorld = vi.fn(
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
);
return {
webContents: {
session: { fetch },
executeJavaScriptInIsolatedWorld,
} as never,
executeJavaScriptInIsolatedWorld,
fetch,
};
}
const JPEG_LANDSCAPE_LAYOUT = {
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
resizeHeight: 16,
resizeWidth: 32,
} as const;
const JPEG_PORTRAIT_LAYOUT = {
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
resizeHeight: 32,
resizeWidth: 16,
} as const;
async function expectJpegLayout(
source: Buffer,
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
): Promise<void> {
const { webContents } = makeWebContents({
rasterize: async (code) => {
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
expect(code).toContain(layout.draw);
return PNG;
},
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
describe("selectFaviconCandidates", () => {
it("filters and deduplicates before applying the candidate cap", () => {
const valid = Array.from(
{ length: MAX_FAVICON_CANDIDATES + 2 },
(_, index) => `https://example.com/favicon-${index}.png`,
);
expect(
selectFaviconCandidates([
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
valid[0]!,
valid[0]!,
...valid.slice(1),
]),
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
});
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
expect(
selectFaviconCandidates([
...Array.from({ length: 128 }, () => oversizedInvalid),
"https://example.com/too-late.png",
]),
).toEqual([]);
});
});
describe("captureFavicon", () => {
it.each([
{
label: "same-origin",
pageUrl: "https://example.com/page",
faviconUrl: "https://example.com/favicon.png",
credentials: "include",
},
{
label: "cross-origin",
pageUrl: "https://example.com/page",
faviconUrl: "https://cdn.example.net/favicon.png",
credentials: "omit",
},
])("uses the explicit credential policy for $label requests", async (testCase) => {
const { webContents, fetch } = makeWebContents();
const result = await captureFavicon({
webContents,
pageUrl: testCase.pageUrl,
candidates: [testCase.faviconUrl],
signal: new AbortController().signal,
});
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
expect(fetch).toHaveBeenCalledWith(
testCase.faviconUrl,
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
);
});
it("decodes base64 and percent-encoded inline images without fetching", async () => {
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
const percentEncodedPng = [...SOURCE_PNG]
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
.join("");
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [candidate],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
expect(fetch).not.toHaveBeenCalled();
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
});
it("tries the next candidate after an ordinary rejection", async () => {
const { webContents, fetch } = makeWebContents({
fetch: async (url) =>
url.endsWith("first.png")
? new Response(null, { status: 404 })
: new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
expect(fetch).toHaveBeenCalledTimes(2);
});
it("cancels a rejected response body before trying the next candidate", async () => {
const cancel = vi.fn();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(1));
},
cancel,
});
const { webContents, fetch } = makeWebContents({
fetch: async (url) =>
url.endsWith("first.png")
? new Response(body, { status: 404 })
: new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
expect(cancel).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledTimes(2);
});
it("stops a pending fetch when its capture is aborted", async () => {
const controller = new AbortController();
const { webContents } = makeWebContents({
fetch: (_url, init) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
once: true,
});
}),
});
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: controller.signal,
});
controller.abort();
expect(await capture).toEqual({ kind: "none" });
});
it("ends candidate fallback when the overall capture deadline expires", async () => {
const timeoutController = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
const { webContents, fetch } = makeWebContents({
fetch: (url, init) => {
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
once: true,
});
});
},
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [
"https://example.com/first.png",
"https://example.com/second.png",
"https://example.com/third.png",
],
signal: new AbortController().signal,
});
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
expect(fetch).toHaveBeenCalledTimes(2);
expect(timeout).toHaveBeenCalledOnce();
} finally {
timeout.mockRestore();
}
});
it("does not publish a rasterization that completes after the capture deadline", async () => {
const captureTimeoutController = new AbortController();
const rasterTimeoutController = new AbortController();
const timeout = vi
.spyOn(AbortSignal, "timeout")
.mockImplementation((milliseconds) =>
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
);
let resolveRasterization!: (value: unknown) => void;
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
rasterize: () =>
new Promise((resolve) => {
resolveRasterization = resolve;
}),
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
});
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
resolveRasterization(PNG);
} finally {
timeout.mockRestore();
}
});
it("cancels a stalled response body when the capture deadline expires", async () => {
const timeoutController = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
const cancel = vi.fn();
const { webContents } = makeWebContents({
fetch: async () =>
new Response(
new ReadableStream<Uint8Array>({
cancel,
}),
{ headers: { "content-type": "image/png" } },
),
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
});
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
expect(cancel).toHaveBeenCalledOnce();
} finally {
timeout.mockRestore();
}
});
it("rejects and cancels an oversized streamed response", async () => {
const cancel = vi.fn();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
controller.enqueue(new Uint8Array(1));
},
cancel,
});
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(cancel).toHaveBeenCalledOnce();
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("retains bounded compatibility with common favicon formats", async () => {
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
for (const [mime, buffer] of [
["image/gif", sourceGif(32, 32)],
["image/jpeg", sourceJpeg(32, 32)],
["image/webp", sourceWebp(32, 32)],
["image/x-icon", sourceIco(SOURCE_PNG)],
] as const) {
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
});
it.each([
{
label: "landscape",
source: sourcePng(64, 32),
resizeWidth: 32,
resizeHeight: 16,
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
},
{
label: "portrait",
source: sourcePng(32, 64),
resizeWidth: 16,
resizeHeight: 32,
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
},
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
const { webContents } = makeWebContents({
rasterize: async (code) => {
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
expect(code).toContain('resizeQuality: "high"');
expect(code).toContain(testCase.draw);
return PNG;
},
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
});
it.each([
...[1, 2, 3, 4].map((orientation) => ({
label: `keeps stored dimensions for orientation ${orientation}`,
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, orientation),
})),
...[5, 6, 7, 8].map((orientation) => ({
label: `uses display dimensions for orientation ${orientation}`,
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpeg(64, 32, orientation),
})),
{
label: "uses the first separate EXIF segment when it is transposed",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpeg(64, 32, [6, 1]),
},
{
label: "uses the first separate EXIF segment when it is untransposed",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, [1, 6]),
},
{
label: "does not consult a later EXIF segment after an invalid orientation",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, [9, 6]),
},
{
label: "uses a later valid orientation in the same IFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
},
{
label: "skips a non-EXIF APP1 segment",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("not-exif")),
sourceJpegExifSegment([6]),
]),
},
{
label: "skips an empty EXIF APP1 segment",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
sourceJpegExifSegment([6]),
]),
},
{
label: "stops after a malformed qualifying EXIF APP1 segment",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
sourceJpegExifSegment([6]),
]),
},
{
label: "ignores the EXIF padding byte",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
},
{
label: "reads big-endian EXIF",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
},
{
label: "matches Chromium for a nonstandard TIFF magic field",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
},
{
label: "rejects a high-bit little-endian alias",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithEndianAlias(0xc9, "II"),
},
{
label: "rejects a high-bit big-endian alias",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithEndianAlias(0xcd, "MM"),
},
{
label: "reads an orientation from a SubIFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
]),
},
{
label: "uses a SubIFD orientation before a later root orientation",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({
rootOrientation: 1,
subIfdFirst: true,
subIfdOrientation: 6,
}),
]),
},
{
label: "uses a root orientation before a later SubIFD orientation",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
]),
},
{
label: "memoizes repeated aliases to the same SubIFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
]),
},
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
await expectJpegLayout(source, layout);
});
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
const source = sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithOverlappingSubIfds(32, 32),
]);
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("rejects an unsafe PNG size before rasterization", async () => {
const buffer = makeUnsafePng();
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
fetch: async () =>
new Response(new Uint8Array(buffer), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it.each([
["GIF", "image/gif", sourceGif(4096, 4096)],
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
[
"GIF cumulative frames",
"image/gif",
sourceGif(
64,
64,
64,
64,
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
),
],
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
["WebP", "image/webp", sourceWebp(4096, 4096)],
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
[
"SVG with embedded bitmap",
"image/svg+xml",
Buffer.from(
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
),
],
[
"ICO invalid payload span",
"image/x-icon",
(() => {
const buffer = Buffer.alloc(22);
buffer.writeUInt16LE(1, 2);
buffer.writeUInt16LE(1, 4);
buffer.writeUInt32LE(100, 14);
buffer.writeUInt32LE(22, 18);
return buffer;
})(),
],
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [candidate],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("ignores output that is not a bounded PNG data URL", async () => {
const { webContents } = makeWebContents({
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
});
it("waits for physical rasterization settlement after a logical timeout", async () => {
vi.useFakeTimers();
try {
let resolveOld!: (value: unknown) => void;
let executions = 0;
const { webContents } = makeWebContents({
rasterize: () => {
executions += 1;
return executions === 1
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(PNG);
},
});
const input = {
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
};
const timedOut = captureFavicon(input);
await vi.advanceTimersByTimeAsync(1_001);
expect(await timedOut).toEqual({ kind: "timed-out" });
const newer = captureFavicon(input);
await Promise.resolve();
expect(executions).toBe(1);
resolveOld(PNG);
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
expect(executions).toBe(2);
} finally {
vi.useRealTimers();
}
});
it("ends candidate fallback after a rasterization timeout", async () => {
vi.useFakeTimers();
try {
let resolveRasterization!: (value: unknown) => void;
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
rasterize: () =>
new Promise((resolve) => {
resolveRasterization = resolve;
}),
});
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
});
await vi.advanceTimersByTimeAsync(1_001);
expect(await capture).toEqual({ kind: "timed-out" });
expect(fetch).toHaveBeenCalledOnce();
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
resolveRasterization(PNG);
} finally {
vi.useRealTimers();
}
});
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
let resolveFirst!: (value: unknown) => void;
let executions = 0;
const { webContents } = makeWebContents({
rasterize: () => {
executions += 1;
return executions === 1
? new Promise((resolve) => {
resolveFirst = resolve;
})
: Promise.resolve(PNG);
},
});
const input = {
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
};
const first = captureFavicon(input);
const superseded = captureFavicon(input);
const newest = captureFavicon(input);
expect(executions).toBe(1);
resolveFirst(PNG);
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
expect(await superseded).toEqual({ kind: "none" });
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
expect(executions).toBe(2);
});
});
+679
View File
@@ -0,0 +1,679 @@
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
export const MAX_FAVICON_CANDIDATES = 8;
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
const FAVICON_RASTER_WORLD_ID = 1001;
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
interface RasterizationGate {
generation: number;
launchAllowed?: Promise<void>;
}
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
if (signal.aborted) return;
await new Promise<void>((resolve) => {
const finish = () => {
signal.removeEventListener("abort", finish);
resolve();
};
signal.addEventListener("abort", finish, { once: true });
void previous.then(finish);
});
}
export type FaviconCaptureResult =
| { readonly kind: "captured"; readonly dataUrl: string }
| { readonly kind: "none" }
| { readonly kind: "timed-out" };
type RasterizationResult =
| { readonly kind: "completed"; readonly value: unknown }
| { readonly kind: "timed-out" };
export function safeHttpOrigin(url: string): string | null {
try {
const parsed = new URL(url);
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
} catch {
return null;
}
}
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
const selected: string[] = [];
const seen = new Set<string>();
let inputUnits = 0;
for (const candidate of candidates) {
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
seen.add(candidate);
selected.push(candidate);
if (selected.length === MAX_FAVICON_CANDIDATES) break;
}
return selected;
}
export async function captureFavicon(input: {
readonly webContents: Electron.WebContents;
readonly pageUrl: string;
readonly candidates: ReadonlyArray<string>;
readonly signal: AbortSignal;
}): Promise<FaviconCaptureResult> {
const pageOrigin = safeHttpOrigin(input.pageUrl);
if (!pageOrigin) return { kind: "none" };
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
for (const candidate of selectFaviconCandidates(input.candidates)) {
if (captureSignal.aborted) {
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
}
const captured = await captureCandidate({
webContents: input.webContents,
pageOrigin,
candidate,
signal: captureSignal,
});
if (captureSignal.aborted) {
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
}
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
}
return { kind: "none" };
}
async function captureCandidate(input: {
readonly webContents: Electron.WebContents;
readonly pageOrigin: string;
readonly candidate: string;
readonly signal: AbortSignal;
}): Promise<FaviconCaptureResult> {
try {
const inline = parseInlineFavicon(input.candidate);
if (inline) {
return await normalizeFaviconBuffer(
input.webContents,
inline.mime,
inline.buffer,
input.signal,
);
}
const candidateOrigin = safeHttpOrigin(input.candidate);
if (!candidateOrigin) return { kind: "none" };
const response = await input.webContents.session.fetch(input.candidate, {
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
redirect: "error",
signal: input.signal,
});
if (!response.ok) {
await response.body?.cancel();
return { kind: "none" };
}
const buffer = await readFaviconResponse(response, input.signal);
if (!buffer || input.signal.aborted) return { kind: "none" };
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
} catch {
return { kind: "none" };
}
}
async function readFaviconResponse(
response: Response,
signal: AbortSignal,
): Promise<Buffer | null> {
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
await response.body?.cancel();
return null;
}
if (!response.body) {
const buffer = Buffer.from(await response.arrayBuffer());
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
}
const reader = response.body.getReader();
const cancelForAbort = () => {
void reader.cancel(signal.reason).catch(() => undefined);
};
signal.addEventListener("abort", cancelForAbort, { once: true });
if (signal.aborted) cancelForAbort();
const chunks: Buffer[] = [];
let byteLength = 0;
try {
while (true) {
const next = await reader.read();
if (next.done) return Buffer.concat(chunks, byteLength);
byteLength += next.value.byteLength;
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
await reader.cancel();
return null;
}
chunks.push(Buffer.from(next.value));
}
} finally {
signal.removeEventListener("abort", cancelForAbort);
reader.releaseLock();
}
}
function isSupportedFaviconUrl(url: string): boolean {
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
try {
const protocol = new URL(url).protocol;
return (
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
);
} catch {
return false;
}
}
function decodeInlineFaviconPayload(payload: string): Buffer | null {
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
let inputOffset = 0;
let outputOffset = 0;
while (inputOffset < payload.length) {
const escapeOffset = payload.indexOf("%", inputOffset);
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
if (escapeOffset === -1) break;
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
decoded[outputOffset] = Number.parseInt(hex, 16);
outputOffset += 1;
inputOffset = escapeOffset + 3;
}
return decoded.subarray(0, outputOffset);
}
function parseInlineFavicon(
url: string,
): { readonly buffer: Buffer; readonly mime: string } | null {
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
if (!match) return null;
const mime = match[1]?.toLowerCase();
const parameters = match[2]
?.split(";")
.filter(Boolean)
.map((parameter) => parameter.toLowerCase());
const payload = match[3];
if (!mime || !parameters || !payload) return null;
const base64 = parameters.at(-1) === "base64";
if (parameters.includes("base64") && !base64) return null;
let buffer: Buffer;
try {
if (base64) {
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
buffer = Buffer.from(payload, "base64");
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
return null;
}
} else {
const decoded = decodeInlineFaviconPayload(payload);
if (!decoded) return null;
buffer = decoded;
}
} catch {
return null;
}
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
? { buffer, mime }
: null;
}
interface ImageDimensions {
readonly width: number;
readonly height: number;
}
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
return (
dimensions !== null &&
Number.isSafeInteger(dimensions.width) &&
Number.isSafeInteger(dimensions.height) &&
dimensions.width > 0 &&
dimensions.height > 0 &&
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
);
}
function pngDimensions(buffer: Buffer): ImageDimensions | null {
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
return null;
}
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
}
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
let offset = startOffset;
while (offset < buffer.byteLength) {
const blockLength = buffer[offset]!;
offset += 1;
if (blockLength === 0) return offset;
if (offset + blockLength > buffer.byteLength) return null;
offset += blockLength;
}
return null;
}
function gifDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
return null;
}
const logicalWidth = buffer.readUInt16LE(6);
const logicalHeight = buffer.readUInt16LE(8);
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
const packed = buffer[10]!;
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
if (offset > buffer.byteLength) return null;
let width = logicalWidth;
let height = logicalHeight;
let frameCount = 0;
let framePixels = 0;
while (offset < buffer.byteLength) {
const marker = buffer[offset];
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
if (marker === 0x2c) {
if (offset + 10 > buffer.byteLength) return null;
const left = buffer.readUInt16LE(offset + 1);
const top = buffer.readUInt16LE(offset + 3);
const frameWidth = buffer.readUInt16LE(offset + 5);
const frameHeight = buffer.readUInt16LE(offset + 7);
if (frameWidth === 0 || frameHeight === 0) return null;
framePixels += frameWidth * frameHeight;
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
width = Math.max(width, left + frameWidth);
height = Math.max(height, top + frameHeight);
if (!safeDimensions({ width, height })) return null;
const framePacked = buffer[offset + 9]!;
offset += 10;
if ((framePacked & 0x80) !== 0) {
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
}
if (offset >= buffer.byteLength) return null;
const minimumCodeSize = buffer[offset]!;
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
offset += 1;
const nextOffset = skipGifSubBlocks(buffer, offset);
if (nextOffset === null) return null;
offset = nextOffset;
frameCount += 1;
continue;
}
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
if (nextOffset === null) return null;
offset = nextOffset;
}
return null;
}
interface JpegExifMetadata {
readonly complete: boolean;
readonly orientation: number | null;
}
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
return null;
}
const metadataWithoutOrientation = (): JpegExifMetadata => ({
complete: true,
orientation: null,
});
if (segment.byteLength < 14) return metadataWithoutOrientation();
const tiffOffset = 6;
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
const readUInt16 = (offset: number): number | null => {
if (offset < 0 || offset + 2 > segment.byteLength) return null;
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
};
const readUInt32 = (offset: number): number | null => {
if (offset < 0 || offset + 4 > segment.byteLength) return null;
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
};
const relativeIfdOffset = readUInt32(tiffOffset + 4);
if (relativeIfdOffset === null) return metadataWithoutOrientation();
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
type IfdOrientation = number | null | typeof budgetExhausted;
const subIfdOrientationByOffset = new Map<number, number | null>();
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
}
const entryCount = readUInt16(ifdOffset);
if (entryCount === null) return null;
let result: IfdOrientation = null;
for (let index = 0; index < entryCount; index += 1) {
if (remainingIfdEntryVisits === 0) return budgetExhausted;
remainingIfdEntryVisits -= 1;
const entryOffset = ifdOffset + 2 + index * 12;
if (entryOffset + 12 > segment.byteLength) break;
const tag = readUInt16(entryOffset);
const type = readUInt16(entryOffset + 2);
const count = readUInt32(entryOffset + 4);
if (tag === 0x0112 && type === 3 && count === 1) {
const orientation = readUInt16(entryOffset + 8);
if (orientation !== null && orientation >= 1 && orientation <= 8) {
result = orientation;
break;
}
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
if (relativeSubIfdOffset !== null) {
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
if (orientation === budgetExhausted) return budgetExhausted;
if (orientation !== null) {
result = orientation;
break;
}
}
}
}
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
return result;
};
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
return orientation === budgetExhausted
? { complete: false, orientation: null }
: { complete: true, orientation };
}
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
const startOfFrameMarkers = new Set([
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
]);
let offset = 2;
let dimensions: ImageDimensions | null = null;
let exifMetadata: JpegExifMetadata | null = null;
while (offset + 3 < buffer.byteLength) {
if (buffer[offset] !== 0xff) {
offset += 1;
continue;
}
while (buffer[offset] === 0xff) offset += 1;
const marker = buffer[offset];
offset += 1;
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
if (offset + 1 >= buffer.byteLength) return null;
const length = buffer.readUInt16BE(offset);
if (length < 2 || offset + length > buffer.byteLength) return null;
if (marker === 0xe1 && exifMetadata === null) {
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
}
if (startOfFrameMarkers.has(marker)) {
if (length < 7) return null;
if (dimensions !== null) return null;
dimensions = {
height: buffer.readUInt16BE(offset + 3),
width: buffer.readUInt16BE(offset + 5),
};
}
offset += length;
}
if (!dimensions) return null;
if (exifMetadata?.complete === false) return null;
const orientation = exifMetadata?.orientation;
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
? { width: dimensions.height, height: dimensions.width }
: dimensions;
}
function webpDimensions(buffer: Buffer): ImageDimensions | null {
if (
buffer.byteLength < 30 ||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
) {
return null;
}
const kind = buffer.subarray(12, 16).toString("ascii");
if (kind === "VP8X") {
return {
width: 1 + buffer.readUIntLE(24, 3),
height: 1 + buffer.readUIntLE(27, 3),
};
}
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
return {
width: buffer.readUInt16LE(26) & 0x3fff,
height: buffer.readUInt16LE(28) & 0x3fff,
};
}
if (kind === "VP8L" && buffer[20] === 0x2f) {
return {
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
};
}
return null;
}
function dibDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 12) return null;
const headerSize = buffer.readUInt32LE(0);
if (headerSize === 12) {
return {
width: buffer.readUInt16LE(4),
height: buffer.readUInt16LE(6),
};
}
if (headerSize < 40 || buffer.byteLength < 12) return null;
return {
width: Math.abs(buffer.readInt32LE(4)),
height: Math.abs(buffer.readInt32LE(8)),
};
}
function icoDimensions(buffer: Buffer): ImageDimensions | null {
if (
buffer.byteLength < 22 ||
buffer.readUInt16LE(0) !== 0 ||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
) {
return null;
}
const count = buffer.readUInt16LE(4);
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
let width = 0;
let height = 0;
for (let index = 0; index < count; index += 1) {
const offset = 6 + index * 16;
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
if (!safeDimensions({ width, height })) return null;
const byteLength = buffer.readUInt32LE(offset + 8);
const imageOffset = buffer.readUInt32LE(offset + 12);
if (
byteLength === 0 ||
imageOffset < 6 + count * 16 ||
imageOffset > buffer.byteLength ||
byteLength > buffer.byteLength - imageOffset
)
return null;
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
if (!safeDimensions(embeddedDimensions)) return null;
}
return { width, height };
}
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
return (
pngDimensions(buffer) ??
gifDimensions(buffer) ??
jpegDimensions(buffer) ??
webpDimensions(buffer) ??
icoDimensions(buffer)
);
}
async function normalizeFaviconBuffer(
webContents: Electron.WebContents,
mime: string | null,
buffer: Buffer,
signal: AbortSignal,
): Promise<FaviconCaptureResult> {
const declaredMime = mime?.trim().toLowerCase() || null;
const normalizedMime =
declaredMime === "application/x-icon"
? "image/x-icon"
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
? null
: declaredMime;
const dimensions = sourceDimensions(buffer);
if (
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
normalizedMime === "image/svg+xml" ||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
!safeDimensions(dimensions)
) {
return { kind: "none" };
}
const rasterized = await rasterizeFavicon(
webContents,
normalizedMime,
buffer,
dimensions,
signal,
);
if (rasterized.kind === "timed-out") return rasterized;
return typeof rasterized.value === "string" &&
rasterized.value.startsWith("data:image/png;base64,") &&
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
? { kind: "captured", dataUrl: rasterized.value }
: { kind: "none" };
}
async function rasterizeFavicon(
webContents: Electron.WebContents,
mime: string | null,
buffer: Buffer,
dimensions: ImageDimensions,
signal: AbortSignal,
): Promise<RasterizationResult> {
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
rasterizationGates.set(webContents, gate);
const generation = ++gate.generation;
const previousLaunchAllowed = gate.launchAllowed;
if (previousLaunchAllowed) {
await waitForRasterLaunch(previousLaunchAllowed, signal);
}
if (signal.aborted || generation !== gate.generation) {
return { kind: "completed", value: null };
}
const payload = buffer.toString("base64");
const blobType = mime ?? "";
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
const drawX = (32 - decodeWidth) / 2;
const drawY = (32 - decodeHeight) / 2;
const code = `
(() => {
const rasterize = async () => {
try {
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
resizeWidth: ${decodeWidth},
resizeHeight: ${decodeHeight},
resizeQuality: "high",
});
try {
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
return null;
}
const canvas = new OffscreenCanvas(32, 32);
const context = canvas.getContext("2d");
if (!context) return null;
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
const blob = await canvas.convertToBlob({ type: "image/png" });
const output = new Uint8Array(await blob.arrayBuffer());
let binary = "";
for (const byte of output) binary += String.fromCharCode(byte);
return "data:image/png;base64," + btoa(binary);
} finally {
bitmap.close();
}
} catch {
return null;
}
};
return rasterize();
})()
`;
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
{ code },
]);
const result = new Promise<RasterizationResult>((resolve, reject) => {
// Electron cannot cancel isolated-world execution. This timeout ends only
// the logical attempt; renderer work may finish after a newer attempt starts.
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
let settled = false;
const finish = (complete: () => void) => {
if (settled) return;
settled = true;
timeout.removeEventListener("abort", onTimeout);
signal.removeEventListener("abort", onAbort);
complete();
};
const onTimeout = () => {
finish(() => resolve({ kind: "timed-out" }));
};
const onAbort = () => {
finish(() => resolve({ kind: "completed", value: null }));
};
timeout.addEventListener("abort", onTimeout, { once: true });
signal.addEventListener("abort", onAbort, { once: true });
void execution.then(
(value) => {
finish(() => resolve({ kind: "completed", value }));
},
(cause: unknown) => {
finish(() => reject(cause));
},
);
if (signal.aborted) onAbort();
});
// The logical timeout does not cancel Electron's renderer work. Keep the
// gate closed until that physical execution actually settles.
const launchAllowed = execution.then(
() => undefined,
() => undefined,
);
gate.launchAllowed = launchAllowed;
void launchAllowed.then(() => {
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
});
return await result;
}
+604
View File
@@ -186,6 +186,102 @@ const makeTestPreviewWebContents = (
capturePage,
}) as never;
const TEST_FAVICON = "data:image/png;base64,cG5n";
const makeSourcePng = (width = 1, height = 1): Buffer => {
const buffer = Buffer.alloc(24);
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
buffer.writeUInt32BE(width, 16);
buffer.writeUInt32BE(height, 20);
return buffer;
};
const makeFaviconWebContents = (options?: {
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
readonly id?: number;
readonly rasterize?: (code: string) => Promise<unknown>;
readonly url?: string;
}) => {
const sourcePng = makeSourcePng();
const listeners = new Map<string, (...args: never[]) => void>();
let currentUrl = options?.url ?? "http://localhost:3200/";
let destroyed = false;
let loading = false;
const fetch = vi.fn(
options?.fetch ??
(async () =>
new Response(new Uint8Array(sourcePng), {
headers: { "content-type": "image/png" },
})),
);
const executeJavaScriptInIsolatedWorld = vi.fn(
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
);
const reload = vi.fn();
const loadURL = vi.fn(async (url: string) => {
currentUrl = url;
});
const off = vi.fn();
const debuggerOff = vi.fn();
const webContents = {
id: options?.id ?? 42,
isDestroyed: () => destroyed,
getType: () => "webview",
getURL: () => currentUrl,
getTitle: () => "Preview",
isLoading: () => loading,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
reload,
reloadIgnoringCache: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off,
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
session: { fetch },
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
executeJavaScriptInIsolatedWorld,
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: debuggerOff,
},
};
return {
executeJavaScriptInIsolatedWorld,
fetch,
debuggerOff,
listeners,
loadURL,
off,
reload,
setDestroyed: (value: boolean) => {
destroyed = value;
},
setLoading: (value: boolean) => {
loading = value;
},
setUrl: (url: string) => {
currentUrl = url;
},
webContents: webContents as never,
};
};
const settle = function* (until: () => boolean) {
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
yield* Effect.promise(() => Promise.resolve());
}
};
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
const listeners = new Map<string, () => void>();
const send = vi.fn();
@@ -257,6 +353,32 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("rejects a destroyed webview during registration", () =>
withManager((manager) =>
Effect.gen(function* () {
const getType = vi.fn(() => "webview" as const);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => true,
getType,
} as never);
yield* manager.createTab("tab_destroyed_registration");
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
_tag: "PreviewWebContentsNotFoundError",
tabId: "tab_destroyed_registration",
webContentsId: 42,
});
}
expect(getType).not.toHaveBeenCalled();
}),
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
@@ -375,6 +497,488 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_destroyed_navigation");
yield* manager.registerWebview("tab_destroyed_navigation", 42);
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
preview.setDestroyed(true);
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
expect(preview.loadURL).not.toHaveBeenCalled();
expect(preview.reload).not.toHaveBeenCalled();
expect(preview.off).toHaveBeenCalled();
expect(preview.debuggerOff).toHaveBeenCalled();
expect(states.at(-1)).toMatchObject({
webContentsId: null,
navStatus: { kind: "Loading", url: "https://example.com/" },
});
}),
),
);
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
withManager((manager) =>
Effect.gen(function* () {
const previous = makeFaviconWebContents();
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
let current = previous.webContents;
let startReplacementRegistration: () => void = () => void 0;
const replacementReady = new Promise<void>((resolve) => {
startReplacementRegistration = resolve;
});
fromId.mockImplementation(() => current);
yield* manager.createTab("tab_destroyed_replacement_race");
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
Effect.forkChild({ startImmediately: true }),
);
previous.setDestroyed(true);
previous.debuggerOff.mockImplementationOnce(() => {
current = replacement.webContents;
startReplacementRegistration();
});
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
const registrationExit = yield* Fiber.await(replacementRegistration);
expect(Exit.isSuccess(registrationExit)).toBe(true);
expect(previous.off).toHaveBeenCalled();
expect(replacement.off).not.toHaveBeenCalled();
expect(states.at(-1)).toMatchObject({
webContentsId: 42,
navStatus: { kind: "Loading", url: "https://example.com/" },
});
}),
),
);
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents({
url: `http://localhost:3200/${"x".repeat(3_000)}`,
});
preview.setLoading(true);
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_loading");
yield* manager.registerWebview("tab_favicon_loading", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
expect(states.at(-1)?.favicon).toMatchObject({
dataUrl: TEST_FAVICON,
pageUrl: "http://localhost:3200",
});
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
}),
),
);
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFirst!: (response: Response) => void;
const firstResponse = new Promise<Response>((resolve) => {
resolveFirst = resolve;
});
const preview = makeFaviconWebContents({
fetch: (url) =>
url.endsWith("first.png")
? firstResponse
: Promise.resolve(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_latest");
yield* manager.registerWebview("tab_favicon_latest", 42);
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
yield* settle(() => preview.fetch.mock.calls.length === 1);
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
yield* settle(() => states.at(-1)?.favicon !== undefined);
resolveFirst(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(preview.fetch).toHaveBeenCalledTimes(2);
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
}),
),
);
effectIt.effect("allows an identical retry after an undecodable capture", () =>
withManager((manager) =>
Effect.gen(function* () {
let rasterizations = 0;
const preview = makeFaviconWebContents({
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_retry");
yield* manager.registerWebview("tab_favicon_retry", 42);
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
yield* settle(() => rasterizations === 1);
yield* settle(() => false);
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
yield* settle(() => states.at(-1)?.favicon !== undefined);
expect(rasterizations).toBe(2);
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("does not publish a capture invalidated by navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFetch!: (response: Response) => void;
const preview = makeFaviconWebContents({
fetch: () =>
new Promise<Response>((resolve) => {
resolveFetch = resolve;
}),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_navigation");
yield* manager.registerWebview("tab_favicon_navigation", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => preview.fetch.mock.calls.length === 1);
preview.listeners.get("did-start-navigation")?.({
isMainFrame: true,
isSameDocument: false,
} as never);
preview.setUrl("https://example.com/");
resolveFetch(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
}),
),
);
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reload");
yield* manager.registerWebview("tab_favicon_reload", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
expect(preview.reload).toHaveBeenCalledOnce();
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_origin");
yield* manager.registerWebview("tab_favicon_origin", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.setUrl("https://example.com/");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect(
"retains the previous document icon across a failed cross-origin navigation",
() =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_failed_origin");
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.listeners.get("did-fail-load")?.(
{} as never,
-105 as never,
"Name not resolved" as never,
"https://unreachable.example/" as never,
true as never,
);
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_blank");
yield* manager.registerWebview("tab_favicon_blank", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.setUrl("about:blank");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
expect(states.at(-1)?.favicon).toBeUndefined();
preview.setUrl("http://localhost:3200/");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
withManager((manager) =>
Effect.gen(function* () {
const initial = makeFaviconWebContents({ id: 42 });
const replacement = makeFaviconWebContents({ id: 43 });
fromId.mockImplementation((id?: number) => {
if (id === 42) return initial.webContents;
if (id === 43) return replacement.webContents;
return null;
});
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_replace");
yield* manager.registerWebview("tab_favicon_replace", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.registerWebview("tab_favicon_replace", 43);
expect(states.at(-1)?.webContentsId).toBe(43);
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFetch!: (response: Response) => void;
const initial = makeFaviconWebContents({
id: 42,
fetch: () =>
new Promise<Response>((resolve) => {
resolveFetch = resolve;
}),
});
const replacement = makeFaviconWebContents({ id: 43 });
fromId.mockImplementation((id?: number) =>
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_late_replace");
yield* manager.registerWebview("tab_favicon_late_replace", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => initial.fetch.mock.calls.length === 1);
yield* manager.registerWebview("tab_favicon_late_replace", 43);
resolveFetch(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(states.at(-1)?.webContentsId).toBe(43);
expect(
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
).toBe(false);
}),
),
);
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
withManager((manager) =>
Effect.gen(function* () {
const initial = makeFaviconWebContents({ id: 42 });
const replacement = makeFaviconWebContents({ id: 42 });
let active = initial.webContents;
fromId.mockImplementation(() => active);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reused_id");
yield* manager.registerWebview("tab_favicon_reused_id", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
active = replacement.webContents;
yield* manager.registerWebview("tab_favicon_reused_id", 42);
expect(states.at(-1)?.favicon).toBeUndefined();
expect(initial.off).toHaveBeenCalled();
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
}),
),
);
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reregister");
yield* manager.registerWebview("tab_favicon_reregister", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.registerWebview("tab_favicon_reregister", 42);
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
+204 -21
View File
@@ -8,6 +8,7 @@
import type {
DesktopPreviewAnnotationTheme,
DesktopPreviewColorScheme,
DesktopPreviewFavicon,
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
@@ -62,6 +63,7 @@ import {
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -85,6 +87,7 @@ export interface PreviewTabState {
pictureInPicture: boolean;
colorScheme: DesktopPreviewColorScheme;
controller: "human" | "agent" | "none";
favicon?: DesktopPreviewFavicon;
updatedAt: string;
}
@@ -346,7 +349,10 @@ type PreviewInputSignal =
| { readonly kind: "key"; readonly key: string; readonly code: string };
interface ManagedListeners {
readonly attachmentId: symbol;
readonly cancelFaviconCapture: () => void;
readonly scope: Scope.Closeable;
readonly webContents: Electron.WebContents;
}
type FrameCaptureConsumer = "picture-in-picture" | "recording";
@@ -613,6 +619,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
tabId: string,
state: PreviewTabState,
) {
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
yield* emit(tabId, state);
}
});
const update = Effect.fn("PreviewManager.update")(function* (
tabId: string,
patch: Partial<PreviewTabState>,
@@ -1204,7 +1219,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
copy.delete(webContentsId);
}),
]);
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
if (managed) {
managed.cancelFaviconCapture();
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
}
});
const isAppShortcut = (input: Electron.Input): boolean =>
@@ -1268,8 +1286,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const attachmentId = Symbol();
let documentId = 0;
let nextRequestId = 0;
let activeCapture: {
readonly controller: AbortController;
readonly documentId: number;
readonly eventKey: string;
readonly requestId: number;
} | null = null;
const cancelFaviconCapture = () => {
documentId += 1;
activeCapture?.controller.abort();
activeCapture = null;
};
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
confirmedNavigation = false,
) {
if (wc.isDestroyed()) return;
const zoomFactor = yield* attempt(
@@ -1282,7 +1315,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
@@ -1292,8 +1327,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const clearFavicon =
confirmedNavigation &&
current.favicon !== undefined &&
safeHttpOrigin(current.favicon.pageUrl) !==
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const state: PreviewTabState = {
...current,
...(clearFavicon ? currentWithoutFavicon : current),
navStatus,
canGoBack,
canGoForward,
@@ -1307,10 +1348,109 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}),
] as const;
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
});
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const syncNavigation = () => runFork(syncState(false, true));
const syncInPageNavigation = () => runFork(syncState(false));
const navigationStarted = (
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
) => {
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
};
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
readonly captureDocumentId: number;
readonly dataUrl: string;
readonly pageUrl: string;
readonly requestId: number;
}) {
const pageOrigin = safeHttpOrigin(input.pageUrl);
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
if (
!pageOrigin ||
wc.isDestroyed() ||
webContents.fromId(wc.id) !== wc ||
managed?.attachmentId !== attachmentId ||
activeCapture?.documentId !== input.captureDocumentId ||
activeCapture.requestId !== input.requestId ||
safeHttpOrigin(wc.getURL()) !== pageOrigin
) {
return;
}
const capturedAt = yield* currentMillis;
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (
!current ||
current.webContentsId !== wc.id ||
webContents.fromId(wc.id) !== wc ||
activeCapture?.documentId !== input.captureDocumentId ||
activeCapture.requestId !== input.requestId
) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
const state: PreviewTabState = {
...current,
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
});
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
});
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
const pageUrl = wc.getURL();
if (!safeHttpOrigin(pageUrl)) return;
const candidates = selectFaviconCandidates(rawCandidates);
if (candidates.length === 0) return;
const eventKey = JSON.stringify([pageUrl, ...candidates]);
if (activeCapture?.eventKey === eventKey) return;
activeCapture?.controller.abort();
const captureDocumentId = documentId;
const requestId = ++nextRequestId;
const controller = new AbortController();
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
runFork(
Effect.tryPromise({
try: () =>
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
catch: (cause) =>
new PreviewOperationError({
operation: "captureFavicon",
tabId,
webContentsId: wc.id,
cause,
}),
}).pipe(
Effect.flatMap((result) =>
result.kind === "captured"
? publishFavicon({
captureDocumentId,
dataUrl: result.dataUrl,
pageUrl,
requestId,
})
: Effect.void,
),
Effect.catch((error) =>
controller.signal.aborted
? Effect.void
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
),
Effect.ensuring(
Effect.sync(() => {
if (activeCapture?.requestId === requestId) activeCapture = null;
}),
),
),
);
};
const failed = (
_event: Event,
code: number,
@@ -1387,9 +1527,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
cancelFaviconCapture();
wc.off("did-start-navigation", navigationStarted);
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("did-navigate-in-page", syncInPageNavigation);
wc.off("page-title-updated", sync);
wc.off("page-favicon-updated", faviconUpdated as never);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
wc.off("did-fail-load", failed as never);
@@ -1399,9 +1542,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-start-navigation", navigationStarted);
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("did-navigate-in-page", syncInPageNavigation);
wc.on("page-title-updated", sync);
wc.on("page-favicon-updated", faviconUpdated as never);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
wc.on("did-fail-load", failed as never);
@@ -1418,7 +1563,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
yield* Ref.update(attachedRef, (attached) =>
replaceMap(attached, (copy) => {
copy.set(wc.id, { scope });
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
}),
);
});
@@ -1561,6 +1706,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const mainWindow = yield* Ref.get(mainWindowRef);
if (
!wc ||
wc.isDestroyed() ||
wc.getType() !== "webview" ||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
) {
@@ -1568,7 +1714,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const currentAttachment = attached.get(webContentsId);
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
@@ -1580,7 +1727,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
tab.webContentsId != null &&
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
? tab.webContentsId
: null;
if (replacedWebContentsId !== null) {
yield* Effect.all(
[
@@ -1627,8 +1777,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const next: PreviewTabState = {
...current,
...currentWithoutFavicon,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
@@ -1707,6 +1858,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
pictureInPicture: current?.pictureInPicture ?? false,
colorScheme: current?.colorScheme ?? "system",
controller: current?.controller ?? "none",
...(current?.favicon ? { favicon: current.favicon } : {}),
updatedAt,
};
return [
@@ -1718,17 +1870,48 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
const webContentsId = pending.webContentsId;
const wc = webContents.fromId(webContentsId);
if (!wc || wc.isDestroyed()) {
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
yield* withTabLifecycleLock(
tabId,
Effect.gen(function* () {
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
const currentWebContents = webContents.fromId(webContentsId);
if (
currentTab?.webContentsId !== webContentsId ||
currentAttachment !== expectedAttachment ||
(currentWebContents && !currentWebContents.isDestroyed())
) {
return;
}
yield* Effect.all(
[
detachControlSession(webContentsId),
detachListeners(webContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (current?.webContentsId !== webContentsId) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
return [
Option.some(next),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
@@ -77,6 +77,7 @@ const backendConfigurationLayer = Layer.succeed(
const netLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(41773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
} satisfies NetService.NetService["Service"]);
+19 -15
View File
@@ -229,15 +229,18 @@ const NODE_PTY_PROBE_SCRIPT = (
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The server bundle externalizes its deps to node_modules, and the WSL Node
// can't read inside app.asar, so confirm those deps are unpacked on the real
// filesystem before reporting the backend healthy. "effect" is the framework
// every server module imports; resolving it validates the whole node_modules
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
// report it accurately instead of letting the server crash on
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
// launch with no fallback).
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
// The WSL Node can't read inside app.asar, so confirm what the server needs is
// unpacked on the real filesystem before reporting the backend healthy. Exit 3
// marks this distinct from a node-pty prebuild problem so the caller can report
// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
// launch (which, in wsl-only mode, would just fail to launch with no fallback).
//
// The sentinel must be a package the CLI bundle leaves external. It used to be
// "effect", back when the bundle externalized its runtime deps and the whole
// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
// so "effect" no longer exists on disk and only the native packages do —
// resolving node-pty is what actually validates the unpacked tree.
try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
const fs = require("node:fs");
const path = require("node:path");
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
@@ -462,16 +465,17 @@ const ensureNodePtyImpl = (
} as const;
}
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
// filesystem — a packaging regression, since the server bundle needs its
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
// Windows and dual mode surfaces the reason inline, instead of the server
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
// The packages the server bundle leaves external (node-pty and the other
// native addons) couldn't be resolved on the WSL filesystem — a packaging
// regression, since those must be unpacked from the asar. Fatal so wsl-only
// mode falls back to Windows and dual mode surfaces the reason inline,
// instead of the server crash-looping on ERR_MODULE_NOT_FOUND once it
// actually launches.
if (probe.exitCode === 3) {
return {
ok: false,
reason:
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
fatal: true,
} as const;
}
@@ -0,0 +1,323 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopWslServerTree from "./DesktopWslServerTree.ts";
// The service reads packaged Windows roots through the (asar-aware, in
// Electron) fs, so a plain directory named server.asar exercises the full
// extraction path under plain Node.
const environmentLayer = (input: {
readonly baseDir: string;
readonly resourcesPath: string;
readonly appVersion?: string;
readonly isPackaged?: boolean;
}) =>
DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: input.baseDir,
platform: "win32",
processArch: "x64",
appVersion: input.appVersion ?? "1.2.3",
appPath: "/repo",
isPackaged: input.isPackaged ?? true,
resourcesPath: input.resourcesPath,
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: input.baseDir,
T3CODE_MODE: "desktop",
}),
),
),
);
const withTempDir = <A, E, R>(
run: (tempDir: string) => Effect.Effect<A, E, R>,
): Effect.Effect<
A,
E | PlatformError.PlatformError,
FileSystem.FileSystem | Exclude<R, Scope.Scope>
> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-wsl-server-tree-test-",
});
return yield* run(tempDir);
}).pipe(Effect.scoped);
const ensureWith = (input: {
readonly baseDir: string;
readonly resourcesPath: string;
readonly appVersion?: string;
readonly isPackaged?: boolean;
}) =>
Effect.gen(function* () {
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
return yield* tree.ensure;
}).pipe(
Effect.provide(DesktopWslServerTree.layer.pipe(Layer.provideMerge(environmentLayer(input)))),
);
describe("DesktopWslServerTree", () => {
it.effect("bounds entry work across an eight-way nested tree", () =>
Effect.gen(function* () {
const active = yield* Ref.make(0);
const maxActive = yield* Ref.make(0);
const visited = yield* Ref.make(0);
yield* DesktopWslServerTree.forEachBoundedTree([{ depth: 0, id: "root" }], (node) =>
Effect.acquireUseRelease(
Effect.gen(function* () {
const current = yield* Ref.updateAndGet(active, (count) => count + 1);
yield* Ref.update(maxActive, (maximum) => Math.max(maximum, current));
yield* Ref.update(visited, (count) => count + 1);
}),
() =>
Effect.gen(function* () {
// Give every task in the current batch a chance to overlap.
yield* Effect.yieldNow;
if (node.depth === 4) return [];
return Array.from({ length: 8 }, (_, index) => ({
depth: node.depth + 1,
id: `${node.id}.${String(index)}`,
}));
}),
() => Ref.update(active, (count) => count - 1),
),
);
assert.equal(yield* Ref.get(active), 0);
assert.equal(yield* Ref.get(maxActive), 8);
assert.equal(yield* Ref.get(visited), 4_681);
}),
);
it.effect("returns the server root unchanged when it is a plain directory (dev)", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: tempDir,
isPackaged: false,
});
assert.isTrue(result.ok);
assert.isFalse(result.ok && result.root.endsWith(".asar"));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("extracts an archive root into a version-keyed state directory", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"server-entry",
);
yield* fileSystem.makeDirectory(path.join(serverRoot, "node_modules/effect"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "node_modules/effect/package.json"),
"{}",
);
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(result.ok);
const root = result.ok ? result.root : "";
assert.include(root, path.join("wsl-server-tree", "1.2.3"));
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "server-entry");
const dep = yield* fileSystem.exists(path.join(root, "node_modules/effect/package.json"));
assert.isTrue(dep);
const marker = yield* fileSystem.readFileString(
path.join(root, "t3code-wsl-server-tree.json"),
);
assert.include(marker, '"version":"1.2.3"');
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("serializes concurrent extraction callers and publishes one complete tree", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const resourcesPath = path.join(tempDir, "resources");
const serverRoot = path.join(resourcesPath, "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"server-entry",
);
const results = yield* Effect.gen(function* () {
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
return yield* Effect.all([tree.ensure, tree.ensure], { concurrency: "unbounded" });
}).pipe(
Effect.provide(
DesktopWslServerTree.layer.pipe(
Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),
),
),
);
assert.isTrue(results.every((result) => result.ok));
const roots = results.flatMap((result) => (result.ok ? [result.root] : []));
assert.lengthOf(new Set(roots), 1);
assert.equal(
yield* fileSystem.readFileString(path.join(roots[0] ?? "", "apps/server/dist/bin.mjs")),
"server-entry",
);
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reuses a completed extraction instead of copying again", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "v1");
const first = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(first.ok);
// Mutate the source; a reused tree must keep the first copy.
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"v2-should-not-appear",
);
const second = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(second.ok);
const root = second.ok ? second.root : "";
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "v1");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("sweeps stale version directories and leftover partials after extraction", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "x");
// T3CODE_HOME is set to tempDir, so the desktop state dir resolves to
// <tempDir>/userdata (no .t3 segment).
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.0.0"), { recursive: true });
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.2.3.partial"), { recursive: true });
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(result.ok);
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.0.0")));
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3.partial")));
assert.isTrue(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("re-extracts when the app version changes", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "old");
const first = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
appVersion: "1.2.3",
});
assert.isTrue(first.ok);
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "new");
const second = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
appVersion: "1.2.4",
});
assert.isTrue(second.ok);
const root = second.ok ? second.root : "";
assert.include(root, "1.2.4");
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "new");
// The previous version's tree is gone.
const treeRoot = path.dirname(root);
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reports a retryable failure when the archive cannot be read", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const result = yield* ensureWith({
baseDir: tempDir,
// resources dir exists but server.asar does not
resourcesPath: path.join(tempDir, "resources"),
});
assert.isFalse(result.ok);
if (!result.ok) {
assert.include(result.reason, "could not be extracted");
assert.isFalse(result.fatal);
}
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
const leftovers = yield* fileSystem
.readDirectory(treeRoot)
.pipe(Effect.orElseSucceed(() => []));
assert.deepStrictEqual(leftovers, []);
}),
).pipe(Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,226 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
// Packaged Windows builds ship the server tree inside resources/server.asar
// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in
// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL
// backend launches plain `wsl.exe -- node`, which cannot read an asar
// archive. This service materializes the archive into a real, version-keyed
// directory the first time the WSL backend starts, and reuses it afterwards —
// so only users who enable WSL ever pay for a loose copy of the server tree.
//
// Reading through Electron's patched fs also transparently returns the
// contents of files that electron-builder/asar left in the server.asar.unpacked
// sibling (native binaries), so a single walk of the archive yields the
// complete tree.
export type WslServerTreeResult =
| { readonly ok: true; readonly root: string }
| { readonly ok: false; readonly reason: string; readonly fatal: boolean };
const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
const COPY_CONCURRENCY = 8;
const Marker = Schema.Struct({ version: Schema.String });
const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
export class DesktopWslServerTreeExtractError extends Schema.TaggedErrorClass<DesktopWslServerTreeExtractError>()(
"DesktopWslServerTreeExtractError",
{
targetDir: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to extract the WSL server tree to ${this.targetDir}.`;
}
}
export class DesktopWslServerTree extends Context.Service<
DesktopWslServerTree,
{
// Resolves the directory the WSL backend should treat as the app root
// (the directory containing apps/server/dist and node_modules). In dev
// the checkout already is that directory; packaged Windows builds extract
// server.asar on first use.
readonly ensure: Effect.Effect<WslServerTreeResult>;
}
>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
// Child scheduling stays here instead of inside `visit`, so nested directories
// cannot create independent concurrency pools. The LIFO work list also keeps
// traversal memory proportional to the remaining frontier rather than the
// number of active fibers.
export const forEachBoundedTree = <Node, E, R>(
roots: ReadonlyArray<Node>,
visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
): Effect.Effect<void, E, R> =>
Effect.gen(function* () {
const pending = [...roots];
while (pending.length > 0) {
const batch = pending.splice(-COPY_CONCURRENCY);
const children = yield* Effect.forEach(batch, visit, {
concurrency: COPY_CONCURRENCY,
});
for (const entries of children) {
pending.push(...entries);
}
}
});
interface CopyTreeEntry {
readonly sourcePath: string;
readonly targetPath: string;
}
// Copy using only operations supported by Electron's asar-patched fs. Symlinks
// are not expected because the sidecar is installed with a hoisted, physical
// layout; anything that is neither a file nor a directory is skipped.
const copyTree = (
fs: FileSystem.FileSystem,
join: (first: string, ...rest: string[]) => string,
from: string,
to: string,
): Effect.Effect<void, PlatformError.PlatformError> =>
forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
[{ sourcePath: from, targetPath: to }],
({ sourcePath, targetPath }) =>
Effect.gen(function* () {
const info = yield* fs.stat(sourcePath);
if (info.type === "Directory") {
yield* fs.makeDirectory(targetPath, { recursive: true });
const entries = yield* fs.readDirectory(sourcePath);
return entries.map((entry) => ({
sourcePath: join(sourcePath, entry),
targetPath: join(targetPath, entry),
}));
}
if (info.type === "File") {
// Read and write stay in the same bounded task, so at most eight file
// buffers can be retained while their writes complete.
const bytes = yield* fs.readFile(sourcePath);
yield* fs.writeFile(targetPath, bytes);
}
return [];
}),
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fs = yield* FileSystem.FileSystem;
const join = environment.path.join;
const serverRoot = environment.serverRoot;
const needsExtraction = environment.isPackaged && environment.platform === "win32";
const treeRoot = join(environment.stateDir, "wsl-server-tree");
const version = environment.appVersion;
const versionDir = join(treeRoot, version);
// Remove sibling trees left behind by previous app versions (and aborted
// extractions). Best-effort: a locked file must not block the backend.
const sweepStale = Effect.gen(function* () {
const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
yield* Effect.forEach(
entries.filter((entry) => entry !== version),
(entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
{ discard: true },
);
});
const markerMatches = Effect.gen(function* () {
const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
const marker = yield* decodeMarker(raw);
return marker.version === version;
}).pipe(Effect.orElseSucceed(() => false));
const extract = Effect.gen(function* () {
yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
yield* fs.makeDirectory(treeRoot, { recursive: true });
// Keep the temporary tree beside the target so rename is atomic. Cleanup
// is owned explicitly because a scoped temp-directory finalizer treats the
// successful rename (and therefore missing original path) as an error.
const partialDir = yield* fs.makeTempDirectory({
directory: treeRoot,
prefix: `.${version}.extract-`,
});
yield* Effect.gen(function* () {
yield* copyTree(fs, join, serverRoot, partialDir);
const markerJson = yield* encodeMarker({ version });
yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
// The marker is written before the rename, so a directory named after
// the version is complete by construction.
yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
yield* fs.rename(partialDir, versionDir);
}).pipe(
Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
);
yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
}).pipe(
Effect.mapError(
(cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
),
);
// Serialize concurrent ensure calls (backend restarts can overlap): the
// first caller extracts, later callers see the marker and reuse the tree.
const gate = yield* Semaphore.make(1);
const ensure: Effect.Effect<WslServerTreeResult> = gate
.withPermits(1)(
Effect.gen(function* () {
if (!needsExtraction) {
return { ok: true, root: serverRoot } as const;
}
if (yield* markerMatches) {
yield* sweepStale;
return { ok: true, root: versionDir } as const;
}
const result = yield* extract.pipe(
Effect.map(() => ({ ok: true, root: versionDir }) as const),
// Retryable: transient antivirus locks and slow disks are the common
// causes, and the backend manager already bounds preflight retries.
Effect.catch((error) =>
Effect.succeed({
ok: false,
reason: `WSL server files could not be extracted to ${versionDir}: ${
error.cause instanceof Error ? error.cause.message : String(error.cause)
}`,
fatal: false,
} as const),
),
);
if (result.ok) {
yield* sweepStale;
}
return result;
}),
)
.pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
return DesktopWslServerTree.of({ ensure });
});
export const layer = Layer.effect(DesktopWslServerTree, make);
export interface DesktopWslServerTreeTestStub {
readonly result?: WslServerTreeResult;
}
export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
Layer.effect(
DesktopWslServerTree,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return DesktopWslServerTree.of({
ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
});
}),
);
@@ -252,6 +252,9 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
val textLength = editor.text?.length ?: 0
val safeStart = start.coerceIn(0, textLength)
val safeEnd = end.coerceIn(0, textLength)
// Re-applying an unchanged selection resets the keyboard's suggestion
// state, so a no-op assignment must be skipped.
if (editor.selectionStart == safeStart && editor.selectionEnd == safeEnd) return
editor.setSelection(safeStart, safeEnd)
}
@@ -281,6 +284,10 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
)
private fun emitSelectionChange(start: Int, end: Int) {
// Caret moves advance the revision counter like text edits do: a
// controlled payload computed before this move is stale and must fail the
// revision guard instead of yanking the caret back mid-typing.
nativeEventCount += 1
onComposerSelectionChange(
mapOf(
"value" to editor.text.toString(),
@@ -489,6 +489,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
return
}
restoreBaseTypingAttributes()
// UIKit moves the selection before textViewDidChange runs. Emitting here
// would pair the post-edit text with a pre-edit revision counter, so let
// the change event that follows carry both; only pure caret moves emit.
guard self.textView.serializedText() == value else {
return
}
emitSelection()
}
@@ -774,8 +780,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
private func emitSelection() {
// Caret moves advance the revision counter like text edits do: a
// controlled payload computed before this move is stale and must fail the
// revision guard instead of yanking the caret back mid-typing.
let currentValue = textView.serializedText()
let selection = sourceSelection()
nativeEventCount += 1
onComposerSelectionChange([
"value": currentValue,
"selection": ["start": selection.start, "end": selection.end],
@@ -817,10 +827,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
NSMaxRange(nextRange) <= textView.attributedText.length else {
return
}
self.requestedSelection = nil
// Programmatically assigning selectedRange resets the keyboard's
// autocorrect and predictive-text context even when the range is
// unchanged, so a no-op assignment must be skipped.
guard !NSEqualRanges(nextRange, textView.selectedRange) else {
return
}
isApplyingControlledValue = true
textView.selectedRange = nextRange
isApplyingControlledValue = false
self.requestedSelection = nil
}
private func updatePlaceholderVisibility() {
@@ -20,12 +20,15 @@ import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
import type { Preferences } from "../../persistence/mobile-preferences";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
armAgentAwarenessLiveActivityForLocalWork,
getAgentAwarenessRegistrationStatus,
mergeAgentAwarenessRegistrationPreferences,
refreshActiveLiveActivityRemoteRegistration,
@@ -43,6 +46,13 @@ import * as Notifications from "expo-notifications";
const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []),
start: vi.fn(() => ({})),
}));
const environmentConfigsMock = vi.hoisted(() => ({
configs: new Map<
string,
{ environment: { capabilities: { agentActivityPublishing?: boolean } } }
>(),
}));
const backgroundRuntime = vi.hoisted(() => ({
pending: [] as Array<{
@@ -77,9 +87,22 @@ vi.mock("expo-widgets", () => ({
vi.mock("../../widgets/AgentActivity", () => ({
default: {
getInstances: widgetMocks.getInstances,
start: widgetMocks.start,
},
}));
// The state modules pull the whole connection stack (and native expo modules)
// into the import graph; the arming gate only needs the configs map.
vi.mock("../../state/atom-registry", () => ({
appAtomRegistry: {
get: () => environmentConfigsMock.configs,
},
}));
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
}));
vi.mock("expo-notifications", () => ({
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
@@ -227,6 +250,8 @@ describe("makeRelayDeviceRegistrationRequest", () => {
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
widgetMocks.start.mockClear();
environmentConfigsMock.configs.clear();
});
it("preserves disabled Live Activity preferences in relay registrations", () => {
@@ -856,4 +881,55 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
},
);
it("skips the Live Activity seed when the environment reports publishing disabled", async () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
environmentConfigsMock.configs.set("env-1", {
environment: { capabilities: { agentActivityPublishing: false } },
});
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-1" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).not.toHaveBeenCalled();
});
it("seeds the Live Activity for publishing and pre-capability environments", async () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
environmentConfigsMock.configs.set("env-publishing", {
environment: { capabilities: { agentActivityPublishing: true } },
});
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-publishing" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
// An environment without the capability may run an older server that
// still publishes; only an explicit false skips the seed.
widgetMocks.start.mockClear();
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-pre-capability" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
});
});
@@ -20,6 +20,8 @@ import {
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import type { Preferences } from "../../persistence/mobile-preferences";
import {
clearAgentAwarenessRegistrationRecord,
@@ -448,18 +450,38 @@ function unregisterDeviceWithRelay(input: {
});
}
// The environment descriptor advertises whether agent-activity publishes
// currently leave that server (`capabilities.agentActivityPublishing`). Only
// an explicit false skips the seed card: older servers omit the capability
// but may still publish.
function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.agentActivityPublishing !== false
);
}
// Arms the lock-screen card the moment the user starts agent work from this
// phone, while the app is still foregrounded and the fresh activity's token
// can be registered immediately. The seeded row is a best-effort placeholder;
// the relay's registration replay repaints it with the authoritative
// aggregate within seconds. No-ops when a card is already armed.
// aggregate within seconds. No-ops when a card is already armed, and skips
// environments that report publishing disabled — the seed would sit on
// "Connecting" forever with no update ever arriving to repaint or end it.
export function armAgentAwarenessLiveActivityForLocalWork(input: {
readonly environmentId: EnvironmentId;
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
return;
}
if (!environmentPublishesAgentActivity(input.environmentId)) {
logRegistrationDebug("live activity arming skipped; environment does not publish", {
environmentId: input.environmentId,
});
return;
}
void loadPreferences()
.catch(() => null)
.then((preferences) => {
@@ -8,6 +8,7 @@ import { AppText as Text } from "../../components/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import {
buildFileTree,
@@ -123,7 +124,7 @@ export function FileTreeBrowser(props: {
const insets = useSafeAreaInsets();
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
// observed adjustedContentInset bottom (~102) seen in the native trace.
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0;
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + IOS_NAV_BAR_HEIGHT : 0;
const iconColor = String(useThemeColor("--color-icon-muted"));
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
const controlledSelectedPathRef = useRef(controlledSelectedPath);
@@ -11,7 +11,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
import { checkForAppUpdateOnLaunch, startAppUpdateForegroundRecheck } from "../updates/app-updates";
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
@@ -34,6 +34,7 @@ export function HomeRouteScreen() {
useEffect(() => {
void checkForAppUpdateOnLaunch();
startAppUpdateForegroundRecheck();
}, []);
const {
@@ -95,15 +95,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
const pasted = await convertPastedImagesToAttachments({
const images = await convertPastedImagesToAttachments({
uris,
existingCount: attachments.length,
});
if (pasted.images.length > 0) {
setAttachments((current) => [...current, ...pasted.images]);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
if (images.length > 0) {
setAttachments((current) => [...current, ...images]);
}
} catch (error) {
console.error("[review comment] error converting pasted images", error);
@@ -39,6 +39,7 @@ import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThemeColor } from "../../lib/useThemeColor";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import {
@@ -277,9 +278,11 @@ function ReviewFileNavigator({
// The nested native header is translucent; start the list below it so
// the scroll-edge effect can sample the content (same treatment as
// FileTreeBrowser in the Files pane).
paddingTop: Platform.OS === "ios" ? insets.top + 44 + 8 : 8,
paddingTop: Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT + 8 : 8,
}}
scrollIndicatorInsets={Platform.OS === "ios" ? { top: insets.top + 44 } : undefined}
scrollIndicatorInsets={
Platform.OS === "ios" ? { top: insets.top + IOS_NAV_BAR_HEIGHT } : undefined
}
renderItem={renderFile}
/>
);
@@ -608,7 +608,10 @@ function AppSettingsSection() {
if (updateInFlight.current) return;
updateInFlight.current = true;
try {
// The user asked for this restart by tapping the version row, so it may
// apply immediately instead of prompting.
await runAppUpdateCheck({
applyMode: "immediate",
onFailure: (message) => Alert.alert("Update failed", message),
onStateChange: setUpdateState,
});
@@ -631,11 +634,15 @@ function AppSettingsSection() {
? "Checking…"
: updateState === "downloading"
? "Downloading…"
: updateState === "restarting"
? "Restarting…"
: updateState === "current"
? "Up to date"
: null;
: // "ready" appears only when this check joined an in-flight background-mode
// check; that download installs at the next backgrounding.
updateState === "ready"
? "Update ready"
: updateState === "restarting"
? "Restarting…"
: updateState === "current"
? "Up to date"
: null;
const versionRow = (
<View className="flex-row items-center gap-4 p-4">
@@ -7,11 +7,13 @@ import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanim
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useThemeColor } from "../../lib/useThemeColor";
import type { GitActionProgress } from "../../state/use-vcs-action-state";
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
const OVERLAY_TOP_GAP = 8;
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
export function GitActionProgressOverlay(props: {
@@ -52,7 +54,7 @@ export function GitActionProgressOverlay(props: {
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
className="absolute inset-x-3 z-[100]"
style={{ top: insets.top + 48 }}
style={{ top: insets.top + APP_BAR_HEIGHT + OVERLAY_TOP_GAP }}
pointerEvents="box-none"
>
<Pressable onPress={handlePress}>
@@ -54,10 +54,7 @@ import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import {
setPendingConnectionError,
useRemoteConnectionStatus,
} from "../../state/use-remote-environment-registry";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
@@ -610,23 +607,17 @@ export function NewTaskDraftScreen(props: {
if (result.images.length > 0) {
flow.appendAttachments(result.images);
}
if (result.error) {
setPendingConnectionError(result.error);
}
}
const handleNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
try {
const pasted = await convertPastedImagesToAttachments({
const images = await convertPastedImagesToAttachments({
uris,
existingCount: flow.attachments.length,
});
if (pasted.images.length > 0) {
flow.appendAttachments(pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
if (images.length > 0) {
flow.appendAttachments(images);
}
} catch (error) {
console.error("[native paste] error converting images", error);
@@ -718,6 +709,7 @@ export function NewTaskDraftScreen(props: {
// -only Activity start. If creation fails, the token registration's replay
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: selectedProject.environmentId,
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
projectTitle: selectedProject.title,
});
@@ -105,7 +105,6 @@ export interface ThreadComposerProps {
readonly selectedThread: OrchestrationThreadShell;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectCwd: string | null;
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
@@ -327,9 +326,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.selectedThread.session?.status === "starting";
const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
? "Queue"
: "Send";
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const connectionStatus = composerConnectionStatus({
@@ -541,6 +538,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// after the send so its preference read and native Activity start don't
// contend with the queued-message feedback on the tap frame.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: props.environmentId,
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
@@ -57,6 +57,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { scopedThreadKey } from "../../lib/scopedEntities";
import type {
PendingApproval,
@@ -100,7 +101,6 @@ export interface ThreadDetailScreenProps {
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -249,7 +249,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -726,7 +726,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
@@ -47,6 +47,7 @@ import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { useFontFamily } from "../../lib/useFontFamily";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
@@ -1396,7 +1397,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const userBubbleMaxWidth = contentWidth * 0.85;
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
const insets = useSafeAreaInsets();
const topContentInset = props.contentTopInset ?? insets.top + 44;
const topContentInset = props.contentTopInset ?? insets.top + IOS_NAV_BAR_HEIGHT;
const bottomContentInset = props.contentBottomInset ?? 18;
const usesNativeAutomaticInsets =
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
@@ -1409,7 +1410,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// header-providing screen) and fall back to the standard iOS bar height.
const navigationHeaderHeight = useContext(HeaderHeightContext);
const anchorTopInset = usesNativeAutomaticInsets
? navigationHeaderHeight || insets.top + 44
? navigationHeaderHeight || insets.top + IOS_NAV_BAR_HEIGHT
: topContentInset;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
@@ -96,6 +96,13 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
return value ?? null;
}
function timestampCovers(timestamp: string | undefined, target: string): boolean {
if (timestamp === undefined) return false;
const timestampMs = Date.parse(timestamp);
const targetMs = Date.parse(target);
return Number.isFinite(timestampMs) && Number.isFinite(targetMs) && timestampMs >= targetMs;
}
function OpeningThreadLoadingScreen() {
return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
}
@@ -280,9 +287,45 @@ function ThreadRouteContent(
}, [props.renderInspector]),
);
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false });
const selectedThreadEnvironmentId = selectedThread?.environmentId ?? null;
const selectedThreadId = selectedThread?.id ?? null;
const selectedThreadCompletedAt = selectedThread?.latestTurn?.completedAt ?? null;
const selectedThreadViewedAtRef = useRef(selectedThread?.viewedAt);
selectedThreadViewedAtRef.current = selectedThread?.viewedAt;
const supportsThreadViewState = serverConfig?.environment.capabilities.threadViewState === true;
useFocusEffect(
useCallback(() => {
if (
selectedThreadEnvironmentId === null ||
selectedThreadId === null ||
selectedThreadCompletedAt === null ||
!supportsThreadViewState
) {
return;
}
if (timestampCovers(selectedThreadViewedAtRef.current, selectedThreadCompletedAt)) {
return;
}
void viewThread({
environmentId: selectedThreadEnvironmentId,
input: {
threadId: selectedThreadId,
viewedThrough: selectedThreadCompletedAt,
},
});
}, [
selectedThreadCompletedAt,
selectedThreadEnvironmentId,
selectedThreadId,
supportsThreadViewState,
viewThread,
]),
);
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
@@ -758,7 +801,6 @@ function ThreadRouteContent(
detailDeleted: selectedThreadDetailState.status === "deleted",
connectionState: routeConnectionState,
});
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const renderThreadRouteBody = (showActionControls: boolean) => (
<>
<ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
@@ -785,7 +827,6 @@ function ThreadRouteContent(
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
loadEarlier={loadEarlierTurns}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
@@ -14,10 +14,7 @@ import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import {
droppedAttachmentsWarning,
type DraftComposerImageAttachment,
} from "../../lib/composerImages";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
import { randomHex } from "../../lib/uuid";
@@ -87,11 +84,7 @@ export function useCreateProjectThread() {
);
return AsyncResult.failure(result.cause);
}
// Legacy drafts can still carry data-url images. `thread.turn.start` now
// only accepts uploaded attachment ids, which mobile cannot mint yet, so
// those images are dropped and the user is told rather than left to
// assume they were sent. Null clears the banner when there are none.
setPendingConnectionError(droppedAttachmentsWarning(input.initialAttachments.length));
setPendingConnectionError(null);
return mapAtomCommandResult(result, () =>
scopeThreadRef(input.project.environmentId, threadId),
@@ -1,11 +1,15 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
createAppUpdateDeferral,
createAppUpdateLaunchCheck,
FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
registerHiddenUpdateTap,
runAppUpdateCheck,
shouldRecheckAppUpdateOnForeground,
type AppUpdateCheckState,
type AppUpdateClient,
type AppUpdateEnvironment,
} from "./app-updates";
vi.mock("expo-updates", () => ({
@@ -31,6 +35,41 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
};
}
function makeUpdateEnvironment(overrides: Partial<AppUpdateEnvironment> = {}): {
readonly backgroundCallbacks: Array<() => void>;
readonly environment: AppUpdateEnvironment;
readonly foregroundStayCallbacks: Array<() => void>;
} {
const backgroundCallbacks: Array<() => void> = [];
const foregroundStayCallbacks: Array<() => void> = [];
return {
backgroundCallbacks,
foregroundStayCallbacks,
environment: {
confirmInstallNow: vi.fn(async () => true),
flushPendingWrites: vi.fn(async () => {}),
isSafeToRestartInBackground: vi.fn(async () => true),
onNextBackground: vi.fn((apply: () => void, _includeCurrent: boolean) => {
backgroundCallbacks.push(apply);
}),
onForegroundStay: vi.fn((apply: () => void) => {
foregroundStayCallbacks.push(apply);
}),
...overrides,
},
};
}
function makeAvailableUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
return makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: true,
isRollBackToEmbedded: false,
})),
...overrides,
});
}
describe("runAppUpdateCheck", () => {
it("does nothing while running from the Metro development server", async () => {
vi.stubGlobal("__DEV__", true);
@@ -45,23 +84,313 @@ describe("runAppUpdateCheck", () => {
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: true,
isRollBackToEmbedded: false,
})),
});
it("downloads silently and installs at the next backgrounding", async () => {
const client = makeAvailableUpdateClient();
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
await runAppUpdateCheck({
client,
deferral,
environment,
onStateChange: (state) => states.push(state),
});
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(states).toEqual(["checking", "downloading", "ready"]);
expect(deferral.pendingInstall).toBe(true);
expect(backgroundCallbacks).toHaveLength(1);
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
expect(environment.flushPendingWrites).toHaveBeenCalled();
});
it("flushes pending writes before restarting", async () => {
const client = makeAvailableUpdateClient();
const { environment } = makeUpdateEnvironment();
await runAppUpdateCheck({
applyMode: "immediate",
client,
deferral: createAppUpdateDeferral(),
environment,
});
const flushOrder = vi.mocked(environment.flushPendingWrites).mock.invocationCallOrder[0]!;
const reloadOrder = vi.mocked(client.reloadAsync).mock.invocationCallOrder[0]!;
expect(flushOrder).toBeLessThan(reloadOrder);
});
it("prompts once the app has stayed foregrounded with the download waiting", async () => {
const client = makeAvailableUpdateClient();
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
expect(foregroundStayCallbacks).toHaveLength(1);
foregroundStayCallbacks[0]!();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
expect(environment.confirmInstallNow).toHaveBeenCalledOnce();
expect(environment.flushPendingWrites).toHaveBeenCalled();
});
it("keeps the background install armed when the foreground prompt is declined", async () => {
const client = makeAvailableUpdateClient();
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
confirmInstallNow: vi.fn(async () => false),
});
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
foregroundStayCallbacks[0]!();
await vi.waitFor(() => expect(environment.confirmInstallNow).toHaveBeenCalledOnce());
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(deferral.pendingInstall).toBe(true);
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
});
it("skips the foreground prompt once the install is no longer pending", async () => {
const client = makeAvailableUpdateClient();
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
// A failed deferred reload resets the deferral before the stay fires.
deferral.pendingInstall = false;
foregroundStayCallbacks[0]!();
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
expect(client.reloadAsync).not.toHaveBeenCalled();
});
it("re-arms instead of restarting when the app is no longer safely backgrounded", async () => {
const client = makeAvailableUpdateClient();
const safe = vi.fn(async () => false);
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
isSafeToRestartInBackground: safe,
});
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
expect(backgroundCallbacks).toHaveLength(1);
// Arming may fire for an already-backgrounded app…
expect(vi.mocked(environment.onNextBackground).mock.calls[0]![1]).toBe(true);
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(deferral.pendingInstall).toBe(true);
// …but a re-arm must wait for a fresh transition, or an unsafe attempt
// would retry in a tight loop within the same background session.
expect(vi.mocked(environment.onNextBackground).mock.calls[1]![1]).toBe(false);
safe.mockResolvedValue(true);
backgroundCallbacks[1]!();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
});
it("resets the deferral when the deferred restart fails", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeAvailableUpdateClient({
reloadAsync: vi.fn(async () => {
throw new Error("reload rejected");
}),
});
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(deferral.pendingInstall).toBe(false));
reportError.mockRestore();
});
it("arms the deferred install once across repeated checks", async () => {
const client = makeAvailableUpdateClient();
const { environment } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
await runAppUpdateCheck({ client, deferral, environment });
expect(environment.onNextBackground).toHaveBeenCalledOnce();
expect(environment.onForegroundStay).toHaveBeenCalledOnce();
});
it("restarts into an already-downloaded update when the user asks to install", async () => {
const client = makeUpdateClient();
const { environment } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
deferral.pendingInstall = true;
await runAppUpdateCheck({ applyMode: "immediate", client, deferral, environment });
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
expect(client.reloadAsync).toHaveBeenCalledOnce();
});
it("honors an immediate request that joined an in-flight background check", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((resolve) => {
resolveCheck = resolve;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const { environment } = makeUpdateEnvironment();
const deferral = createAppUpdateDeferral();
const backgroundCheck = runAppUpdateCheck({ client, deferral, environment });
const manualCheck = runAppUpdateCheck({
applyMode: "immediate",
client,
deferral,
environment,
});
resolveCheck({ isAvailable: true, isRollBackToEmbedded: false });
await Promise.all([backgroundCheck, manualCheck]);
// The coalesced background check deferred the download, but the manual
// caller explicitly asked to install, so the restart happens anyway.
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(client.reloadAsync).toHaveBeenCalledOnce();
});
it("runs a single restart when the deferred install races the foreground prompt", async () => {
const client = makeAvailableUpdateClient();
let releaseFlush!: () => void;
const blockedFlush = new Promise<void>((resolve) => {
releaseFlush = resolve;
});
const flushPendingWrites = vi.fn(async (): Promise<void> => {});
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
flushPendingWrites,
});
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
flushPendingWrites.mockReturnValue(blockedFlush);
// The deferred install starts and blocks on its flush; the foreground
// prompt firing in that window must not begin a second restart.
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(flushPendingWrites).toHaveBeenCalledOnce());
foregroundStayCallbacks[0]!();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
releaseFlush();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
});
it("holds the deferred restart and re-arms when the pre-restart flush fails", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeAvailableUpdateClient();
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
flushPendingWrites: vi.fn(async () => {
throw new Error("disk full");
}),
});
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(deferral.pendingInstall).toBe(true);
reportError.mockRestore();
});
it("restarts without prompting when the caller asked for an immediate install", async () => {
const client = makeAvailableUpdateClient();
const { environment } = makeUpdateEnvironment();
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
applyMode: "immediate",
client,
deferral: createAppUpdateDeferral(),
environment,
onStateChange: (state) => states.push(state),
});
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
expect(client.reloadAsync).toHaveBeenCalledOnce();
expect(states).toEqual(["checking", "downloading", "restarting"]);
});
it("holds an automatic rollback restart when the flush fails and re-arms it", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: false,
isRollBackToEmbedded: true,
})),
fetchUpdateAsync: vi.fn(async () => ({
isNew: false,
isRollBackToEmbedded: true,
})),
});
const flushPendingWrites = vi.fn(async (): Promise<void> => {
throw new Error("storage unavailable");
});
const { backgroundCallbacks, environment } = makeUpdateEnvironment({ flushPendingWrites });
const deferral = createAppUpdateDeferral();
await runAppUpdateCheck({ client, deferral, environment });
// Nobody asked for this restart, so it must not discard the state it
// failed to land; the rollback waits armed for the next backgrounding.
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(deferral.pendingInstall).toBe(true);
expect(backgroundCallbacks).toHaveLength(1);
flushPendingWrites.mockResolvedValue(undefined);
backgroundCallbacks[0]!();
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
reportError.mockRestore();
});
it("still restarts a user-requested install when the flush fails", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeAvailableUpdateClient();
const { environment } = makeUpdateEnvironment({
flushPendingWrites: vi.fn(async () => {
throw new Error("storage unavailable");
}),
});
await runAppUpdateCheck({
applyMode: "immediate",
client,
deferral: createAppUpdateDeferral(),
environment,
});
expect(client.reloadAsync).toHaveBeenCalledOnce();
reportError.mockRestore();
});
it("restarts into the embedded bundle for a rollback directive", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
@@ -73,10 +402,13 @@ describe("runAppUpdateCheck", () => {
isRollBackToEmbedded: true,
})),
});
const { environment } = makeUpdateEnvironment();
await runAppUpdateCheck({ client });
await runAppUpdateCheck({ client, deferral: createAppUpdateDeferral(), environment });
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
// A rollback pulls a broken bundle, so it never waits on the prompt.
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
expect(client.reloadAsync).toHaveBeenCalledOnce();
});
@@ -276,6 +608,36 @@ describe("createAppUpdateLaunchCheck", () => {
});
});
describe("shouldRecheckAppUpdateOnForeground", () => {
it("requires a meaningful background gap", () => {
expect(shouldRecheckAppUpdateOnForeground(null, 100_000, false)).toBe(false);
expect(
shouldRecheckAppUpdateOnForeground(
100_000,
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS - 1,
false,
),
).toBe(false);
expect(
shouldRecheckAppUpdateOnForeground(
100_000,
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
false,
),
).toBe(true);
});
it("stays quiet while a downloaded update waits for its install", () => {
expect(
shouldRecheckAppUpdateOnForeground(
100_000,
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
true,
),
).toBe(false);
});
});
describe("registerHiddenUpdateTap", () => {
it("unlocks the manual check on the fifth tap", () => {
let count = 0;
+378 -1
View File
@@ -8,7 +8,13 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
export type AppUpdateCheckState =
| "idle"
| "checking"
| "downloading"
| "ready"
| "restarting"
| "current";
export interface AppUpdateClient {
readonly isEnabled: boolean;
@@ -23,8 +29,70 @@ export interface AppUpdateClient {
readonly reloadAsync: () => Promise<void>;
}
/**
* The pieces of the app the update flow has to coordinate with before it may
* tear down the JavaScript runtime. Injectable so the flow stays unit-testable.
*/
export interface AppUpdateEnvironment {
/** Asks the user to install the waiting update now; `false` keeps it deferred. */
readonly confirmInstallNow: () => Promise<boolean>;
/**
* Lands persisted state (drafts, outbox) before the restart. Rejects when a
* write failed, so a silent restart can hold off instead of dropping the
* unsaved in-memory state.
*/
readonly flushPendingWrites: () => Promise<void>;
/**
* Whether a deferred restart may fire right now: the app must still be
* backgrounded (flush latency or an iOS suspend can push the continuation
* into the next foreground session) and not merely paused behind an
* app-initiated handoff like the Android image picker.
*/
readonly isSafeToRestartInBackground: () => Promise<boolean>;
/**
* Runs `apply` the next time the app enters the background. With
* `includeCurrent`, an app that is already backgrounded fires immediately
* (so a backgrounding that raced module load is not missed); without it,
* only a future transition fires, so an attempt that already failed in the
* current background session cannot retry in a tight loop.
*/
readonly onNextBackground: (apply: () => void, includeCurrent: boolean) => void;
/**
* Runs `apply` once the app has stayed foregrounded for the whole prompt
* window — the signal that a deferred install has had no backgrounding to
* ride on.
*/
readonly onForegroundStay: (apply: () => void) => void;
}
/** Tracks a downloaded update waiting for a safe moment to install. */
export interface AppUpdateDeferral {
pendingInstall: boolean;
/**
* Claimed by whichever restart sequence (deferred backgrounding, foreground
* prompt, manual install) starts first, so racing paths cannot tear down
* the runtime twice.
*/
installInProgress: boolean;
}
export function createAppUpdateDeferral(): AppUpdateDeferral {
return { pendingInstall: false, installInProgress: false };
}
const appUpdateDeferral = createAppUpdateDeferral();
interface AppUpdateCheckOptions {
/**
* "background" (default) installs silently at the next backgrounding,
* asking only if the app then stays foregrounded so long that the install
* never gets its chance. "immediate" restarts as soon as the download
* lands — reserved for flows where the user explicitly requested the update.
*/
readonly applyMode?: "background" | "immediate";
readonly client?: AppUpdateClient;
readonly deferral?: AppUpdateDeferral;
readonly environment?: AppUpdateEnvironment;
readonly onFailure?: (message: string) => void;
readonly onStateChange?: (state: AppUpdateCheckState) => void;
}
@@ -86,6 +154,15 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
// A background-mode check in flight may have deferred the download this
// caller explicitly asked to install; honor the explicit request now.
if (options.applyMode === "immediate") {
const deferral = options.deferral ?? appUpdateDeferral;
if (deferral.pendingInstall) {
const environment = options.environment ?? defaultAppUpdateEnvironment;
await installPendingAppUpdate(client, environment, deferral, options);
}
}
return;
}
@@ -109,6 +186,9 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
appUpdateCheckInFlight = inFlight;
const execution = performAppUpdateCheck(client, {
applyMode: options.applyMode,
deferral: options.deferral,
environment: options.environment,
onFailure: (message) => {
progress.failure = message;
notifyListeners(failureListeners, message);
@@ -175,6 +255,15 @@ async function performAppUpdateCheck(
options: AppUpdateCheckOptions,
): Promise<void> {
const setState = options.onStateChange ?? (() => {});
const environment = options.environment ?? defaultAppUpdateEnvironment;
const deferral = options.deferral ?? appUpdateDeferral;
// The user explicitly asked to install and a previous check has already
// downloaded the update; restart into it without another network round trip.
if (options.applyMode === "immediate" && deferral.pendingInstall) {
await installPendingAppUpdate(client, environment, deferral, options);
return;
}
setState("checking");
const check = await settlePromise(() => client.checkForUpdateAsync());
@@ -203,14 +292,252 @@ async function performAppUpdateCheck(
return;
}
// A rollback directive exists to pull a broken bundle; never hold it
// behind a prompt or a deferred install.
if (options.applyMode === "immediate" || fetched.value.isRollBackToEmbedded) {
const outcome = await installAppUpdate(
client,
environment,
deferral,
options,
options.applyMode === "immediate",
);
if (outcome === "flush-failed") {
// Only reachable for an automatic rollback: keep the state-bearing
// runtime alive and retry like a deferred install. The fetched rollback
// still applies at the next cold start regardless.
setState("ready");
armDeferredAppUpdateInstall(client, environment, deferral);
}
return;
}
setState("ready");
armDeferredAppUpdateInstall(client, environment, deferral);
}
type AppUpdateInstallOutcome = "installed" | "flush-failed" | "restart-failed";
/**
* Restarting mid-session while native surfaces are mounted is the crashiest
* moment expo-updates has, so the restart flushes persistence first and, by
* default, waits for a backgrounding — where nothing is rendering and the
* teardown is invisible. Only a restart the user explicitly asked for may
* proceed over a failed flush; an automatic one aborts with "flush-failed"
* so unsaved state is never silently discarded.
*/
async function installAppUpdate(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
options: AppUpdateCheckOptions,
userRequested: boolean,
): Promise<AppUpdateInstallOutcome> {
// A concurrent install sequence already owns the restart.
if (deferral.installInProgress) return "installed";
deferral.installInProgress = true;
const setState = options.onStateChange ?? (() => {});
setState("restarting");
const flushed = await settlePromise(() => environment.flushPendingWrites());
if (flushed._tag === "Failure") {
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
if (!userRequested) {
deferral.installInProgress = false;
return "flush-failed";
}
}
const reloaded = await settlePromise(() => client.reloadAsync());
if (reloaded._tag === "Failure") {
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
setState("idle");
deferral.installInProgress = false;
return "restart-failed";
}
return "installed";
}
/** Restarts into an already-downloaded update at the user's request. */
async function installPendingAppUpdate(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
options: AppUpdateCheckOptions,
): Promise<void> {
const outcome = await installAppUpdate(client, environment, deferral, options, true);
if (outcome === "restart-failed") {
// Let later checks re-arm the install; the downloaded update still
// applies at the next cold start regardless.
deferral.pendingInstall = false;
}
}
function armDeferredAppUpdateInstall(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
): void {
if (deferral.pendingInstall) return;
deferral.pendingInstall = true;
scheduleDeferredAppUpdateInstall(client, environment, deferral, true);
environment.onForegroundStay(() => {
void promptDeferredAppUpdateInstall(client, environment, deferral);
});
}
/**
* A deferred install normally rides the next backgrounding, but a session that
* never leaves the foreground would sit on the download forever. Only then is
* the user asked, and declining simply leaves the background install armed.
*/
async function promptDeferredAppUpdateInstall(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
): Promise<void> {
if (!deferral.pendingInstall || deferral.installInProgress) return;
const installNow = await settlePromise(() => environment.confirmInstallNow());
if (installNow._tag !== "Success" || !installNow.value) return;
// A backgrounding while the alert was up may have started the deferred
// restart already; the stale accept must not start a second one.
if (!deferral.pendingInstall || deferral.installInProgress) return;
await installPendingAppUpdate(client, environment, deferral, {});
}
function scheduleDeferredAppUpdateInstall(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
includeCurrent: boolean,
): void {
environment.onNextBackground(() => {
void applyDeferredAppUpdateInstall(client, environment, deferral);
}, includeCurrent);
}
async function applyDeferredAppUpdateInstall(
client: AppUpdateClient,
environment: AppUpdateEnvironment,
deferral: AppUpdateDeferral,
): Promise<void> {
if (!deferral.pendingInstall || deferral.installInProgress) return;
deferral.installInProgress = true;
const flushed = await settlePromise(() => environment.flushPendingWrites());
const safe = await settlePromise(() => environment.isSafeToRestartInBackground());
if (flushed._tag === "Failure" || safe._tag !== "Success" || !safe.value) {
if (flushed._tag === "Failure") {
// Nothing is lost yet: keep the state-bearing runtime alive and retry
// the flush at the next backgrounding instead of restarting over it.
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
}
deferral.installInProgress = false;
// This attempt already ran in the current background session; retrying
// before a fresh transition would just loop over the same failure.
scheduleDeferredAppUpdateInstall(client, environment, deferral, false);
return;
}
const reloaded = await settlePromise(() => client.reloadAsync());
if (reloaded._tag === "Failure") {
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", undefined);
deferral.installInProgress = false;
// Let later checks re-arm the install; the downloaded update still
// applies at the next cold start regardless.
deferral.pendingInstall = false;
}
}
async function defaultConfirmInstallNow(): Promise<boolean> {
const { Alert } = await import("react-native");
return new Promise<boolean>((resolve) => {
Alert.alert(
"Update ready",
"A new version has been downloaded and installs automatically the next time you leave the app. Install it now instead?",
[
{ onPress: () => resolve(false), style: "cancel", text: "Later" },
{ onPress: () => resolve(true), text: "Install Now" },
],
{ cancelable: true, onDismiss: () => resolve(false) },
);
});
}
async function defaultFlushPendingWrites(): Promise<void> {
// Attempt every flush before surfacing the first failure, so one broken
// store cannot keep the others from landing.
const results = await Promise.allSettled([
import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
]);
const failed = results.find(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (failed) throw failed.reason;
}
async function defaultIsSafeToRestartInBackground(): Promise<boolean> {
const { isForegroundHandoffActive } = await import("../../lib/foreground-handoff");
if (isForegroundHandoffActive()) return false;
const { AppState } = await import("react-native");
return AppState.currentState === "background";
}
function defaultOnNextBackground(apply: () => void, includeCurrent: boolean): void {
void import("react-native").then(({ AppState }) => {
const subscription = AppState.addEventListener("change", (state) => {
if (state !== "background") return;
subscription.remove();
apply();
});
// The app may already have backgrounded while this module was loading;
// the listener alone would then wait a whole extra foreground cycle.
if (includeCurrent && AppState.currentState === "background") {
subscription.remove();
apply();
}
});
}
/**
* How long the app may stay foregrounded with a downloaded update before the
* install prompt appears. Long enough that most sessions background naturally
* and install silently instead.
*/
export const DEFERRED_INSTALL_PROMPT_AFTER_MS = 30 * 60 * 1000;
/**
* The window resets on every backgrounding because that is exactly when the
* deferred install gets its chance. iOS "inactive" blips (app switcher, a
* pulled-down notification shade) leave the timer running.
*/
function defaultOnForegroundStay(apply: () => void): void {
void import("react-native").then(({ AppState }) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const arm = () => {
timer ??= setTimeout(() => {
subscription.remove();
apply();
}, DEFERRED_INSTALL_PROMPT_AFTER_MS);
};
const disarm = () => {
if (timer === undefined) return;
clearTimeout(timer);
timer = undefined;
};
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") arm();
else if (state === "background") disarm();
});
if (AppState.currentState === "active") arm();
});
}
const defaultAppUpdateEnvironment: AppUpdateEnvironment = {
confirmInstallNow: defaultConfirmInstallNow,
flushPendingWrites: defaultFlushPendingWrites,
isSafeToRestartInBackground: defaultIsSafeToRestartInBackground,
onNextBackground: defaultOnNextBackground,
onForegroundStay: defaultOnForegroundStay,
};
function reportUpdateFailure(
result: AtomCommandResult<unknown, unknown>,
fallback: string,
@@ -243,3 +570,53 @@ export function createAppUpdateLaunchCheck(
}
export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
/**
* The app can stay resident for days, so a launch-only check misses updates
* published while it was in memory. Anything shorter reads as noise: brief
* app switches should not trigger network checks or an install prompt.
*/
export const FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS = 15 * 60 * 1000;
export function shouldRecheckAppUpdateOnForeground(
backgroundedAtMs: number | null,
activeAtMs: number,
pendingInstall: boolean,
): boolean {
if (pendingInstall) return false;
return (
backgroundedAtMs !== null &&
activeAtMs - backgroundedAtMs >= FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS
);
}
export function createAppUpdateForegroundRecheck(
client: AppUpdateClient = Updates,
deferral: AppUpdateDeferral = appUpdateDeferral,
): () => void {
let started = false;
return () => {
if (started || !isAppUpdateCheckAvailable(client)) return;
started = true;
void import("react-native").then(({ AppState }) => {
let backgroundedAtMs: number | null = null;
AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
}
if (state !== "active") return;
const shouldCheck = shouldRecheckAppUpdateOnForeground(
backgroundedAtMs,
Date.now(),
deferral.pendingInstall,
);
backgroundedAtMs = null;
if (shouldCheck) void runAppUpdateCheck({ client, deferral });
});
});
};
}
export const startAppUpdateForegroundRecheck = createAppUpdateForegroundRecheck();
+19
View File
@@ -0,0 +1,19 @@
import type { File } from "expo-file-system";
let tempFileSequence = 0;
/**
* Replaces a file's contents through a sibling temp file and an overwriting
* rename, so an interrupted write (app restart, process death) never leaves a
* truncated document at the final path. Each write stages through its own
* temp file so concurrent writers to the same destination cannot move or
* clobber each other's staging file mid-flight.
*/
export async function writeFileAtomically(file: File, contents: string): Promise<void> {
const { File: FileConstructor } = await import("expo-file-system");
tempFileSequence += 1;
const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
temp.create({ intermediates: true, overwrite: true });
temp.write(contents);
temp.moveSync(file, { overwrite: true });
}
+56 -26
View File
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
const files = new Map<string, { base64: string; deleted: boolean }>();
@@ -37,22 +38,33 @@ vi.mock("./uuid", () => ({
import {
convertPastedImagesToAttachments,
droppedAttachmentsWarning,
isOwnedPastedImageUri,
toUploadChatImageAttachments,
} from "./composerImages";
describe("droppedAttachmentsWarning", () => {
it("stays quiet when a message carries no legacy images", () => {
expect(droppedAttachmentsWarning(0)).toBeNull();
});
it("names how many legacy images were left behind", () => {
expect(droppedAttachmentsWarning(1)).toBe(
"1 image was not sent. Image attach needs an app update.",
);
expect(droppedAttachmentsWarning(3)).toBe(
"3 images were not sent. Image attach needs an app update.",
);
describe("toUploadChatImageAttachments", () => {
it("strips client draft id and previewUri for the startTurn wire shape", () => {
expect(
toUploadChatImageAttachments([
{
id: "client-draft-id",
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
sizeBytes: 12,
dataUrl: "data:image/png;base64,AA==",
previewUri: "file:///tmp/preview.png",
},
]),
).toEqual([
{
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
sizeBytes: 12,
dataUrl: "data:image/png;base64,AA==",
},
]);
});
});
@@ -71,24 +83,42 @@ describe("native pasted image cleanup", () => {
expect(isOwnedPastedImageUri("https://example.com/t3-composer-paste/id.png")).toBe(false);
});
// Image attach is off until mobile implements upload-on-attach, so pasted
// images produce no attachment. Temp-file cleanup must still happen.
it("attaches nothing and deletes owned temp files, leaving user files alone", async () => {
const owned =
it("converts owned files to data-backed previews and deletes the source", async () => {
const uri =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
const userOwned = "file:///private/var/mobile/photos/library.png";
files.set(owned, { base64: "aGVsbG8=", deleted: false });
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
files.set(uri, { base64: "aGVsbG8=", deleted: false });
const pasted = await convertPastedImagesToAttachments({
uris: [owned, userOwned],
const attachments = await convertPastedImagesToAttachments({
uris: [uri],
existingCount: 0,
});
expect(pasted.images).toEqual([]);
// The drop is surfaced to callers, not just logged.
expect(pasted.error).toContain("app update");
expect(files.get(owned)?.deleted).toBe(true);
expect(attachments).toEqual([
expect.objectContaining({
dataUrl: "data:image/png;base64,aGVsbG8=",
previewUri: "data:image/png;base64,aGVsbG8=",
}),
]);
expect(files.get(uri)?.deleted).toBe(true);
});
it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
const rejected =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
const overflow =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
const userOwned = "file:///private/var/mobile/photos/library.png";
files.set(rejected, { base64: "", deleted: false });
files.set(overflow, { base64: "aGVsbG8=", deleted: false });
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
await convertPastedImagesToAttachments({
uris: [rejected, overflow, userOwned],
existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
});
expect(files.get(rejected)?.deleted).toBe(true);
expect(files.get(overflow)?.deleted).toBe(true);
expect(files.get(userOwned)?.deleted).toBe(false);
});
});
+34 -68
View File
@@ -1,46 +1,30 @@
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import { estimateBase64ByteSize } from "./base64";
import { beginForegroundHandoff } from "./foreground-handoff";
import { uuidv4 } from "./uuid";
/**
* Local-only draft shape. It used to extend the contracts upload type, but
* `thread.turn.start` now carries id references to already-uploaded blobs, so
* `dataUrl` never reaches the wire and lives purely in mobile draft storage.
*/
export interface DraftComposerImageAttachment {
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
readonly id: string;
readonly previewUri: string;
readonly type: "image";
readonly name: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly dataUrl: string;
}
export const IMAGE_ATTACH_UNAVAILABLE_MESSAGE = "Image attach needs an app update.";
/**
* Copy for legacy draft/outbox images that predate the contract change and so
* cannot be sent. Returns null when there is nothing to warn about.
*/
export function droppedAttachmentsWarning(count: number): string | null {
if (count <= 0) {
return null;
}
const subject = count === 1 ? "1 image was" : `${count} images were`;
return `${subject} not sent. ${IMAGE_ATTACH_UNAVAILABLE_MESSAGE}`;
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
export function toUploadChatImageAttachments(
attachments: ReadonlyArray<DraftComposerImageAttachment>,
): ReadonlyArray<UploadChatImageAttachment> {
return attachments.map((attachment) => ({
type: attachment.type,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: attachment.dataUrl,
}));
}
/**
* Mobile has no upload-on-attach implementation yet (web shipped first), and
* the old data-url path is gone from the contract. Capture stays disabled
* until the mobile port lands; flip this back on with that change.
*/
const IMAGE_ATTACH_ENABLED: boolean = false;
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
async function loadImagePicker() {
@@ -63,10 +47,6 @@ export async function pickComposerImages(input: { readonly existingCount: number
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly error: string | null;
}> {
if (!IMAGE_ATTACH_ENABLED) {
return { images: [], error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (remainingSlots <= 0) {
return {
@@ -86,13 +66,21 @@ export async function pickComposerImages(input: { readonly existingCount: number
};
}
const result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
});
// The picker covers the Android activity, which reports the app as
// backgrounded; the guard keeps background-triggered restarts away mid-pick.
const endHandoff = beginForegroundHandoff();
let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
try {
result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
});
} finally {
endHandoff();
}
if (result.canceled) {
return {
@@ -158,7 +146,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if ((await clipboard.hasImageAsync()) && IMAGE_ATTACH_ENABLED) {
if (await clipboard.hasImageAsync()) {
if (remainingSlots <= 0) {
return {
images: [],
@@ -202,26 +190,14 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
};
}
// Reached with attach disabled even when the clipboard holds an image:
// mixed copy payloads (common on iOS) must still paste their text, with
// the image drop surfaced rather than silently swallowed.
if (await clipboard.hasStringAsync()) {
const text = await clipboard.getStringAsync();
const droppedImage = !IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync());
return {
images: [],
text: text.length > 0 ? text : null,
error: droppedImage
? IMAGE_ATTACH_UNAVAILABLE_MESSAGE
: text.length > 0
? null
: "Clipboard is empty.",
error: text.length > 0 ? null : "Clipboard is empty.",
};
}
if (!IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync())) {
// Image-only clipboard while attach is disabled.
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
return {
images: [],
@@ -267,19 +243,9 @@ export function isOwnedPastedImageUri(uri: string): boolean {
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray<string>;
readonly existingCount: number;
}): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
/** Set when pasted images were dropped; callers surface it like a pick error. */
readonly error: string | null;
}> {
}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
const { File } = await import("expo-file-system");
// Zero slots while attach is disabled: the loop below still runs so owned
// temporary paste files are deleted, but nothing is decoded or attached.
const remainingSlots = IMAGE_ATTACH_ENABLED
? PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount
: 0;
const error =
!IMAGE_ATTACH_ENABLED && input.uris.length > 0 ? IMAGE_ATTACH_UNAVAILABLE_MESSAGE : null;
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
const results: DraftComposerImageAttachment[] = [];
for (const [index, uri] of input.uris.entries()) {
@@ -320,5 +286,5 @@ export async function convertPastedImagesToAttachments(input: {
}
}
return { images: results, error };
return results;
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vite-plus/test";
import { beginForegroundHandoff, isForegroundHandoffActive } from "./foreground-handoff";
describe("foreground handoff", () => {
it("is active only while a handoff is open", () => {
expect(isForegroundHandoffActive()).toBe(false);
const end = beginForegroundHandoff();
expect(isForegroundHandoffActive()).toBe(true);
end();
expect(isForegroundHandoffActive()).toBe(false);
});
it("stays active until every overlapping handoff ends", () => {
const endFirst = beginForegroundHandoff();
const endSecond = beginForegroundHandoff();
endFirst();
expect(isForegroundHandoffActive()).toBe(true);
endSecond();
expect(isForegroundHandoffActive()).toBe(false);
});
it("tolerates an end function called twice", () => {
const endFirst = beginForegroundHandoff();
const endSecond = beginForegroundHandoff();
endFirst();
endFirst();
expect(isForegroundHandoffActive()).toBe(true);
endSecond();
expect(isForegroundHandoffActive()).toBe(false);
});
});
+22
View File
@@ -0,0 +1,22 @@
/**
* Tracks app-initiated OS-surface handoffs (image picker, auth tab, share
* sheet). Android reports the app as backgrounded while one of these covers
* the activity, so background-triggered work — like a deferred app update
* restart — has to wait them out instead of tearing down the mid-flow runtime.
*/
let activeHandoffs = 0;
/** Returns an idempotent end function; call it when the handoff resolves. */
export function beginForegroundHandoff(): () => void {
activeHandoffs += 1;
let ended = false;
return () => {
if (ended) return;
ended = true;
activeHandoffs -= 1;
};
}
export function isForegroundHandoffActive(): boolean {
return activeHandoffs > 0;
}
+12
View File
@@ -3,3 +3,15 @@ export const HOME_HORIZONTAL_INSET = 20;
/** Compensates for the tighter native sidebar title margin on iPad. */
export const IPAD_HOME_TITLE_OFFSET = 10;
/**
* Height of the native iOS navigation bar below the safe-area inset, used as
* a fallback when the measured HeaderHeightContext is unavailable.
*/
export const IOS_NAV_BAR_HEIGHT = 44;
/* Height of the app's own header chrome below the safe-area inset, on every
* platform (matches the `min-h-12` AndroidScreenHeader). Distinct from the
* 44pt native iOS navigation bar.
*/
export const APP_BAR_HEIGHT = 48;
@@ -8,7 +8,7 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import type { DraftComposerImageAttachment } from "./composerImages";
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
@@ -28,11 +28,6 @@ export interface ProjectThreadStartTurnSpec {
readonly messageId: string;
readonly createdAt: string;
readonly text: string;
/**
* Legacy data-url drafts only. `thread.turn.start` now takes id references
* to uploaded blobs, which mobile cannot mint yet, so these are dropped
* rather than sent. Callers surface `droppedAttachmentsWarning` to the user.
*/
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
@@ -60,7 +55,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
messageId: MessageId.make(spec.messageId),
role: "user" as const,
text: spec.text,
attachments: [],
attachments: toUploadChatImageAttachments(spec.attachments),
},
modelSelection: spec.modelSelection,
titleSeed: title,
+38 -22
View File
@@ -19,6 +19,7 @@ import { useFontFamily } from "../lib/useFontFamily";
import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -102,11 +103,11 @@ export function ComposerEditor({
const nativeRef = useRef<NativeComposerEditorRef>(null);
const mostRecentEventCountRef = useRef(0);
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
const [nativeEventSequence, setNativeEventSequence] = useState(0);
const previousRenderedEventSequenceRef = useRef(0);
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
{ eventCount: 0, value: props.value, selection: selection ?? null },
]);
const [, forceNativeEventRender] = useState(0);
// The native editor mounts empty, so the snapshot history starts empty: the
// first controlled payload must be a non-echo so a restored draft (or a
// recycled native view) is applied rather than skipped.
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
const bodyText = useScaledTextRole("body");
const textColor = useThemeColor("--color-foreground");
@@ -154,15 +155,16 @@ export function ComposerEditor({
})),
);
}, [props.value, skillLabels]);
const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
const controlledEventCount = includesNativeEvent
? resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
)
: mostRecentEventCount;
// Every render resolves against the snapshot history, so a render whose
// (value, selection) lags the acknowledged native state is stamped behind
// the native revision and rejected by the editor instead of re-applying a
// stale caret or stale text mid-typing.
const controlledEventCount = resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
);
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
props.value,
selection ?? null,
@@ -170,9 +172,7 @@ export function ComposerEditor({
nativeEventSnapshotsRef.current,
);
const isNativeEcho =
includesNativeEvent &&
controlledEventCount === mostRecentEventCount &&
acknowledgesLatestNativeEvent;
controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
const controlledDocumentJson = JSON.stringify({
value: props.value,
selection: isNativeEcho ? null : (selection ?? null),
@@ -180,9 +180,6 @@ export function ComposerEditor({
mostRecentEventCount: controlledEventCount,
isNativeEcho,
});
useEffect(() => {
previousRenderedEventSequenceRef.current = nativeEventSequence;
}, [nativeEventSequence]);
useEffect(() => {
if (!acknowledgesLatestNativeEvent) return;
nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
@@ -190,6 +187,18 @@ export function ComposerEditor({
mostRecentEventCount,
);
}, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
const assumedValue = props.value;
useEffect(() => {
// A native event that arrived after this render was committed moves the
// acknowledged revision forward; the editor rejects this payload, so the
// snapshot history must not assume it applied.
if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
nativeEventSnapshotsRef.current = assumeComposerControlledState(
nativeEventSnapshotsRef.current,
controlledEventCount,
assumedValue,
);
}, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
const acceptNativeEvent = useCallback(
(eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
@@ -257,7 +266,7 @@ export function ComposerEditor({
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -266,9 +275,16 @@ export function ComposerEditor({
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
// A selection change that raced a text mutation can carry post-edit
// text. It must reach the parent alongside the acknowledged revision,
// or the next render stamps the stale draft at that revision and can
// re-apply it over the newer native text.
if (event.nativeEvent.value !== props.value) {
onChangeText(event.nativeEvent.value);
}
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
@@ -21,6 +21,7 @@ import { useFontFamily } from "../lib/useFontFamily";
import { useThemeColor } from "../lib/useThemeColor";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -103,11 +104,11 @@ export function ComposerEditor({
const nativeRef = useRef<NativeComposerEditorRef>(null);
const mostRecentEventCountRef = useRef(0);
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
const [nativeEventSequence, setNativeEventSequence] = useState(0);
const previousRenderedEventSequenceRef = useRef(0);
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
{ eventCount: 0, value: props.value, selection: selection ?? null },
]);
const [, forceNativeEventRender] = useState(0);
// The native editor mounts empty, so the snapshot history starts empty: the
// first controlled payload must be a non-echo so a restored draft (or a
// recycled native view) is applied rather than skipped.
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
const confirmedTokensRef = useRef(initialConfirmedTokens);
const textColor = useThemeColor("--color-foreground");
@@ -155,15 +156,16 @@ export function ComposerEditor({
})),
);
}, [props.value, skillLabels]);
const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
const controlledEventCount = includesNativeEvent
? resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
)
: mostRecentEventCount;
// Every render resolves against the snapshot history, so a render whose
// (value, selection) lags the acknowledged native state is stamped behind
// the native revision and rejected by the editor instead of re-applying a
// stale caret or stale text mid-typing.
const controlledEventCount = resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
);
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
props.value,
selection ?? null,
@@ -171,9 +173,7 @@ export function ComposerEditor({
nativeEventSnapshotsRef.current,
);
const isNativeEcho =
includesNativeEvent &&
controlledEventCount === mostRecentEventCount &&
acknowledgesLatestNativeEvent;
controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
const controlledDocumentJson = JSON.stringify({
value: props.value,
selection: isNativeEcho ? null : (selection ?? null),
@@ -181,9 +181,6 @@ export function ComposerEditor({
mostRecentEventCount: controlledEventCount,
isNativeEcho,
});
useEffect(() => {
previousRenderedEventSequenceRef.current = nativeEventSequence;
}, [nativeEventSequence]);
useEffect(() => {
if (!acknowledgesLatestNativeEvent) return;
nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
@@ -191,6 +188,18 @@ export function ComposerEditor({
mostRecentEventCount,
);
}, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
const assumedValue = props.value;
useEffect(() => {
// A native event that arrived after this render was committed moves the
// acknowledged revision forward; the editor rejects this payload, so the
// snapshot history must not assume it applied.
if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
nativeEventSnapshotsRef.current = assumeComposerControlledState(
nativeEventSnapshotsRef.current,
controlledEventCount,
assumedValue,
);
}, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
const acceptNativeEvent = useCallback(
(eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
@@ -263,7 +272,7 @@ export function ComposerEditor({
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -272,9 +281,17 @@ export function ComposerEditor({
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
// Android emits the selection change mid-mutation, before the change
// event, so the payload can carry post-edit text. It must reach the
// parent alongside the acknowledged revision, or the next render
// stamps the stale draft at that revision and can re-apply it over
// the newer native text.
if (event.nativeEvent.value !== props.value) {
onChangeText(event.nativeEvent.value);
}
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
@@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -42,6 +43,19 @@ describe("isComposerNativeEcho", () => {
it("matches value and revision when selection is uncontrolled", () => {
expect(isComposerNativeEcho("native", null, 3, snapshots)).toBe(true);
});
it("does not claim a controlled selection against an assumed state without one", () => {
// An echo payload serializes `selection: null`; classifying a controlled
// selection as an echo of an assumed state would drop a parent caret move.
const assumed = [{ eventCount: 3, value: "native", selection: null }];
expect(isComposerNativeEcho("native", { start: 0, end: 0 }, 3, assumed)).toBe(false);
expect(isComposerNativeEcho("other", { start: 0, end: 0 }, 3, assumed)).toBe(false);
});
it("matches an assumed state when selection is uncontrolled", () => {
const assumed = [{ eventCount: 3, value: "native", selection: null }];
expect(isComposerNativeEcho("native", null, 3, assumed)).toBe(true);
});
});
describe("resolveComposerControlledEventCount", () => {
@@ -95,7 +109,7 @@ describe("pruneAcknowledgedComposerNativeEvents", () => {
selection: { start: eventCount, end: eventCount },
}));
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 999)).toEqual([]);
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 999)).toEqual([snapshots[999]]);
});
it("retains native events that arrive after the acknowledged render", () => {
@@ -104,6 +118,77 @@ describe("pruneAcknowledgedComposerNativeEvents", () => {
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
];
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 40)).toEqual([snapshots[1]]);
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 40)).toEqual(snapshots);
});
it("retains the newest acknowledged snapshot so settled re-renders stay echoes", () => {
const snapshots = [
{ eventCount: 40, value: "a", selection: { start: 1, end: 1 } },
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
{ eventCount: 42, value: "abc", selection: { start: 3, end: 3 } },
];
const pruned = pruneAcknowledgedComposerNativeEvents(snapshots, 42);
expect(pruned).toEqual([snapshots[2]]);
expect(isComposerNativeEcho("abc", { start: 3, end: 3 }, 42, pruned)).toBe(true);
});
it("keeps the newest of several snapshots sharing the acknowledged revision", () => {
const snapshots = [
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
{ eventCount: 41, value: "ab", selection: { start: 1, end: 1 } },
];
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 41)).toEqual([snapshots[1]]);
});
});
describe("assumeComposerControlledState", () => {
it("replaces the acknowledged history with the applied controlled state", () => {
const snapshots = [{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } }];
expect(assumeComposerControlledState(snapshots, 3, "")).toEqual([
{ eventCount: 3, value: "", selection: null },
]);
});
it("keeps native events that raced past the controlled revision", () => {
const snapshots = [
{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } },
{ eventCount: 4, value: "typed!", selection: { start: 6, end: 6 } },
];
expect(assumeComposerControlledState(snapshots, 3, "")).toEqual([
{ eventCount: 3, value: "", selection: null },
snapshots[1],
]);
});
it("applies a parent caret move on the assumed value at the assumed revision", () => {
// Same value, new caret: not an echo (so the selection is serialized) but
// still stamped at the assumed revision so the editor accepts it.
const snapshots = assumeComposerControlledState([], 3, "typed");
expect(isComposerNativeEcho("typed", { start: 2, end: 2 }, 3, snapshots)).toBe(false);
expect(resolveComposerControlledEventCount("typed", { start: 2, end: 2 }, 3, snapshots)).toBe(
3,
);
});
it("re-applies a parent value that round-trips back to an acknowledged state", () => {
// Native acknowledged "typed", the parent then controlled the editor to ""
// (a send clearing the draft) and back to "typed" (the send failed and the
// draft was restored). The restore must be a fresh non-echo edit stamped at
// the current revision, not an echo the editor would drop.
const snapshots = assumeComposerControlledState(
[{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } }],
3,
"",
);
expect(isComposerNativeEcho("typed", { start: 5, end: 5 }, 3, snapshots)).toBe(false);
expect(resolveComposerControlledEventCount("typed", { start: 5, end: 5 }, 3, snapshots)).toBe(
3,
);
});
});
@@ -31,10 +31,7 @@ export function resolveComposerControlledEventCount(
if (snapshot?.value !== value) continue;
newestValueEventCount ??= snapshot.eventCount;
if (
selection === null ||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end)
) {
if (selection === null || snapshotSelectionMatches(snapshot, selection)) {
return snapshot.eventCount;
}
}
@@ -49,6 +46,21 @@ export function resolveComposerControlledEventCount(
return mostRecentEventCount;
}
// A snapshot without a selection describes a state the editor applied itself
// (an assumed controlled document, where the native side may have bounded the
// caret). Revision stamping treats it as matching any controlled selection so
// a parent caret move on the assumed value stays at the assumed revision and
// passes the editor's staleness guard. Echo detection must not reuse this
// wildcard: an echo payload serializes `selection: null`, which would drop
// that caret move instead of applying it.
function snapshotSelectionMatches(
snapshot: ComposerNativeEventSnapshot,
selection: ComposerEditorSelection,
): boolean {
if (snapshot.selection === null) return true;
return snapshot.selection.start === selection.start && snapshot.selection.end === selection.end;
}
export function isComposerNativeEcho(
value: string,
selection: ComposerEditorSelection | null,
@@ -62,7 +74,9 @@ export function isComposerNativeEcho(
snapshot.eventCount === eventCount &&
snapshot.value === value &&
(selection === null ||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end))
(snapshot.selection !== null &&
snapshot.selection.start === selection.start &&
snapshot.selection.end === selection.end))
) {
return true;
}
@@ -70,9 +84,43 @@ export function isComposerNativeEcho(
return false;
}
/**
* Records that a parent-driven controlled document was handed to the native
* editor. From that point the acknowledged snapshot history describes a
* superseded native state, so it is replaced with the assumed applied state;
* a later parent update back to a previously acknowledged value must classify
* as a fresh edit, not as a native echo the editor would drop. Native events
* that raced past the controlled revision stay authoritative and are kept.
*/
export function assumeComposerControlledState(
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
eventCount: number,
value: string,
): ComposerNativeEventSnapshot[] {
return [
{ eventCount, value, selection: null },
...snapshots.filter((snapshot) => snapshot.eventCount > eventCount),
];
}
export function pruneAcknowledgedComposerNativeEvents(
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
acknowledgedEventCount: number,
): ComposerNativeEventSnapshot[] {
return snapshots.filter((snapshot) => snapshot.eventCount > acknowledgedEventCount);
// The newest acknowledged snapshot must survive pruning: it is what lets a
// later, unrelated re-render classify the settled composer state as a native
// echo instead of a parent-driven edit that would re-control the caret (and
// reset the keyboard's autocorrect context on iOS).
let latestAcknowledgedIndex = -1;
for (let index = snapshots.length - 1; index >= 0; index -= 1) {
const snapshot = snapshots[index];
if (snapshot !== undefined && snapshot.eventCount <= acknowledgedEventCount) {
latestAcknowledgedIndex = index;
break;
}
}
return snapshots.filter(
(snapshot, index) =>
index === latestAcknowledgedIndex || snapshot.eventCount > acknowledgedEventCount,
);
}
+1 -1
View File
@@ -169,7 +169,7 @@ export function resolveThreadOutboxDeliveryAction(input: {
if (!input.threadExists) {
return input.shellStatus === "live" ? "remove" : "wait";
}
return input.environmentConnected && !input.threadBusy ? "send" : "wait";
return input.environmentConnected ? "send" : "wait";
}
/**
+25 -5
View File
@@ -1,6 +1,7 @@
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { writeFileAtomically } from "../lib/atomic-file";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
@@ -9,6 +10,24 @@ import {
const THREAD_OUTBOX_DIRECTORY = "thread-outbox";
const inFlightWrites = new Set<Promise<void>>();
function trackInFlightWrite(operation: Promise<void>): Promise<void> {
inFlightWrites.add(operation);
void operation.catch(() => undefined).finally(() => inFlightWrites.delete(operation));
return operation;
}
/**
* Awaits queued-message writes so an app update restart cannot tear down the
* runtime while one is mid-file.
*/
export async function flushThreadOutboxWrites(): Promise<void> {
while (inFlightWrites.size > 0) {
await Promise.allSettled(inFlightWrites);
}
}
export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutboxStorageError>()(
"ThreadOutboxStorageError",
{
@@ -89,11 +108,12 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
write: async (message) => {
const fileName = messageFileName(message.messageId);
try {
const file = await getMessageFile(message.messageId);
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
await trackInFlightWrite(
(async () => {
const file = await getMessageFile(message.messageId);
await writeFileAtomically(file, JSON.stringify(encodeQueuedThreadMessage(message)));
})(),
);
} catch (cause) {
throw new ThreadOutboxStorageError({
operation: "write",
@@ -487,6 +487,27 @@ describe("thread outbox", () => {
).toBe("send");
});
it("sends existing-thread messages whenever connected so queued messages can steer", () => {
expect(
resolveThreadOutboxDeliveryAction({
isCreation: false,
threadExists: true,
shellStatus: "live",
environmentConnected: true,
threadBusy: true,
}),
).toBe("send");
expect(
resolveThreadOutboxDeliveryAction({
isCreation: false,
threadExists: true,
shellStatus: "live",
environmentConnected: false,
threadBusy: true,
}),
).toBe("wait");
});
it("sends queued creations once connected and live, removing already-created ones", () => {
expect(
resolveThreadOutboxDeliveryAction({
+12 -1
View File
@@ -3,7 +3,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { appAtomRegistry } from "./atom-registry";
import { createThreadOutboxManager } from "./thread-outbox-manager";
import type { QueuedThreadMessage } from "./thread-outbox-model";
import { expoThreadOutboxStorage } from "./thread-outbox-storage";
import { expoThreadOutboxStorage, flushThreadOutboxWrites } from "./thread-outbox-storage";
export * from "./thread-outbox-model";
@@ -12,6 +12,17 @@ export const threadOutboxManager = createThreadOutboxManager({
storage: expoThreadOutboxStorage,
});
/**
* Lands queued outbox mutations before the JS runtime is torn down (app update
* restart). An enqueued message is published to the atom immediately but its
* durable write waits behind the mutation queue, so draining only the writes
* already mid-file would miss it.
*/
export async function flushThreadOutbox(): Promise<void> {
await threadOutboxManager.serialize(async () => {});
await flushThreadOutboxWrites();
}
export function ensureThreadOutboxLoaded(): void {
void threadOutboxManager.load();
}
@@ -4,6 +4,7 @@ import { vi } from "vite-plus/test";
const composerDraftFileMocks = vi.hoisted(() => {
let document = "";
let writeError: Error | null = null;
let releaseRead: (() => void) | null = null;
let readBarrier = Promise.resolve();
@@ -17,23 +18,35 @@ const composerDraftFileMocks = vi.hoisted(() => {
releaseRead?.();
releaseRead = null;
},
getDocument() {
return document;
},
setDocument(value: unknown) {
document = JSON.stringify(value);
},
setWriteError(error: Error | null) {
writeError = error;
},
Directory: class {
create() {}
},
File: class {
exists = true;
parentDirectory = null;
create() {}
moveSync() {}
async text() {
await readBarrier;
return document;
}
write(value: string) {
if (writeError) {
throw writeError;
}
document = value;
}
},
@@ -49,15 +62,18 @@ vi.mock("expo-file-system", () => ({
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
ComposerDraftPersistenceError,
composerDraftsAtom,
copyComposerDraftContentIfEmpty,
copyComposerDraftContentState,
decodePersistedComposerDrafts,
type ComposerDraft,
flushComposerDrafts,
getComposerDraftSnapshot,
mergeComposerDraftContentState,
removeComposerDraftsForEnvironment,
restoreComposerDraftSnapshotState,
setComposerDraftText,
} from "./use-composer-drafts";
const DRAFT: ComposerDraft = {
@@ -393,4 +409,27 @@ describe("mobile composer drafts", () => {
[unrelatedKey]: unrelated,
});
});
it("lands a still-debounced draft write when flushed", async () => {
const draftKey = "environment-1:thread-1";
setComposerDraftText(draftKey, "typed right before the restart");
await flushComposerDrafts();
expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
drafts: { [draftKey]: { text: "typed right before the restart" } },
});
});
it("propagates a flush write failure instead of resolving as saved", async () => {
const draftKey = "environment-1:thread-1";
setComposerDraftText(draftKey, "unsaved");
composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
try {
await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
} finally {
composerDraftFileMocks.setWriteError(null);
}
});
});
+23 -5
View File
@@ -13,6 +13,7 @@ import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
import { writeFileAtomically } from "../lib/atomic-file";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
@@ -188,10 +189,7 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
} as const;
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(encoded);
await writeFileAtomically(file, encoded);
} catch (cause) {
throw new ComposerDraftPersistenceError({
operation,
@@ -211,6 +209,26 @@ async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>
}
}
/**
* Lands any debounced or in-flight draft write before the JS runtime is torn
* down (app update restart), so the freshest draft state survives it. A write
* failure propagates so the caller can decide whether the restart may proceed.
*/
export async function flushComposerDrafts(): Promise<void> {
// An edit during an awaited write schedules another debounced write, so
// keep landing snapshots until no debounce is pending after a queue drain.
do {
while (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
await persistenceQueue.run(() =>
writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom)),
);
}
await persistenceQueue.run(() => Promise.resolve());
} while (persistTimer !== null);
}
function schedulePersistComposerDrafts(drafts: Record<string, ComposerDraft>): void {
if (persistTimer !== null) {
clearTimeout(persistTimer);
@@ -627,7 +645,7 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
persistTimer = null;
}
appAtomRegistry.set(composerDraftsAtom, next);
await writePersistedComposerDrafts(next);
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
}
export function useComposerDraft(draftKey: string | null): ComposerDraft {
@@ -129,10 +129,6 @@ export function useThreadComposerState() {
);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
return null;
@@ -238,15 +234,12 @@ export function useThreadComposerState() {
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
try {
const pasted = await convertPastedImagesToAttachments({
const images = await convertPastedImagesToAttachments({
uris,
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
});
if (pasted.images.length > 0) {
appendComposerDraftAttachments(threadKey, pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
if (images.length > 0) {
appendComposerDraftAttachments(threadKey, images);
}
} catch (error) {
console.error("[native paste] error converting images", {
@@ -311,7 +304,6 @@ export function useThreadComposerState() {
modelSelection,
runtimeMode,
interactionMode,
activeThreadBusy,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,
@@ -17,7 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { scopedThreadKey } from "../lib/scopedEntities";
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
import { droppedAttachmentsWarning } from "../lib/composerImages";
import { toUploadChatImageAttachments } from "../lib/composerImages";
import { randomHex } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { useProjects, useThreadShells } from "./entities";
@@ -37,17 +37,14 @@ import {
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { environmentThreadShells, threadEnvironment } from "./threads";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
import {
editingQueuedMessageIdsAtom,
useThreadOutboxMessages,
useThreadOutboxShellStatuses,
} from "./use-thread-outbox";
import {
setPendingConnectionError,
useRemoteConnectionStatus,
} from "./use-remote-environment-registry";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
Atom.keepAlive,
@@ -152,14 +149,6 @@ export function useThreadOutboxDrain(): void {
return false;
}
// Messages queued before the attachment contract change can still hold
// data-url images. They are never put on the wire, so tell the user the
// text went without them instead of dropping them silently.
const droppedWarning = droppedAttachmentsWarning(queuedMessage.attachments.length);
if (droppedWarning !== null) {
setPendingConnectionError(droppedWarning);
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
@@ -237,7 +226,7 @@ export function useThreadOutboxDrain(): void {
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: [],
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
},
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
@@ -373,22 +362,12 @@ export function useThreadOutboxDrain(): void {
return true;
}
// The guards evaluated before the confirmation await are stale by now:
// the thread may have gone busy, or the user may have opened this
// message in the editor. Re-read both and defer to the next drain pass
// (returning true skips the failure/backoff path) rather than sending
// a payload the user is editing or racing an active turn.
// the user may have opened this message in the editor. Re-read that
// guard and defer to the next drain pass (returning true skips the
// failure/backoff path) rather than sending a payload being edited.
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
return true;
}
const freshThread = findThread(
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
nextQueuedMessage,
);
const freshThreadBusy =
freshThread?.session?.status === "running" || freshThread?.session?.status === "starting";
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
return true;
}
return deliveryAction === "remove"
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
: creation !== undefined
@@ -60,6 +60,7 @@ function threadDetailToShell(
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
viewedAt: thread.viewedAt,
snoozedUntil: thread.snoozedUntil ?? null,
snoozedAt: thread.snoozedAt ?? null,
session: thread.session,
+1
View File
@@ -31,6 +31,7 @@
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"msgpackr-extract": "3.0.4",
"node-pty": "^1.1.0",
"yaml": "catalog:"
},
@@ -1,106 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { parseThreadSegmentFromAttachmentId } from "../attachmentStore.ts";
import {
deletePendingAttachment,
issueAttachmentUploadUrl,
storeAttachmentUpload,
validateAttachmentUploadToken,
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
} from "./AttachmentUpload.ts";
const testLayer = ServerSecretStore.layer.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
Layer.provideMerge(NodeServices.layer),
);
const uploadInput = {
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 6,
} as const;
describe("AttachmentUpload", () => {
it.effect("mints a pending id and a token that validates round-trip", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
expect(parseThreadSegmentFromAttachmentId(issued.attachmentId)).toBe("pending");
expect(issued.relativeUrl.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`)).toBe(true);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const claims = yield* validateAttachmentUploadToken(token);
expect(claims).toMatchObject({
kind: "attachment-upload",
attachmentId: issued.attachmentId,
mimeType: "image/png",
sizeBytes: 6,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects a tampered token", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const [payload, signature] = token.split(".");
const tampered = `${payload}x.${signature}`;
expect(yield* validateAttachmentUploadToken(tampered)).toBeNull();
expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("stores matching bytes and rejects a size mismatch", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const issued = yield* issueAttachmentUploadUrl(uploadInput);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const claims = yield* validateAttachmentUploadToken(token);
if (!claims) throw new Error("expected valid claims");
const short = yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]));
expect(short).toMatchObject({ ok: false, status: 400 });
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(6));
expect(stored).toEqual({ ok: true });
const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`);
expect(NodeFS.existsSync(finalPath)).toBe(true);
// No .part residue after a successful store (suffix is per-request).
const partResidue = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
entry.endsWith(".part"),
);
expect(partResidue).toEqual([]);
}).pipe(Effect.provide(testLayer)),
);
it.effect("deletes pending uploads idempotently but never thread-scoped files", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
const uuid = "00000000-0000-4000-8000-0000000000dd";
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
yield* deletePendingAttachment(`pending-${uuid}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
// Second delete is a no-op, not an error.
yield* deletePendingAttachment(`pending-${uuid}`);
const scopedUuid = "00000000-0000-4000-8000-0000000000ee";
const scopedPath = NodePath.join(config.attachmentsDir, `thread-1-${scopedUuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// A delete aimed at a claimed attachment must not remove it.
yield* deletePendingAttachment(`pending-${scopedUuid}`);
yield* deletePendingAttachment(`thread-1-${scopedUuid}`);
expect(NodeFS.existsSync(scopedPath)).toBe(true);
}).pipe(Effect.provide(testLayer)),
);
});
-221
View File
@@ -1,221 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import {
ATTACHMENT_UPLOAD_URL_TTL_MS,
type AttachmentCreateUploadUrlInput,
AttachmentUploadSigningKeyError,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
createPendingAttachmentId,
findAttachmentPathByUuid,
parseAttachmentIdFromRelativePath,
parseAttachmentUuid,
parseThreadSegmentFromAttachmentId,
PENDING_ATTACHMENT_THREAD_SEGMENT,
} from "../attachmentStore.ts";
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import { inferImageExtension } from "../imageMime.ts";
export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
// Shares the asset-access secret: upload and asset claims are distinguished
// by their schema `kind`, so a token minted for one can never validate as
// the other, and one key covers both signing uses.
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const UploadClaimsSchema = Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment-upload"),
attachmentId: Schema.String,
mimeType: Schema.String,
/** Exact byte count the client committed to at mint time. */
sizeBytes: Schema.Number,
expiresAt: Schema.Number,
});
export type AttachmentUploadClaims = typeof UploadClaimsSchema.Type;
const UploadClaimsJson = Schema.fromJsonString(UploadClaimsSchema);
const decodeUploadClaimsOption = Schema.decodeUnknownOption(UploadClaimsJson);
const encodeUploadClaims = Schema.encodeSync(UploadClaimsJson);
// Plain function (not Effect) so the base64/JSON failure modes stay a simple
// null, mirroring AssetAccess.decodeClaims.
function decodeUploadClaims(encodedPayload: string): AttachmentUploadClaims | null {
try {
return Option.getOrNull(decodeUploadClaimsOption(base64UrlDecodeUtf8(encodedPayload)));
} catch {
return null;
}
}
const loadSigningSecret = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
});
/**
* Mints the `pending-<uuid>` id and a signed, expiring upload URL for it.
* Called over the authenticated ws; the returned URL itself carries
* authorization (mirroring signed asset GET URLs), which is what lets the
* browser POST bytes to any environment without extra credential plumbing.
*/
export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
input: AttachmentCreateUploadUrlInput,
) {
const secret = yield* loadSigningSecret.pipe(
Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
);
const attachmentId = createPendingAttachmentId();
const expiresAt = (yield* Clock.currentTimeMillis) + ATTACHMENT_UPLOAD_URL_TTL_MS;
const encodedPayload = base64UrlEncode(
encodeUploadClaims({
version: 1,
kind: "attachment-upload",
attachmentId,
mimeType: input.mimeType.toLowerCase(),
sizeBytes: input.sizeBytes,
expiresAt,
}),
);
const token = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
return {
attachmentId,
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${token}`,
expiresAt,
};
});
/** Verifies signature and expiry; null means "treat as not found". */
export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
token: string,
) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secret = yield* loadSigningSecret.pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to load the attachment upload signing key.", { cause }),
),
Effect.orElseSucceed(() => null),
);
if (!secret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) return null;
const claims = decodeUploadClaims(encodedPayload);
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
return claims;
});
export type StoreUploadResult =
| { readonly ok: true }
| { readonly ok: false; readonly status: number; readonly detail: string };
/**
* Persists validated upload bytes. Writes to `<id>.<ext>.part` first and
* renames on success, so a crashed or aborted upload can never leave a file
* that looks like a complete attachment. Re-running with the same token
* overwrites atomically, which makes client retries safe.
*/
export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
claims: AttachmentUploadClaims,
bytes: Uint8Array,
) {
if (bytes.byteLength !== claims.sizeBytes) {
return {
ok: false,
status: 400,
detail: `Body was ${bytes.byteLength} bytes, expected ${claims.sizeBytes}.`,
} satisfies StoreUploadResult;
}
const config = yield* ServerConfig.ServerConfig;
const extension = inferImageExtension({ mimeType: claims.mimeType });
const relativePath = `${claims.attachmentId}${extension}`;
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath,
});
// Unique per request: two concurrent POSTs of the same token must not
// interleave writes into one temp file. Both rename onto the final path
// atomically; last one wins with identical claims-validated content.
const partPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
});
if (!finalPath || !partPath) {
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const writeResult = yield* Effect.gen(function* () {
yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
yield* fileSystem.writeFile(partPath, bytes);
yield* fileSystem.rename(partPath, finalPath);
}).pipe(
Effect.as({ ok: true } satisfies StoreUploadResult),
Effect.tapError((cause) =>
Effect.logError("Failed to persist attachment upload.", {
attachmentId: claims.attachmentId,
cause,
}),
),
Effect.orElseSucceed(
() =>
({
ok: false,
status: 500,
detail: "Failed to persist upload.",
}) satisfies StoreUploadResult,
),
);
return writeResult;
});
/**
* Deletes a never-sent upload. Idempotent, and refuses (as a silent no-op)
* anything already claimed by a thread: those files are owned by their
* message and only die with the thread.
*/
export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
attachmentId: string,
) {
if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return;
}
const uuid = parseAttachmentUuid(attachmentId);
if (!uuid) return;
const config = yield* ServerConfig.ServerConfig;
const filePath = findAttachmentPathByUuid({ attachmentsDir: config.attachmentsDir, uuid });
if (!filePath) return;
const path = yield* Path.Path;
const foundId = parseAttachmentIdFromRelativePath(path.basename(filePath));
if (
!foundId ||
parseThreadSegmentFromAttachmentId(foundId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
) {
return;
}
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.remove(filePath).pipe(
Effect.catch(
() =>
// Raced with the sweep or a duplicate delete; idempotent by design.
Effect.void,
),
);
});
+4 -160
View File
@@ -7,19 +7,10 @@ import { describe, expect, it } from "vite-plus/test";
import {
createAttachmentId,
createPendingAttachmentId,
parseThreadSegmentFromAttachmentId,
planAttachmentClaim,
resolveAttachmentPathById,
sweepStalePendingAttachments,
toSafeThreadAttachmentSegment,
PENDING_ATTACHMENT_MAX_AGE_MS,
} from "./attachmentStore.ts";
function makeTempAttachmentsDir(): string {
return NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"));
}
describe("attachmentStore", () => {
it("sanitizes thread ids when creating attachment ids", () => {
const attachmentId = createAttachmentId("thread.folder/unsafe space");
@@ -54,9 +45,11 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = makeTempAttachmentsDir();
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const attachmentId = "thread-1-00000000-0000-4000-8000-00000000000a";
const attachmentId = "thread-1-attachment";
const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
@@ -70,155 +63,6 @@ describe("attachmentStore", () => {
}
});
it("resolves a pending id to the renamed thread-scoped file after claim", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const uuid = "00000000-0000-4000-8000-00000000000b";
const scopedPath = NodePath.join(attachmentsDir, `thread-9-${uuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// Old signed asset URLs carry the pending id; they must keep resolving.
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId: `pending-${uuid}`,
});
expect(resolved).toBe(scopedPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reserves the pending segment for uploads", () => {
expect(toSafeThreadAttachmentSegment("pending")).toBe("pending_thread");
const pendingId = createPendingAttachmentId();
expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
});
describe("planAttachmentClaim", () => {
const uuid = "00000000-0000-4000-8000-00000000000c";
it("plans a rename for a pending attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.webp`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toEqual({
ok: true,
finalId: `thread-foo-${uuid}`,
currentPath: pendingPath,
finalPath: NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`),
alreadyScoped: false,
});
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("is idempotent when a retry references an already-renamed file", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const scopedPath = NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: true, alreadyScoped: true });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("refuses an attachment claimed by another thread", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
NodeFS.writeFileSync(
NodePath.join(attachmentsDir, `other-thread-${uuid}.png`),
Buffer.from("pixels"),
);
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reports a missing attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
describe("sweepStalePendingAttachments", () => {
it("deletes stale pending and partial files, keeps fresh and scoped ones", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const stalePending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000001.png",
);
const freshPending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000002.png",
);
const scoped = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.png",
);
const stalePart = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000004.png.part",
);
// Fixed epoch so the test never touches the real clock: files are
// stamped relative to `nowMs` below, not to wall time.
const nowMs = 1_800_000_000_000;
const freshMs = nowMs - 60_000;
const staleMs = nowMs - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
for (const filePath of [stalePending, freshPending, scoped, stalePart]) {
NodeFS.writeFileSync(filePath, Buffer.from("x"));
}
NodeFS.utimesSync(freshPending, freshMs / 1000, freshMs / 1000);
NodeFS.utimesSync(stalePending, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(scoped, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(stalePart, staleMs / 1000, staleMs / 1000);
const swept = sweepStalePendingAttachments({
attachmentsDir,
nowMs,
});
expect(swept.deleted).toBe(2);
expect(NodeFS.existsSync(stalePending)).toBe(false);
expect(NodeFS.existsSync(stalePart)).toBe(false);
expect(NodeFS.existsSync(freshPending)).toBe(true);
expect(NodeFS.existsSync(scoped)).toBe(true);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+10 -175
View File
@@ -1,7 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import type { ChatAttachment } from "@t3tools/contracts";
@@ -9,8 +8,9 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension } from "./imageMime.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -19,13 +19,6 @@ const ATTACHMENT_ID_PATTERN = new RegExp(
"i",
);
/**
* Segment used for attachments uploaded before their thread exists
* (upload-on-attach). Files named `pending-<uuid>.<ext>` are re-scoped to the
* thread at turn start and swept when stale.
*/
export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
const segment = threadId
.trim()
@@ -38,65 +31,9 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
if (segment.length === 0) {
return null;
}
// `pending` is reserved for not-yet-sent uploads; a thread that slugged to
// it would have its attachments swept as orphans.
if (segment === PENDING_ATTACHMENT_THREAD_SEGMENT) {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}_thread`;
}
return segment;
}
export function createPendingAttachmentId(): string {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
}
/** Extracts the trailing uuid from a `<segment>-<uuid>` attachment id. */
export function parseAttachmentUuid(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
return match?.[2]?.toLowerCase() ?? null;
}
/**
* Finds the on-disk file for an attachment uuid regardless of its current
* segment (`pending-` before send, thread-scoped after). The uuid is the
* stable identity: turn-start renames the file's segment but never the uuid,
* which is what keeps send retries and signed asset URLs working across the
* rename.
*/
export function findAttachmentPathByUuid(input: {
readonly attachmentsDir: string;
readonly uuid: string;
}): string | null {
const uuid = input.uuid.toLowerCase();
if (!new RegExp(`^${ATTACHMENT_ID_UUID_PATTERN}$`, "i").test(uuid)) {
return null;
}
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return null;
}
const suffixPattern = new RegExp(`-${uuid}\\.[a-z0-9]{1,8}$`, "i");
for (const entry of entries) {
if (!suffixPattern.test(entry)) {
continue;
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: entry,
});
if (resolved && NodeFS.existsSync(resolved)) {
return resolved;
}
}
return null;
}
export function createAttachmentId(threadId: string): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
@@ -143,122 +80,20 @@ export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly attachmentId: string;
}): string | null {
// Resolution is by uuid, not by exact id: a signed asset URL minted for a
// `pending-` id must keep working after turn start renames the file to its
// thread segment (draft previews hold such URLs across a send).
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
return findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
}
export type AttachmentClaimPlan =
| {
readonly ok: true;
readonly finalId: string;
readonly currentPath: string;
readonly finalPath: string;
/** True when a prior (possibly failed) send already renamed the file. */
readonly alreadyScoped: boolean;
}
| { readonly ok: false; readonly reason: string };
/**
* Plans the pending-to-thread re-scope for one referenced attachment at turn
* start. Pure path logic; the caller performs the rename. The uuid is matched
* against whatever segment the file currently has so retries after a partial
* send are idempotent, and a file already claimed by a different thread is
* refused rather than stolen.
*/
export function planAttachmentClaim(input: {
readonly attachmentsDir: string;
readonly threadId: string;
readonly attachmentId: string;
}): AttachmentClaimPlan {
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
return { ok: false, reason: "invalid attachment id" };
}
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
if (!threadSegment) {
return { ok: false, reason: "invalid thread id" };
}
const currentPath = findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
if (!currentPath) {
return { ok: false, reason: "attachment not found (removed or expired)" };
}
const fileName = NodePath.basename(currentPath);
const currentId = parseAttachmentIdFromRelativePath(fileName);
const currentSegment = currentId ? parseThreadSegmentFromAttachmentId(currentId) : null;
if (!currentSegment) {
return { ok: false, reason: "attachment file name is malformed" };
}
const extension = NodePath.extname(fileName);
const finalId = `${threadSegment}-${uuid}`;
if (currentSegment === threadSegment) {
return { ok: true, finalId, currentPath, finalPath: currentPath, alreadyScoped: true };
}
if (currentSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return { ok: false, reason: "attachment belongs to another thread" };
}
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${finalId}${extension}`,
});
if (!finalPath) {
return { ok: false, reason: "failed to resolve attachment path" };
}
return { ok: true, finalId, currentPath, finalPath, alreadyScoped: false };
}
export const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
export const PARTIAL_UPLOAD_MAX_AGE_MS = 24 * 60 * 60 * 1000;
/**
* Deletes never-sent uploads (`pending-*`) past their retention window and
* half-written `*.part` files left by aborted uploads. Runs at server start;
* chip removal deletes eagerly, this is the backstop.
*/
export function sweepStalePendingAttachments(input: {
readonly attachmentsDir: string;
readonly nowMs: number;
}): { readonly deleted: number } {
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return { deleted: 0 };
}
let deleted = 0;
for (const entry of entries) {
const isPartial = entry.endsWith(".part");
const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
if (!isPartial) {
const id = parseAttachmentIdFromRelativePath(entry);
const segment = id ? parseThreadSegmentFromAttachmentId(id) : null;
if (segment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
continue;
}
}
const resolved = resolveAttachmentRelativePath({
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: entry,
relativePath: `${normalizedId}${extension}`,
});
if (!resolved) {
continue;
}
try {
const stats = NodeFS.statSync(resolved);
if (input.nowMs - stats.mtimeMs > maxAgeMs) {
NodeFS.unlinkSync(resolved);
deleted += 1;
}
} catch {
// Raced with a concurrent delete or an unreadable entry; skip it.
if (maybePath && NodeFS.existsSync(maybePath)) {
return maybePath;
}
}
return { deleted };
return null;
}
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
-2
View File
@@ -83,8 +83,6 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
+3 -2
View File
@@ -36,6 +36,7 @@ import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import {
CLOUD_LINKED_USER_ID,
isAgentActivityPublishingEnabledValue,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
@@ -142,7 +143,7 @@ function stringToBytes(value: string): Uint8Array {
}
export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
return value === "true";
return isAgentActivityPublishingEnabledValue(value);
}
interface CloudCliStatus {
@@ -447,7 +448,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
bootServiceLayer(config),
headlessRelayClientTracingLayer,
).pipe(
+40
View File
@@ -1,6 +1,10 @@
import { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as ServerSecretStore from "../auth/ServerSecretStore.ts";
export const CLOUD_MINT_PUBLIC_KEY = "cloud-mint-ed25519-public-key";
export const CLOUD_ENDPOINT_RUNTIME_CONFIG = "cloud-endpoint-runtime-config";
export const CLOUD_LINKED_USER_ID = "cloud-linked-user-id";
@@ -16,3 +20,39 @@ export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect(
export const decodeRuntimeConfig = Schema.decodeUnknownOption(
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
);
export function isAgentActivityPublishingEnabledValue(value: string | null): boolean {
return value === "true";
}
/** Whether agent-activity publishes currently leave this environment: the
publish opt-in secret is enabled and the relay link credentials exist.
Mirrors the per-publish gate in AgentAwarenessRelay, so the descriptor
capability never advertises publishing that the publisher would skip. */
export const readAgentActivityPublishingActive = (
secrets: ServerSecretStore.ServerSecretStore["Service"],
): Effect.Effect<boolean> =>
Effect.gen(function* () {
const readSecretString = (name: string) =>
secrets
.get(name)
.pipe(
Effect.map((bytes) =>
Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
),
);
const [enabled, url, environmentCredential] = yield* Effect.all([
readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET),
readSecretString(RELAY_URL_SECRET),
readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
]);
// Empty strings are as unconfigured as missing files: the publisher's
// truthiness gate skips them, so the capability must too.
return (
isAgentActivityPublishingEnabledValue(enabled) &&
url !== null &&
url !== "" &&
environmentCredential !== null &&
environmentCredential !== ""
);
}).pipe(Effect.orElseSucceed(() => false));
-15
View File
@@ -6,7 +6,6 @@
*
* @module ServerConfig
*/
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -15,8 +14,6 @@ import * as LogLevel from "effect/LogLevel";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { sweepStalePendingAttachments } from "./attachmentStore.ts";
export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
@@ -155,18 +152,6 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
],
{ concurrency: "unbounded" },
);
// Backstop GC for upload-on-attach: never-sent `pending-*` uploads and
// aborted `*.part` files. Eager deletes happen at chip removal; this covers
// crashed clients and abandoned drafts.
const nowMs = yield* Clock.currentTimeMillis;
const swept = sweepStalePendingAttachments({
attachmentsDir: derivedPaths.attachmentsDir,
nowMs,
});
if (swept.deleted > 0) {
yield* Effect.logInfo("Swept stale pending attachments.", { deleted: swept.deleted });
}
});
const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
@@ -0,0 +1,126 @@
import { it } from "@effect/vitest";
import { HostProcessHostname } from "@t3tools/shared/hostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect } from "vite-plus/test";
import * as RemoteOpenTargets from "./RemoteOpenTargets.ts";
const encoder = new TextEncoder();
const TAILSCALE_STATUS_JSON = JSON.stringify({
Self: { DNSName: "bb-1.tail1234.ts.net.", TailscaleIPs: ["100.64.1.2"] },
});
/** Spawner whose `tailscale status --json` exits with the given output. */
const spawnerLayer = (input: { readonly exitCode: number; readonly stdout: string }) =>
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(input.stdout)),
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
),
),
);
const netLayer = (input: { readonly ipv4: boolean; readonly ipv6: boolean }) =>
Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
hasListenerOnHost: (_port, host) => Effect.succeed(host === "::1" ? input.ipv6 : input.ipv4),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
});
const resolveTargets = (input: {
readonly sshd: { readonly ipv4: boolean; readonly ipv6: boolean };
readonly tailscale: { readonly exitCode: number; readonly stdout: string };
readonly hostname: string;
}) =>
Effect.flatMap(RemoteOpenTargets.RemoteOpenTargets, (service) => service.resolveTargets()).pipe(
Effect.provideService(HostProcessHostname, input.hostname),
Effect.provide(
RemoteOpenTargets.layer.pipe(
Layer.provide(Layer.mergeAll(netLayer(input.sshd), spawnerLayer(input.tailscale))),
),
),
);
const TAILSCALE_UP = { exitCode: 0, stdout: TAILSCALE_STATUS_JSON };
const TAILSCALE_DOWN = { exitCode: 1, stdout: "" };
describe("RemoteOpenTargets", () => {
it.effect("advertises nothing when no sshd accepts on either loopback", () =>
Effect.gen(function* () {
const targets = yield* resolveTargets({
sshd: { ipv4: false, ipv6: false },
tailscale: TAILSCALE_UP,
hostname: "bb-1",
});
expect(targets).toEqual([]);
}),
);
it.effect("orders the tailnet name before the mDNS name", () =>
Effect.gen(function* () {
const targets = yield* resolveTargets({
sshd: { ipv4: true, ipv6: true },
tailscale: TAILSCALE_UP,
hostname: "bb-1",
});
expect(targets).toEqual([
{ kind: "tailscale", host: "bb-1.tail1234.ts.net" },
{ kind: "mdns", host: "bb-1.local" },
]);
}),
);
it.effect("accepts an sshd bound to IPv6 loopback only", () =>
Effect.gen(function* () {
const targets = yield* resolveTargets({
sshd: { ipv4: false, ipv6: true },
tailscale: TAILSCALE_DOWN,
hostname: "bb-1",
});
expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
}),
);
it.effect("falls back to mDNS alone when tailscale is unavailable", () =>
Effect.gen(function* () {
const targets = yield* resolveTargets({
sshd: { ipv4: true, ipv6: false },
tailscale: TAILSCALE_DOWN,
hostname: "bb-1",
});
expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
}),
);
it.effect("shortens an FQDN hostname to its first label for mDNS", () =>
Effect.gen(function* () {
const targets = yield* resolveTargets({
sshd: { ipv4: true, ipv6: true },
tailscale: TAILSCALE_DOWN,
hostname: "bb-1.example.com",
});
expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
}),
);
});
@@ -0,0 +1,72 @@
/**
* RemoteOpenTargets - resolves the SSH hostnames this environment advertises
* for remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`).
*
* The server can only check itself: sshd listening locally, tailscaled
* reporting a MagicDNS name, and the machine hostname for mDNS. Whether a
* given name resolves from the viewer's machine is inherently client-side.
* Targets are ordered most-reachable first (tailnet name works from anywhere
* on the tailnet; `<hostname>.local` only on the same LAN).
*/
import { type RemoteOpenTarget } from "@t3tools/contracts";
import { HostProcessHostname } from "@t3tools/shared/hostProcess";
import * as NetService from "@t3tools/shared/Net";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
const SSH_PORT = 22;
export class RemoteOpenTargets extends Context.Service<
RemoteOpenTargets,
{
readonly resolveTargets: () => Effect.Effect<ReadonlyArray<RemoteOpenTarget>>;
}
>()("t3/environment/RemoteOpenTargets") {}
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const net = yield* NetService.NetService;
const resolveTargets = Effect.gen(function* () {
// No local sshd means no name can work; advertise nothing so clients
// render a clear "no SSH route" state instead of links that hang.
// Check both loopback families: sshd can be bound IPv6-only.
const sshdListening = yield* Effect.zipWith(
net.hasListenerOnHost(SSH_PORT, "127.0.0.1"),
net.hasListenerOnHost(SSH_PORT, "::1"),
(ipv4, ipv6) => ipv4 || ipv6,
);
if (!sshdListening) {
return [];
}
const targets: Array<RemoteOpenTarget> = [];
// Tailscale absent or down is the common case, not an error.
const magicDnsName = yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
if (magicDnsName !== null) {
targets.push({ kind: "tailscale", host: magicDnsName });
}
// os.hostname() may already be an FQDN (macOS often reports
// "Name.local"); mDNS names are always `<first-label>.local`.
const hostname = yield* HostProcessHostname;
const shortHostname = hostname.split(".")[0]?.trim();
if (shortHostname !== undefined && shortHostname.length > 0) {
targets.push({ kind: "mdns", host: `${shortHostname}.local` });
}
return targets;
});
return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
});
export const layer = Layer.effect(RemoteOpenTargets, make);
@@ -3,9 +3,16 @@ import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
@@ -14,7 +21,21 @@ const isServerEnvironmentIdPersistenceError = Schema.is(
);
const makeServerEnvironmentLayer = (baseDir: string) =>
ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
ServerEnvironment.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
);
const emptySecretStoreLayer = Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
get: () => Effect.succeed(Option.none()),
set: () => Effect.void,
create: () => Effect.void,
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
remove: () => Effect.void,
}),
);
const makeServerConfig = Effect.fn(function* (baseDir: string) {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
@@ -70,7 +91,55 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.pullRequests).toBe(true);
expect(second.capabilities.threadViewState).toBe(true);
expect(second.capabilities.threadTitleRegeneration).toBe(true);
expect(second.capabilities.agentActivityPublishing).toBe(false);
}),
);
it.effect("reports agent activity publishing from the current secret state", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-environment-publish-test-",
});
const testLayer = Layer.mergeAll(
ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
ServerSecretStore.layer,
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
yield* Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const encode = (value: string) => new TextEncoder().encode(value);
const unlinked = yield* serverEnvironment.getDescriptor;
expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
// The opt-in alone is not enough: without relay link credentials no
// publish would leave this environment.
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
const withoutLink = yield* serverEnvironment.getDescriptor;
expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
// Empty credentials are as unconfigured as missing ones: the
// publisher's truthiness gate skips them, so the capability must not
// advertise publishing.
yield* secrets.set(RELAY_URL_SECRET, encode(""));
yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
const emptyUrl = yield* serverEnvironment.getDescriptor;
expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
const linked = yield* serverEnvironment.getDescriptor;
expect(linked.capabilities.agentActivityPublishing).toBe(true);
// The toggle changes at runtime, so the same service instance must
// reflect a flip without a restart.
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
const disabled = yield* serverEnvironment.getDescriptor;
expect(disabled.capabilities.agentActivityPublishing).toBe(false);
}).pipe(Effect.provide(testLayer));
}),
);
@@ -113,6 +182,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
}).pipe(
Effect.provide(
ServerEnvironment.layer.pipe(
Layer.provide(emptySecretStoreLayer),
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
),
),
@@ -9,6 +9,8 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { readAgentActivityPublishingActive } from "../cloud/config.ts";
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
@@ -66,6 +68,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
@@ -148,6 +151,7 @@ export const make = Effect.gen(function* () {
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadViewState: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
@@ -156,13 +160,22 @@ export const make = Effect.gen(function* () {
return ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.succeed(descriptor),
// The publish opt-in and relay link change at runtime (`t3 connect
// publish`, the client settings toggle), so the capability is read per
// descriptor request rather than baked in at startup.
getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
Effect.map((agentActivityPublishing) => ({
...descriptor,
capabilities: { ...descriptor.capabilities, agentActivityPublishing },
})),
),
});
});
/**
* ServerEnvironment is acquired from persisted filesystem and host-process
* state. It intentionally has no fallback Layer.succeed value: callers must
* provide the external platform services and a ServerConfig.
* provide the external platform services, a ServerConfig, and the
* ServerSecretStore backing the descriptor's publishing capability.
*/
export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));
-45
View File
@@ -28,11 +28,6 @@ import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
storeAttachmentUpload,
validateAttachmentUploadToken,
} from "./assets/AttachmentUpload.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -231,46 +226,6 @@ export const assetRouteLayer = HttpRouter.add(
}),
);
export const attachmentUploadRouteLayer = HttpRouter.add(
"POST",
`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
if (token.length === 0) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
// Invalid, tampered, and expired tokens are indistinguishable from
// missing ones on purpose, matching the signed asset GET route.
const claims = yield* validateAttachmentUploadToken(token);
if (!claims) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const contentLength = Number(request.headers["content-length"] ?? "");
if (!Number.isInteger(contentLength) || contentLength !== claims.sizeBytes) {
return HttpServerResponse.text("Content-Length must match the minted upload size.", {
status: 400,
});
}
const body = yield* request.arrayBuffer.pipe(Effect.orElseSucceed(() => null));
if (body === null) {
return HttpServerResponse.text("Failed to read the upload body.", { status: 400 });
}
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(body));
return stored.ok
? HttpServerResponse.empty({ status: 204 })
: HttpServerResponse.text(stored.detail, { status: stored.status });
}),
);
export const staticAndDevRouteLayer = HttpRouter.add(
"GET",
"*",
+81 -9
View File
@@ -1,20 +1,92 @@
import { describe, expect, it } from "vite-plus/test";
import { inferImageExtension } from "./imageMime.ts";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
describe("imageMime", () => {
it("maps known image mime types to extensions", () => {
expect(inferImageExtension({ mimeType: "image/png" })).toBe(".png");
expect(inferImageExtension({ mimeType: "image/jpeg" })).toBe(".jpg");
expect(inferImageExtension({ mimeType: "IMAGE/WEBP" })).toBe(".webp");
it("parses base64 data URL with mime type", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("falls back to a safe file name extension", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.PNG" })).toBe(".png");
it("parses base64 data URL with mime parameters", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("falls back to .bin when nothing safe matches", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.exe" })).toBe(".bin");
it("rejects non-base64 data URL", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
});
it("rejects missing mime type", () => {
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
});
it("parses base64 data URL with spaces in payload", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("rejects payload with characters outside the base64 alphabet", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
});
it("rejects structurally malformed base64", () => {
// '=' before the trailing padding position
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
// more than two padding characters
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
// length not a multiple of 4
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
});
it("accepts base64 with one or two trailing padding characters", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
mimeType: "image/png",
base64: "SGVsbA==",
});
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8h",
});
});
it("rejects empty and whitespace-only payloads", () => {
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
});
it("parses a case-insensitive scheme and mime type", () => {
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses a multi-megabyte payload from a deep call stack", () => {
// Regression: matching the payload with a regex borrowed the JS call
// stack, so a ~10 MB image parsed inside fiber execution threw
// "RangeError: Maximum call stack size exceeded".
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
const findMaxDepth = (depth: number): number => {
try {
return findMaxDepth(depth + 1);
} catch {
return depth;
}
};
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
expect(result?.mimeType).toBe("image/png");
expect(result?.base64.length).toBe(14_000_000);
});
it("does not read inherited keys from mime extension map", () => {
+83
View File
@@ -29,6 +29,89 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".webp",
]);
// Whether `code` is a character the base64 payload may contain, aside from
// the whitespace handled separately below.
function isBase64Char(code: number): boolean {
return (
(code >= 0x61 && code <= 0x7a) || // a-z
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2b || // +
code === 0x2f || // /
code === 0x3d // =
);
}
function isBase64Whitespace(code: number): boolean {
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
}
// Data URLs carry the full image payload, so this parser must never run a
// regex across the payload: V8's regex engine borrows the JS call stack, and
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
// execution) throws "Maximum call stack size exceeded".
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const trimmed = dataUrl.trim();
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
const commaIndex = trimmed.indexOf(",");
if (commaIndex === -1) return null;
const header = trimmed.slice(5, commaIndex);
if (header.length === 0) return null;
const headerParts: Array<string> = [];
for (const part of header.split(";")) {
const partTrimmed = part.trim();
if (partTrimmed.length > 0) {
headerParts.push(partTrimmed);
}
}
if (headerParts.length < 2) {
return null;
}
const trailingToken = headerParts.at(-1)?.toLowerCase();
if (trailingToken !== "base64") {
return null;
}
const mimeType = headerParts[0]?.toLowerCase();
if (!mimeType) return null;
const payload = trimmed.slice(commaIndex + 1);
const runs: Array<string> = [];
let runStart = -1;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (isBase64Char(code)) {
if (runStart === -1) runStart = index;
continue;
}
if (!isBase64Whitespace(code)) return null;
if (runStart !== -1) {
runs.push(payload.slice(runStart, index));
runStart = -1;
}
}
if (runStart !== -1) {
runs.push(payload.slice(runStart));
}
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
if (base64.length === 0 || base64.length % 4 !== 0) return null;
const firstPad = base64.indexOf("=");
if (firstPad !== -1) {
// '=' is only valid as one or two trailing padding characters; Node's
// decoder would otherwise silently truncate at the first '='.
if (base64.length - firstPad > 2) return null;
for (let index = firstPad; index < base64.length; index += 1) {
if (base64.charCodeAt(index) !== 0x3d) return null;
}
}
return { mimeType, base64 };
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -237,6 +237,64 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
yield* eventStore.append({
type: "thread.viewed",
eventId: EventId.make("evt-viewed-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:03.000Z",
commandId: CommandId.make("cmd-viewed-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-viewed-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
viewedAt: "2026-01-01T00:00:03.000Z",
},
});
yield* projectionPipeline.bootstrap;
const viewedRows = yield* sql<{
readonly viewedAt: string;
readonly updatedAt: string;
}>`
SELECT
viewed_at AS "viewedAt",
updated_at AS "updatedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(viewedRows, [
{
viewedAt: "2026-01-01T00:00:03.000Z",
updatedAt: "2026-01-01T00:00:02.000Z",
},
]);
yield* eventStore.append({
type: "thread.marked-unread",
eventId: EventId.make("evt-marked-unread-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:04.000Z",
commandId: CommandId.make("cmd-marked-unread-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-marked-unread-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
viewedAt: "2025-12-31T23:59:59.999Z",
},
});
yield* projectionPipeline.bootstrap;
const markedUnreadRows = yield* sql<{ readonly viewedAt: string }>`
SELECT viewed_at AS "viewedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(markedUnreadRows, [{ viewedAt: "2025-12-31T23:59:59.999Z" }]);
}),
);
});
@@ -617,6 +617,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: event.payload.createdAt,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
@@ -695,6 +696,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.viewed":
case "thread.marked-unread": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
viewedAt: event.payload.viewedAt,
});
return;
}
case "thread.snoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -321,6 +321,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-02-24T00:00:02.000Z",
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -440,6 +441,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-02-24T00:00:02.000Z",
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -424,6 +424,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -460,6 +461,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -498,6 +500,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -940,6 +943,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -1573,6 +1577,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1780,6 +1785,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1916,6 +1922,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2061,6 +2068,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2340,6 +2348,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
viewedAt: threadRow.value.viewedAt ?? threadRow.value.createdAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
@@ -2461,6 +2470,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
viewedAt: threadRow.value.viewedAt ?? threadRow.value.createdAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
@@ -1,138 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import {
type ClientOrchestrationCommand,
CommandId,
MessageId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
WorkspacePaths.layer,
ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
).pipe(Layer.provideMerge(NodeServices.layer));
const UUID = "00000000-0000-4000-8000-0000000000aa";
function turnStartCommand(attachment: {
readonly id: string;
readonly sizeBytes: number;
}): ClientOrchestrationCommand {
return {
type: "thread.turn.start",
commandId: CommandId.make("command-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "look at this",
attachments: [
{
type: "image",
id: attachment.id,
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: attachment.sizeBytes,
},
],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: "2026-08-01T00:00:00.000Z",
};
}
describe("normalizeDispatchCommand attachments", () => {
it.effect("claims a pending upload: renames the file and rewrites the id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${UUID}.png`);
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(pendingPath, bytes);
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments).toHaveLength(1);
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`))).toBe(
true,
);
}).pipe(Effect.provide(testLayer)),
);
it.effect("is idempotent when a retry references an already-claimed file", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`), bytes);
// The retry still carries the original pending id.
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the referenced upload does not exist", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 6 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("not found");
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the stored size does not match the reference", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.join(config.attachmentsDir, `pending-${UUID}.png`),
Buffer.from("pixels"),
);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 999 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("size");
}).pipe(Effect.provide(testLayer)),
);
it.effect("refuses an attachment already claimed by another thread", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `other-thread-${UUID}.png`), bytes);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("another thread");
}).pipe(Effect.provide(testLayer)),
);
});
+52 -38
View File
@@ -1,15 +1,18 @@
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import {
type ClientOrchestrationCommand,
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { planAttachmentClaim } from "../attachmentStore.ts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { parseBase64DataUrl } from "../imageMime.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const canonicalizeClientCommandTimestamps = (
@@ -45,6 +48,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
const receivedAt = DateTime.formatIso(yield* DateTime.now);
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
@@ -100,57 +104,67 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
return canonicalCommand as OrchestrationCommand;
}
// Attachments arrive as id references to bytes already uploaded via the
// signed upload URL flow. Each `pending-<uuid>` file is renamed to its
// thread segment here; the uuid never changes, so signed asset URLs and
// send retries (which may reference an already-renamed file) keep working.
const normalizedAttachments = yield* Effect.forEach(
canonicalCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const claimPlan = planAttachmentClaim({
attachmentsDir: serverConfig.attachmentsDir,
threadId: canonicalCommand.threadId,
attachmentId: attachment.id,
});
if (!claimPlan.ok) {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: ${claimPlan.reason}.`,
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
const attachmentId = createAttachmentId(canonicalCommand.threadId);
if (!attachmentId) {
return yield* new OrchestrationDispatchCommandError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment = {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
return yield* new OrchestrationDispatchCommandError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
() =>
new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,
cause,
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to persist attachment '${attachment.name}'.`,
}),
),
);
if (Number(stats.size) !== attachment.sizeBytes) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: stored size does not match the reference.`,
});
}
if (!claimPlan.alreadyScoped) {
yield* fileSystem.rename(claimPlan.currentPath, claimPlan.finalPath).pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
cause,
}),
),
);
}
return {
...attachment,
id: claimPlan.finalId,
mimeType: attachment.mimeType.toLowerCase(),
};
return persistedAttachment;
}),
{ concurrency: 1 },
);
+4
View File
@@ -11,6 +11,8 @@ import {
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadViewedPayload as ContractsThreadViewedPayloadSchema,
ThreadMarkedUnreadPayload as ContractsThreadMarkedUnreadPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
@@ -43,6 +45,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadViewedPayload = ContractsThreadViewedPayloadSchema;
export const ThreadMarkedUnreadPayload = ContractsThreadMarkedUnreadPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
+69
View File
@@ -7,6 +7,7 @@ import {
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -561,6 +562,74 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.view": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
const cappedViewedAt = DateTime.make(command.viewedThrough).pipe(
Option.filter(
(viewedThrough) => DateTime.Order(viewedThrough, DateTime.makeUnsafe(occurredAt)) <= 0,
),
Option.as(command.viewedThrough),
Option.getOrElse(() => occurredAt),
);
const viewedAt = DateTime.make(thread.viewedAt ?? thread.createdAt).pipe(
Option.filter(
(previousViewedAt) =>
DateTime.Order(previousViewedAt, DateTime.makeUnsafe(cappedViewedAt)) >= 0,
),
Option.as(thread.viewedAt ?? thread.createdAt),
Option.getOrElse(() => cappedViewedAt),
);
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.viewed",
payload: {
threadId: command.threadId,
viewedAt,
},
};
}
case "thread.mark-unread": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
const latestCompletedAt = thread.latestTurn?.completedAt;
const viewedAt =
latestCompletedAt == null
? (thread.viewedAt ?? thread.createdAt)
: DateTime.make(latestCompletedAt).pipe(
Option.map(DateTime.subtractDuration("1 millis")),
Option.map(DateTime.formatIso),
Option.getOrElse(() => thread.viewedAt ?? thread.createdAt),
);
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.marked-unread",
payload: {
threadId: command.threadId,
viewedAt,
},
};
}
case "thread.snooze": {
const thread = yield* requireThreadNotArchived({
readModel,
@@ -0,0 +1,99 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
import { decideOrchestrationCommand } from "./decider.ts";
const COMPLETED_AT = "2026-01-01T00:01:00.000Z";
const VIEWED_THROUGH = "2026-01-01T00:00:45.000Z";
function makeReadModel(): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:01.000Z",
completedAt: COMPLETED_AT,
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: COMPLETED_AT,
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-01-01T00:00:30.000Z",
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: COMPLETED_AT,
};
}
it.layer(NodeServices.layer)("thread view-state decider", (it) => {
it.effect("stamps a view at the acknowledged boundary", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse("2026-01-02T00:00:00.000Z"));
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.view",
commandId: CommandId.make("cmd-view"),
threadId: ThreadId.make("thread-1"),
viewedThrough: VIEWED_THROUGH,
},
readModel: makeReadModel(),
});
const viewed = Array.isArray(event) ? event[0] : event;
expect(viewed?.type).toBe("thread.viewed");
if (viewed?.type === "thread.viewed") {
expect(viewed.payload.viewedAt).toBe(VIEWED_THROUGH);
}
}),
);
it.effect("marks unread just before the latest completion", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-unread",
commandId: CommandId.make("cmd-mark-unread"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(),
});
const markedUnread = Array.isArray(event) ? event[0] : event;
expect(markedUnread?.type).toBe("thread.marked-unread");
if (markedUnread?.type === "thread.marked-unread") {
expect(markedUnread.payload.viewedAt).toBe("2026-01-01T00:00:59.999Z");
}
}),
);
});
@@ -84,5 +84,29 @@ it.effect("projects settled lifecycle events", () =>
);
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
const viewedAt = "2026-01-01T00:00:01.000Z";
const viewed = yield* projectEvent(
activityUnsettled,
makeEvent({
sequence: 5,
type: "thread.viewed",
payload: { threadId: ThreadId.make("thread-1"), viewedAt },
}),
);
expect(viewed.threads[0]?.viewedAt).toBe(viewedAt);
expect(viewed.threads[0]?.updatedAt).toBe(now);
const markedUnreadAt = "2025-12-31T23:59:59.999Z";
const markedUnread = yield* projectEvent(
viewed,
makeEvent({
sequence: 6,
type: "thread.marked-unread",
payload: { threadId: ThreadId.make("thread-1"), viewedAt: markedUnreadAt },
}),
);
expect(markedUnread.threads[0]?.viewedAt).toBe(markedUnreadAt);
expect(markedUnread.threads[0]?.updatedAt).toBe(now);
}),
);
@@ -30,6 +30,8 @@ import {
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadViewedPayload,
ThreadMarkedUnreadPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -381,6 +383,26 @@ export function projectEvent(
})),
);
case "thread.viewed":
return decodeForEvent(ThreadViewedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
viewedAt: payload.viewedAt,
}),
})),
);
case "thread.marked-unread":
return decodeForEvent(ThreadMarkedUnreadPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
viewedAt: payload.viewedAt,
}),
})),
);
case "thread.snoozed":
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -45,6 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at,
settled_override,
settled_at,
viewed_at,
snoozed_until,
snoozed_at,
pinned_at,
@@ -72,6 +73,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.viewedAt ?? row.createdAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
@@ -99,6 +101,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
viewed_at = excluded.viewed_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
@@ -133,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -169,6 +173,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -53,6 +53,7 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
import Migration0041 from "./Migrations/041_ProjectionThreadsViewedAt.ts";
/**
* Migration loader with all migrations defined inline.
@@ -105,6 +106,7 @@ export const migrationEntries = [
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
[40, "ProjectionProjectFaviconPath", Migration0040],
[41, "ProjectionThreadsViewedAt", Migration0041],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,47 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("041_ProjectionThreadsViewedAt", (it) => {
it.effect("adds viewed_at and marks historical rows viewed", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 40 });
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
runtime_mode,
interaction_mode,
created_at,
updated_at
) VALUES (
'thread-1',
'project-1',
'Historical thread',
'full-access',
'default',
'2026-01-01T00:00:00.000Z',
'2026-01-02T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 41 });
const rows = yield* sql<{ readonly viewedAt: string | null }>`
SELECT viewed_at AS "viewedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.equal(rows[0]?.viewedAt, "2026-01-02T00:00:00.000Z");
}),
);
});
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "viewed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN viewed_at TEXT
`;
}
// Upgrading must not make every historical completion appear unread.
yield* sql`
UPDATE projection_threads
SET viewed_at = COALESCE(viewed_at, updated_at, created_at)
WHERE viewed_at IS NULL
`;
});
@@ -39,6 +39,7 @@ export const ProjectionThread = Schema.Struct({
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
viewedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
+535 -25
View File
@@ -1,35 +1,61 @@
import * as NodeNet from "node:net";
import { it as effectIt } from "@effect/vitest";
import {
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
PREVIEW_URL_MAX_LENGTH,
type DiscoveredLocalServer,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Net from "@t3tools/shared/Net";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import { expect } from "vite-plus/test";
import { FetchHttpClient } from "effect/unstable/http";
import * as ProcessRunner from "../processRunner.ts";
import * as PortScanner from "./PortScanner.ts";
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.fail(
new ProcessRunner.ProcessSpawnError({
command: input.command,
argumentCount: input.args.length,
cwd: input.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "PowerShell is not installed in the test environment",
}),
const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
Effect.fail(
new ProcessRunner.ProcessSpawnError({
command: input.command,
argumentCount: input.args.length,
cwd: input.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "PowerShell is not installed in the test environment",
}),
),
}),
);
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: processProbeFailure,
});
const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"]) =>
let integrationListeningPort: number | null = null;
const TestIntegrationNet = Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: (port) => Effect.sync(() => port !== integrationListeningPort),
hasListenerOnHost: (port) => Effect.sync(() => port === integrationListeningPort),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
});
const makeProbeFailureLayer = (
run: ProcessRunner.ProcessRunner["Service"]["run"],
fetch: typeof globalThis.fetch = globalThis.fetch,
) =>
PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -37,23 +63,70 @@ const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"
Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
}),
Layer.succeed(HostProcessPlatform, "linux"),
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
),
),
);
const TestPortDiscoveryLive = PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(TestProcessRunner, Net.layer, Layer.succeed(HostProcessPlatform, "win32")),
Layer.mergeAll(
TestProcessRunner,
TestIntegrationNet,
Layer.succeed(HostProcessPlatform, "win32"),
FetchHttpClient.layer,
),
),
);
const openServer = (port: number): Effect.Effect<NodeNet.Server | null> =>
const LSOF_TEST_PORT = 43_123;
const makeLsofScannerLayer = (input: {
readonly pid: () => number;
readonly fetch: typeof globalThis.fetch;
}) =>
PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(ProcessRunner.ProcessRunner, {
run: () =>
Effect.succeed({
stdout: `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
stderr: "",
code: null,
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
}),
Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
}),
Layer.succeed(HostProcessPlatform, "linux"),
FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
),
),
),
);
const openServer = (
port: number,
onConnection: (socket: NodeNet.Socket) => void,
): Effect.Effect<NodeNet.Server | null> =>
Effect.callback((resume) => {
const server = NodeNet.createServer();
const server = NodeNet.createServer(onConnection);
server.once("error", () => {
resume(Effect.succeed(null));
});
@@ -72,9 +145,10 @@ const closeServer = (server: NodeNet.Server): Effect.Effect<void> =>
const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
ports: ReadonlyArray<number>,
onConnection: (socket: NodeNet.Socket) => void,
) {
for (const port of ports) {
const server = yield* openServer(port);
const server = yield* openServer(port, onConnection);
if (server !== null) return { port, server };
}
return yield* Effect.die(
@@ -83,8 +157,46 @@ const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(fun
});
const commonDevServer = Effect.acquireRelease(
openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
({ server }) => closeServer(server),
openCommonDevServer(PortScanner.COMMON_DEV_PORTS, (socket) => {
socket.once("data", () => {
socket.end("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 5\r\n\r\nhello");
});
}).pipe(
Effect.tap(({ port }) =>
Effect.sync(() => {
integrationListeningPort = port;
}),
),
),
({ server }) =>
closeServer(server).pipe(
Effect.ensuring(
Effect.sync(() => {
integrationListeningPort = null;
}),
),
),
);
const commonNonHttpServer = Effect.acquireRelease(
openCommonDevServer(PortScanner.COMMON_DEV_PORTS.toReversed(), (socket) => {
socket.on("error", () => undefined);
socket.once("data", () => socket.end("MYSQL\r\n\r\n"));
}).pipe(
Effect.tap(({ port }) =>
Effect.sync(() => {
integrationListeningPort = port;
}),
),
),
({ server }) =>
closeServer(server).pipe(
Effect.ensuring(
Effect.sync(() => {
integrationListeningPort = null;
}),
),
),
);
/**
@@ -94,7 +206,7 @@ const commonDevServer = Effect.acquireRelease(
*/
effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
it.effect(
"scan() returns a server we just opened on a curated dev port",
"scan() returns an HTTP server we just opened on a curated dev port",
Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
const { port } = yield* commonDevServer;
const scanner = yield* PortScanner.PortDiscovery;
@@ -105,13 +217,23 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
}),
);
it.effect(
"scan() excludes a listening port that does not speak HTTP",
Effect.fn("PortScannerTest.scanExcludesNonHttpServer")(function* () {
const { port } = yield* commonNonHttpServer;
const scanner = yield* PortScanner.PortDiscovery;
const result = yield* scanner.scan();
expect(result.some((server) => server.port === port)).toBe(false);
}),
);
it.effect(
"retain drives an immediate broadcast to subscribers",
Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
const { port } = yield* commonDevServer;
const received: number[] = [];
const scanner = yield* PortScanner.PortDiscovery;
yield* scanner.subscribe((servers) =>
yield* scanner.subscribe({ configuredUrls: [], initialSnapshot: [] }, (servers) =>
Effect.sync(() => {
for (const server of servers) received.push(server.port);
}),
@@ -122,7 +244,395 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
);
});
effectIt("does not swallow process probe defects", () =>
effectIt.effect("revalidates a successful HTML probe after its cache entry expires", () => {
let responds = true;
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return responds
? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
: Promise.reject(new TypeError("not HTTP"));
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect(yield* scanner.scan()).toHaveLength(1);
expect(yield* scanner.scan()).toHaveLength(1);
expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
responds = false;
yield* TestClock.adjust(Duration.seconds(15));
expect(yield* scanner.scan()).toHaveLength(0);
expect(requests).toEqual([
`http://localhost:${LSOF_TEST_PORT}/`,
`http://localhost:${LSOF_TEST_PORT}/`,
`https://localhost:${LSOF_TEST_PORT}/`,
]);
}).pipe(Effect.provide(layer));
});
effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
const requests: string[] = [];
const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
const url = String(input);
requests.push(url);
return Promise.resolve(
url === configuredUrl
? new Response("docs", { headers: { "content-type": "text/html" } })
: new Response("not found", {
status: 404,
headers: { "content-type": "text/html" },
}),
);
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const servers = yield* scanner.scan([configuredUrl]);
expect(servers).toHaveLength(1);
expect(servers[0]?.url).toBe(configuredUrl);
expect(requests).toContain(configuredUrl);
}).pipe(Effect.provide(layer));
});
effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
const customPort = 43_124;
const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
const expectedUrl = `http://localhost:${customPort}/docs`;
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
}) as typeof globalThis.fetch;
const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const servers = yield* scanner.scan([configuredUrl]);
expect(servers).toHaveLength(1);
expect(servers[0]?.host).toBe("localhost");
expect(servers[0]?.port).toBe(customPort);
expect(servers[0]?.url).toBe(expectedUrl);
expect(requests).toEqual([expectedUrl]);
}).pipe(Effect.provide(layer));
});
effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
const ipv4Url = "https://127.0.0.1:43125/docs";
const ipv6Url = "http://[::1]:43126/docs";
const wildcardPrefix = "http://0.0.0.0/";
const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
)}`;
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
}) as typeof globalThis.fetch;
const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
expect(requests).toEqual([ipv4Url, ipv6Url]);
}).pipe(Effect.provide(layer));
});
effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
const url = String(input);
return Promise.resolve(
url === docsUrl || url === adminUrl
? new Response("app", { headers: { "content-type": "text/html" } })
: new Response("not found", { status: 404 }),
);
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
Effect.sync(() => docsSnapshots.push(servers)),
);
yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
Effect.sync(() => adminSnapshots.push(servers)),
);
yield* scanner.retain;
expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
}).pipe(Effect.scoped, Effect.provide(layer));
});
effectIt.effect(
"keeps each subscriber's candidates when their combined union exceeds the per-client cap",
() => {
const firstSubscriberUrls = Array.from(
{ length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
(_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
);
const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
Promise.resolve(
String(input) === secondSubscriberUrl
? new Response("app", { headers: { "content-type": "text/html" } })
: new Response("not found", { status: 404 }),
)) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
yield* scanner.subscribe(
{ configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
() => Effect.void,
);
yield* scanner.subscribe(
{ configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
(servers) => Effect.sync(() => secondSnapshots.push(servers)),
);
yield* scanner.retain;
expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
}).pipe(Effect.scoped, Effect.provide(layer));
},
);
effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
const url = String(input);
requests.push(url);
return Promise.resolve(
url === docsUrl || url === adminUrl
? new Response("app", { headers: { "content-type": "text/html" } })
: new Response("not found", { status: 404 }),
);
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const docsScope = yield* Scope.make();
yield* scanner
.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
.pipe(Effect.provideService(Scope.Scope, docsScope));
yield* scanner.subscribe(
{ configuredUrls: [adminUrl], initialSnapshot: [] },
() => Effect.void,
);
yield* scanner.retain;
yield* Scope.close(docsScope, Exit.void);
requests.length = 0;
yield* TestClock.adjust(Duration.seconds(15));
expect(requests).toContain(adminUrl);
expect(requests).not.toContain(docsUrl);
}).pipe(Effect.scoped, Effect.provide(layer));
});
effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
const requestCount = requests.length;
expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
expect(requests).toHaveLength(requestCount);
}).pipe(Effect.provide(layer));
});
effectIt.effect("shares a configured root probe with discovered-root classification", () => {
const requests: string[] = [];
const rootUrl = `http://localhost:${LSOF_TEST_PORT}/`;
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
expect(requests).toEqual([rootUrl]);
yield* TestClock.adjust(Duration.seconds(15));
expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
expect(requests).toEqual([rootUrl, rootUrl]);
}).pipe(Effect.provide(layer));
});
effectIt.effect("starts fresh cache entries after the probing batch completes", () =>
Effect.gen(function* () {
const baseClock = yield* Clock.Clock;
const times = [0, 20_000, 20_000, 20_000];
let timeIndex = 0;
const currentTimeMillis = () => times[Math.min(timeIndex++, times.length - 1)]!;
const clock: Clock.Clock = {
...baseClock,
currentTimeMillisUnsafe: currentTimeMillis,
currentTimeMillis: Effect.sync(currentTimeMillis),
};
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
yield* Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect(yield* scanner.scan()).toHaveLength(1);
expect(yield* scanner.scan()).toHaveLength(1);
expect(requests).toHaveLength(1);
}).pipe(Effect.provide(layer), Effect.provideService(Clock.Clock, clock));
}),
);
effectIt.effect("caches a failed web probe until its bounded cache entry expires", () => {
let responds = false;
const requests: string[] = [];
const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
requests.push(String(input));
return responds
? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
: Promise.reject(new TypeError("not HTTP"));
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect(yield* scanner.scan()).toHaveLength(0);
expect(yield* scanner.scan()).toHaveLength(0);
expect(requests).toHaveLength(2);
responds = true;
yield* TestClock.adjust(Duration.seconds(15));
expect(yield* scanner.scan()).toHaveLength(1);
expect(requests).toHaveLength(3);
}).pipe(Effect.provide(layer));
});
effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
const redirects: Array<string | undefined> = [];
const fetchFn = (async (
input: Parameters<typeof globalThis.fetch>[0],
init?: Parameters<typeof globalThis.fetch>[1],
) => {
redirects.push(init?.redirect);
if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
return new Response(null, { status: 302, headers: { location: "https://example.com" } });
}) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const servers = yield* scanner.scan();
expect(servers).toHaveLength(1);
expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
expect(redirects).toEqual(["manual", "manual"]);
}).pipe(Effect.provide(layer));
});
effectIt.effect(
"excludes HTTP errors, non-navigation responses, and successful non-documents",
() => {
let pid = 1;
let makeResponse = () =>
new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
Promise.resolve(makeResponse())) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => pid, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () =>
new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () =>
new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () =>
new Response(null, { status: 204, headers: { "content-type": "text/html" } });
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () => new Response(null, { status: 302 });
expect(yield* scanner.scan()).toHaveLength(0);
pid += 1;
makeResponse = () =>
new Response("<html />", {
status: 200,
headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
});
expect(yield* scanner.scan()).toHaveLength(1);
}).pipe(Effect.provide(layer));
},
);
effectIt.effect("aborts HTTP and HTTPS probes when they time out", () => {
const aborted: string[] = [];
const fetchFn = ((
input: Parameters<typeof globalThis.fetch>[0],
init?: Parameters<typeof globalThis.fetch>[1],
) =>
new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const onAbort = () => {
aborted.push(String(input));
reject(new DOMException("Aborted", "AbortError"));
};
if (signal?.aborted) {
onAbort();
} else {
signal?.addEventListener("abort", onAbort, { once: true });
}
})) as typeof globalThis.fetch;
const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
const scanFiber = yield* Effect.forkChild(scanner.scan());
yield* TestClock.adjust(Duration.seconds(2));
expect(yield* Fiber.join(scanFiber)).toHaveLength(0);
expect(aborted).toEqual([
`http://localhost:${LSOF_TEST_PORT}/`,
`https://localhost:${LSOF_TEST_PORT}/`,
]);
}).pipe(Effect.provide(layer));
});
effectIt.effect("does not swallow process probe defects", () =>
Effect.gen(function* () {
const defect = new Error("unexpected process probe defect");
const layer = makeProbeFailureLayer(() => Effect.die(defect));
@@ -140,7 +650,7 @@ effectIt("does not swallow process probe defects", () =>
}),
);
effectIt("does not swallow process probe interruption", () =>
effectIt.effect("does not swallow process probe interruption", () =>
Effect.gen(function* () {
const layer = makeProbeFailureLayer(() => Effect.interrupt);
+305 -31
View File
@@ -8,29 +8,49 @@
* Windows / lsof missing: checks a curated list of common dev ports through
* the shared Net service.
*
* Listening ports are published only after a bounded HTTP(S) probe finds a
* successful HTML document or a redirect to one.
* Positive and negative results are cached briefly by candidate URL and listener identity,
* limiting repeated requests without leaving stale classifications around.
*
* Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
* polls forever, but each tick is a no-op when the retain count is zero.
*/
import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
import {
CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
PREVIEW_URL_MAX_LENGTH,
ThreadId,
type DiscoveredLocalServer,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Net from "@t3tools/shared/Net";
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
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 Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import * as ProcessRunner from "../processRunner.ts";
export class PortDiscovery extends Context.Service<
PortDiscovery,
{
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
readonly scan: (
configuredUrls?: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
readonly subscribe: (
input: {
readonly configuredUrls: ReadonlyArray<string>;
readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
},
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
) => Effect.Effect<void, never, Scope.Scope>;
readonly retain: Effect.Effect<void, never, Scope.Scope>;
@@ -53,12 +73,20 @@ export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
const POLL_INTERVAL = Duration.seconds(3);
const LSOF_TIMEOUT_MS = 5_000;
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
const WEB_PROBE_TIMEOUT = Duration.seconds(1);
const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
const WEB_PROBE_CONCURRENCY = 16;
const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
interface ScannerState {
interface ListenerSubscription {
readonly configuredUrls: ReadonlyArray<string>;
readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
readonly listeners: ReadonlySet<Listener>;
}
interface ScannerState {
readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
readonly terminalProcesses: ReadonlyMap<
string,
{
@@ -74,11 +102,86 @@ interface TerminalProcessOwner {
readonly terminalId: string;
}
interface WebProbeCacheEntry {
readonly pid: number | null;
readonly isWeb: boolean;
readonly expiresAtMillis: number;
}
interface WebProbeGroup {
readonly server: DiscoveredLocalServer;
readonly urls: ReadonlyArray<string>;
readonly configuredKey: string | null;
}
interface WebProbeSnapshot {
readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
}
const terminalOwnerKey = (owner: {
readonly threadId: string;
readonly terminalId: string;
}): string => `${owner.threadId}\u0000${owner.terminalId}`;
const parseConfiguredUrl = (raw: string): URL | null => {
try {
const url = new URL(raw);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
if (!isLoopbackHost(url.hostname)) return null;
return url;
} catch {
return null;
}
};
const localServerKey = (host: string, port: number): string =>
`${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
const urlPort = (url: URL): number =>
url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
const webProbeCacheKey = (raw: string): string => {
const url = new URL(raw);
url.hash = "";
return url.href;
};
const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
...new Set(
urls
.slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
.filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
.map(parseConfiguredUrl)
.filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
.map((url) => {
if (url.hostname === "0.0.0.0") url.hostname = "localhost";
return url.href;
})
.filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
),
];
const projectWebProbeSnapshot = (
snapshot: WebProbeSnapshot,
configuredUrls: ReadonlyArray<string>,
): ReadonlyArray<DiscoveredLocalServer> => {
const visibleByServer = new Map<string, DiscoveredLocalServer>();
for (const raw of normalizeConfiguredUrls(configuredUrls)) {
const url = new URL(raw);
const port = urlPort(url);
const serverKey = localServerKey(url.hostname, port);
if (visibleByServer.has(serverKey)) continue;
const configured = snapshot.configured.get(webProbeCacheKey(raw));
if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
}
for (const server of snapshot.discovered) {
const key = localServerKey(server.host, server.port);
if (!visibleByServer.has(key)) visibleByServer.set(key, server);
}
return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
};
const parseLsofOutput = (
raw: string,
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
@@ -190,12 +293,14 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
const net = yield* Net.NetService;
const processRunner = yield* ProcessRunner.ProcessRunner;
const hostPlatform = yield* HostProcessPlatform;
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
const stateRef = yield* Ref.make<ScannerState>({
lastSnapshot: [],
listeners: new Set(),
listeners: new Map(),
terminalProcesses: new Map(),
retainCount: 0,
});
const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
const scanSemaphore = yield* Semaphore.make(1);
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
const results = yield* Effect.forEach(
@@ -221,6 +326,149 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
}));
});
const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
httpClient.get(url).pipe(
Effect.map((response) => {
const location = response.headers.location?.trim();
if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
if (response.status < 200 || response.status >= 300) return null;
if (response.status === 204 || response.status === 205) return null;
const contentType = response.headers["content-type"]
?.split(";", 1)[0]
?.trim()
.toLowerCase();
return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
}),
Effect.scoped,
Effect.timeoutOption(WEB_PROBE_TIMEOUT),
Effect.map(Option.getOrNull),
Effect.orElseSucceed(() => null),
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
),
);
const makeWebProbeGroups = (
servers: ReadonlyArray<DiscoveredLocalServer>,
configuredUrls: ReadonlyArray<string>,
): ReadonlyArray<WebProbeGroup> => {
const serversByKey = new Map(
servers.map((server) => [localServerKey(server.host, server.port), server] as const),
);
const groups: WebProbeGroup[] = [];
const configuredResources = new Set<string>();
for (const raw of configuredUrls) {
const url = new URL(raw);
const port = urlPort(url);
const key = localServerKey(url.hostname, port);
const resourceKey = webProbeCacheKey(raw);
if (configuredResources.has(resourceKey)) continue;
configuredResources.add(resourceKey);
groups.push({
server: serversByKey.get(key) ?? {
host: url.hostname,
port,
url: raw,
processName: null,
pid: null,
terminal: null,
},
urls: [raw],
configuredKey: resourceKey,
});
}
for (const server of servers) {
groups.push({
server,
urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
configuredKey: null,
});
}
return groups;
};
const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
servers: ReadonlyArray<DiscoveredLocalServer>,
configuredUrls: ReadonlyArray<string>,
) {
const nowMillis = yield* Clock.currentTimeMillis;
const cached = yield* Ref.get(webProbeCacheRef);
const groups = makeWebProbeGroups(servers, configuredUrls);
const batchProbes = new Map<
string,
Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
>();
const batchProbeSemaphore = yield* Semaphore.make(1);
const getProbe = (url: string, pid: number | null) => {
const key = webProbeCacheKey(url);
const identity = `${key}\u0000${pid ?? ""}`;
return batchProbeSemaphore
.withPermits(1)(
Effect.gen(function* () {
const existing = batchProbes.get(identity);
if (existing) return [existing] as const;
const cachedProbe = cached.get(key);
const cachedIsCurrent =
cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
const memoized = yield* Effect.cached(
cachedIsCurrent
? Effect.succeed({ probe: cachedProbe, fresh: false })
: probeWebUrl(url).pipe(
Effect.map((result) => ({
probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
fresh: true,
})),
),
);
batchProbes.set(identity, memoized);
return [memoized] as const;
}),
)
.pipe(Effect.flatMap(([probe]) => probe));
};
const probed = yield* Effect.forEach(
groups,
(group) =>
Effect.gen(function* () {
const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
let visibleUrl: string | null = null;
for (const url of group.urls) {
const key = webProbeCacheKey(url);
const { probe, fresh } = yield* getProbe(url, group.server.pid);
probes.push([key, probe, fresh]);
if (probe.isWeb) {
visibleUrl = url;
break;
}
}
return { group, probes, visibleUrl };
}),
{ concurrency: WEB_PROBE_CONCURRENCY },
);
const completedAtMillis = yield* Clock.currentTimeMillis;
const nextCache = new Map(
[...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
);
const discovered: DiscoveredLocalServer[] = [];
const configured = new Map<string, DiscoveredLocalServer>();
for (const { group, probes, visibleUrl } of probed) {
for (const [key, probe, fresh] of probes) {
nextCache.set(
key,
fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
);
}
if (visibleUrl === null) continue;
const server = { ...group.server, url: visibleUrl };
if (group.configuredKey === null) discovered.push(server);
else configured.set(group.configuredKey, server);
}
yield* Ref.set(webProbeCacheRef, nextCache);
return { discovered, configured } satisfies WebProbeSnapshot;
});
const recoverProcessProbeFailure =
(probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
@@ -229,7 +477,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
platform: hostPlatform,
}).pipe(Effect.as(null));
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
configuredUrls: ReadonlyArray<string>,
) {
const state = yield* Ref.get(stateRef);
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
for (const registration of state.terminalProcesses.values()) {
@@ -259,8 +509,8 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
ProcessTimeoutError: recoverWindowsProbeFailure,
}),
);
if (listeners !== null) return listeners;
return yield* probeCommonPorts();
if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);
return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
}
const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
const lsofResult = yield* processRunner
@@ -281,27 +531,47 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
ProcessTimeoutError: recoverLsofProbeFailure,
}),
);
if (lsofResult !== null) return lsofResult;
return yield* probeCommonPorts();
if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
});
const broadcast = Effect.fn("PortDiscovery.broadcast")(function* (
servers: ReadonlyArray<DiscoveredLocalServer>,
) {
const listeners = (yield* Ref.get(stateRef)).listeners;
yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });
});
const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
(configuredUrls: ReadonlyArray<string>) =>
scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
);
const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
const normalized = normalizeConfiguredUrls(configuredUrls);
return scanSnapshot(normalized).pipe(
Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
);
};
const pollTick = Effect.fn("PortDiscovery.pollTick")(
function* () {
if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
const next = yield* scanOnce();
const changed = yield* Ref.modify(stateRef, (state) =>
serversEqual(state.lastSnapshot, next)
? [false, state]
: [true, { ...state, lastSnapshot: next }],
);
if (changed) yield* broadcast(next);
const configuredUrls = [
...new Set(
[...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
(subscription) => subscription.configuredUrls,
),
),
];
const snapshot = yield* scanSnapshot(configuredUrls);
const notifications = yield* Ref.modify(stateRef, (state) => {
const listeners = new Map(state.listeners);
const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
for (const [listener, subscription] of listeners) {
const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
if (serversEqual(subscription.lastSnapshot, next)) continue;
listeners.set(listener, { ...subscription, lastSnapshot: next });
changed.push([listener, next]);
}
return [changed, { ...state, listeners }];
});
yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
discard: true,
});
},
Effect.catchCause((cause: Cause.Cause<never>) =>
Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
@@ -332,15 +602,19 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
);
const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
(listener) =>
(input, listener) =>
Effect.acquireRelease(
Ref.update(stateRef, (state) => ({
...state,
listeners: new Set([...state.listeners, listener]),
})),
Ref.update(stateRef, (state) => {
const listeners = new Map(state.listeners);
listeners.set(listener, {
configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
lastSnapshot: input.initialSnapshot,
});
return { ...state, listeners };
}),
() =>
Ref.update(stateRef, (state) => {
const listeners = new Set(state.listeners);
const listeners = new Map(state.listeners);
listeners.delete(listener);
return { ...state, listeners };
}),
+2 -1
View File
@@ -35,6 +35,7 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
isAgentActivityPublishingEnabledValue,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_ISSUER_SECRET,
@@ -102,7 +103,7 @@ export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | n
}
export function isAgentActivityPublishingEnabled(value: string | null): boolean {
return value === "true";
return isAgentActivityPublishingEnabledValue(value);
}
export function resolveAgentActivityPublishingStartupState(input: {
+10 -4
View File
@@ -107,6 +107,7 @@ import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as GitManager from "./git/GitManager.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -650,10 +651,15 @@ const buildAppUnderTest = (options?: {
}),
),
Layer.provide(
Layer.mock(ExternalLauncher.ExternalLauncher)({
resolveAvailableEditors: () => Effect.succeed([]),
...options?.layers?.externalLauncher,
}),
Layer.mergeAll(
Layer.mock(ExternalLauncher.ExternalLauncher)({
resolveAvailableEditors: () => Effect.succeed([]),
...options?.layers?.externalLauncher,
}),
Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
resolveTargets: () => Effect.succeed([]),
}),
),
),
Layer.provide(
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({
+2 -2
View File
@@ -13,7 +13,6 @@ import * as ServerConfig from "./config.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
serverEnvironmentHttpApiLayer,
staticAndDevRouteLayer,
browserApiCorsLayer,
@@ -82,6 +81,7 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlRe
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -421,6 +421,7 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsService.layer),
Layer.provideMerge(ExternalLauncher.layer),
Layer.provideMerge(RemoteOpenTargets.layer),
Layer.provideMerge(ServerLifecycleEvents.layer),
Layer.provide(NetService.layer),
);
@@ -452,7 +453,6 @@ export const makeRoutesLayer = Layer.mergeAll(
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
),
+120
View File
@@ -24,6 +24,7 @@ import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";
import * as ProcessRunner from "../processRunner.ts";
@@ -953,6 +954,125 @@ it.layer(
}),
);
it.effect("derives subprocess activity for every terminal from one shared process snapshot", () =>
Effect.gen(function* () {
const runCalls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
// FakePtyAdapter assigns pids starting at 9000, so the two terminals
// opened below run as pids 9000 and 9001.
const psStdout = [" 100 9000 vim", " 101 100 git", " 200 9001 /usr/bin/python3"].join(
"\n",
);
const processRunner: ProcessRunner.ProcessRunner["Service"] = {
run: (input) =>
Effect.sync(() => {
runCalls.push({ command: input.command, args: input.args });
return {
stdout: psStdout,
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
};
const { manager, getEvents } = yield* createManager(5, {
subprocessPollIntervalMs: 20,
}).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
Effect.provide(withHostPlatform("linux")),
);
yield* manager.open(openInput());
yield* manager.open(openInput({ threadId: "thread-2" }));
yield* waitFor(
Effect.map(
getEvents,
(events) =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.label === "vim",
) &&
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.label === "python3",
),
),
"1200 millis",
);
yield* waitFor(
Effect.sync(() => runCalls.length >= 3),
"1200 millis",
);
// Every spawn is the shared table snapshot — no per-terminal `pgrep`
// or per-child `ps -p` invocations.
expect(runCalls.every((call) => call.args.join(" ") === "-eo pid=,ppid=,comm=")).toBe(true);
}),
);
it.effect("keeps last known subprocess state when the process snapshot fails", () =>
Effect.gen(function* () {
let failSnapshots = false;
let failedCalls = 0;
const processRunner: ProcessRunner.ProcessRunner["Service"] = {
run: () =>
Effect.sync(() => {
if (failSnapshots) failedCalls += 1;
return {
stdout: failSnapshots ? "" : " 100 9000 vim",
stderr: "",
code: ChildProcessSpawner.ExitCode(failSnapshots ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
};
const { manager, getEvents } = yield* createManager(5, {
subprocessPollIntervalMs: 20,
}).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
Effect.provide(withHostPlatform("linux")),
);
yield* manager.open(openInput());
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.label === "vim",
),
),
"1200 millis",
);
failSnapshots = true;
yield* waitFor(
Effect.sync(() => failedCalls >= 3),
"1200 millis",
);
// A failed snapshot is not authoritative: no terminal flips to idle.
const activityEvents = (yield* getEvents).filter((event) => event.type === "activity");
expect(activityEvents.length).toBeGreaterThan(0);
expect(activityEvents.every((event) => event.hasRunningSubprocess === true)).toBe(true);
}),
);
it.effect("caps persisted history to configured line limit", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(3);
+191 -229
View File
@@ -89,12 +89,21 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
"TerminalSubprocessCheckError",
{
cause: Schema.optional(Schema.Defect()),
terminalPid: Schema.Number,
command: Schema.Literals(["powershell", "pgrep", "ps"]),
command: Schema.Literals(["powershell", "ps"]),
exitCode: Schema.optional(Schema.NullOr(Schema.Number)),
timedOut: Schema.optional(Schema.Boolean),
stdoutTruncated: Schema.optional(Schema.Boolean),
},
) {
override get message(): string {
return `Failed to inspect terminal subprocesses for PID ${this.terminalPid} with ${this.command}`;
const details = [
this.exitCode !== undefined && this.exitCode !== null ? `exit code ${this.exitCode}` : null,
this.timedOut ? "timed out" : null,
this.stdoutTruncated ? "output truncated" : null,
]
.filter((detail) => detail !== null)
.join(", ");
return `Failed to inspect terminal subprocesses with ${this.command}${details.length > 0 ? ` (${details})` : ""}`;
}
}
@@ -610,247 +619,170 @@ function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
);
}
function parseFirstChildPidFromPgrep(stdout: string): number | null {
interface TerminalProcessTableSnapshot {
readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
readonly commandById: ReadonlyMap<number, string>;
}
function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot {
const childrenByParent = new Map<number, number[]>();
const commandById = new Map<number, string>();
for (const line of stdout.split(/\r?\n/g)) {
const n = Number.parseInt(line.trim(), 10);
if (Number.isInteger(n) && n > 0) {
return n;
}
// `comm=` is the final column and may itself contain spaces, so only the
// first two tokens are structural.
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
if (!match) continue;
const pid = Number(match[1]);
const ppid = Number(match[2]);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
commandById.set(pid, (match[3] ?? "").trim());
const children = childrenByParent.get(ppid) ?? [];
children.push(pid);
childrenByParent.set(ppid, children);
}
return null;
return { childrenByParent, commandById };
}
function windowsInspectSubprocess(
terminalPid: number,
platform: NodeJS.Platform,
): Effect.Effect<
TerminalSubprocessInspectResult,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const command =
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
// powershell.exe is a real executable — never spawn it through cmd.exe
// shell mode, which would re-tokenize the `-Command` payload (pipes,
// semicolons) before PowerShell ever sees it.
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
}).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const processNameById = new Map<number, string>();
const childrenByParent = new Map<number, number[]>();
for (const line of result.stdout.split(/\r?\n/g)) {
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const parentPid = Number(parentPidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
processNameById.set(pid, nameRaw?.trim() ?? "");
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
const directChildren = childrenByParent.get(terminalPid) ?? [];
const childPid = directChildren[0];
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const processIds = new Set<number>([terminalPid]);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
}
const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? "", platform);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
} as const;
}),
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "powershell",
}),
),
);
function parseWindowsProcessTable(stdout: string): TerminalProcessTableSnapshot {
const childrenByParent = new Map<number, number[]>();
const commandById = new Map<number, string>();
for (const line of stdout.split(/\r?\n/g)) {
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const parentPid = Number(parentPidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
commandById.set(pid, nameRaw?.trim() ?? "");
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
return { childrenByParent, commandById };
}
const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(function* (
function deriveSubprocessInspectResult(
snapshot: TerminalProcessTableSnapshot,
terminalPid: number,
platform: NodeJS.Platform,
): Effect.fn.Return<
TerminalSubprocessInspectResult,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const runPgrep = processRunner
.run({
command: "pgrep",
args: ["-P", String(terminalPid)],
timeout: "1 second",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "pgrep",
}),
),
);
const runPs = processRunner
.run({
command: "ps",
args: ["-eo", "pid=,ppid="],
timeout: "1 second",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "ps",
}),
),
);
let childPid: number | null = null;
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
if (pgrepResult.value.code === 0) {
childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout);
} else if (pgrepResult.value.code === 1) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
}
if (childPid === null) {
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
childPid = pid;
break;
}
}
}
if (childPid === null) {
): TerminalSubprocessInspectResult {
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? [])[0];
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
const runComm = processRunner.run({
command: "ps",
args: ["-p", String(childPid), "-o", "comm="],
timeout: "1 second",
maxOutputBytes: 8_192,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
const commResult = yield* Effect.exit(runComm);
let rawComm: string | null = null;
if (commResult._tag === "Success" && commResult.value && commResult.value.code === 0) {
rawComm = commResult.value.stdout.trim();
}
if (!rawComm || rawComm.length === 0) {
const runArgs = processRunner.run({
command: "ps",
args: ["-p", String(childPid), "-o", "args="],
timeout: "1 second",
maxOutputBytes: 16_384,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
const argsResult = yield* Effect.exit(runArgs);
if (argsResult._tag === "Success" && argsResult.value && argsResult.value.code === 0) {
const first = argsResult.value.stdout.trim().split(/\s+/)[0] ?? "";
rawComm = first.length > 0 ? first : null;
}
}
const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null;
const processIds = new Set<number>([terminalPid]);
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Success" && psResult.value.code === 0) {
const childrenByParent = new Map<number, number[]>();
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParent.get(ppid) ?? [];
children.push(pid);
childrenByParent.set(ppid, children);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const child of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(child)) continue;
processIds.add(child);
pending.push(child);
}
}
} else {
processIds.add(childPid);
}
const normalized = normalizeChildCommandName(snapshot.commandById.get(childPid) ?? "", platform);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
};
}
const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const;
// Resolve `ps` to an absolute path once at startup. Spawning by bare name
// walks every PATH entry per spawn (one failed posix_spawn per directory
// until the hit), which is measurable at a 1s poll cadence on long PATHs.
const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
for (const candidate of POSIX_PS_ABSOLUTE_PATHS) {
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (exists) return candidate;
}
return "ps";
});
function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) {
return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot")(function* (
psCommand: string,
): Effect.fn.Return<
TerminalProcessTableSnapshot,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
command: psCommand,
args: ["-eo", "pid=,ppid=,comm="],
timeout: "1 second",
maxOutputBytes: 524_288,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
command: "ps",
}),
),
);
if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
// Not authoritative: an empty or partial table would mark every terminal
// idle and clear its registered process ids. Failing skips the tick.
return yield* new TerminalSubprocessCheckError({
command: "ps",
exitCode: result.code,
timedOut: result.timedOut,
stdoutTruncated: result.stdoutTruncated,
});
}
return parsePosixProcessTable(result.stdout);
});
const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(
function* (): Effect.fn.Return<
TerminalProcessTableSnapshot,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const command =
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
// powershell.exe is a real executable — never spawn it through cmd.exe
// shell mode, which would re-tokenize the `-Command` payload (pipes,
// semicolons) before PowerShell ever sees it.
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
command: "powershell",
}),
),
);
if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
// Not authoritative: an empty or partial table would mark every terminal
// idle and clear its registered process ids. Failing skips the tick.
return yield* new TerminalSubprocessCheckError({
command: "powershell",
exitCode: result.code,
timedOut: result.timedOut,
stdoutTruncated: result.stdoutTruncated,
});
}
if (platform === "win32") {
return yield* windowsInspectSubprocess(terminalPid, platform);
}
return yield* posixInspectSubprocess(terminalPid, platform);
});
}
return parseWindowsProcessTable(result.stdout);
},
);
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
@@ -1227,12 +1159,27 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const processRunner = yield* ProcessRunner.ProcessRunner;
const subprocessInspector =
options.subprocessInspector ??
((terminalPid) =>
defaultSubprocessInspectorForPlatform(platform)(terminalPid).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
));
// One process-table snapshot per poll tick, shared across every terminal.
// Per-terminal `pgrep`/`ps` calls multiply spawn load by terminal count and
// can exhaust the PID space on hosts with many sessions (#6332).
const fetchProcessTableSnapshot = (
platform === "win32"
? windowsProcessTableSnapshot()
: posixProcessTableSnapshot(yield* resolvePosixPsCommand())
).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner));
const customSubprocessInspector = options.subprocessInspector;
const acquireSubprocessInspector: Effect.Effect<
TerminalSubprocessInspector,
TerminalSubprocessCheckError
> =
customSubprocessInspector !== undefined
? Effect.succeed(customSubprocessInspector)
: Effect.map(
fetchProcessTableSnapshot,
(snapshot): TerminalSubprocessInspector =>
(terminalPid) =>
Effect.succeed(deriveSubprocessInspectResult(snapshot, terminalPid, platform)),
);
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
@@ -2064,6 +2011,21 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
return;
}
const inspectorOption = yield* acquireSubprocessInspector.pipe(
Effect.map(Option.some),
Effect.catch((reason) =>
Effect.logWarning("failed to snapshot processes for terminal subprocess polling", {
reason,
}).pipe(Effect.as(Option.none<TerminalSubprocessInspector>())),
),
);
if (Option.isNone(inspectorOption)) {
return;
}
const subprocessInspector = inspectorOption.value;
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
session: TerminalSessionState & { pid: number },
) {
@@ -950,6 +950,27 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("reports changes to a file named HEAD", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
yield* writeTextFile(cwd, "HEAD", "first line\n");
yield* git(cwd, ["add", "HEAD"]);
yield* git(cwd, ["commit", "-m", "add HEAD file"]);
yield* writeTextFile(cwd, "HEAD", "first line\nsecond line\n");
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.isRepo, true);
assert.equal(status.hasWorkingTreeChanges, true);
assert.deepInclude(status.workingTree.files, {
path: "HEAD",
insertions: 1,
deletions: 0,
});
}),
);
it.effect("reports default-branch delta separately from upstream delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
Loaded 100 of 273 files, more files were not shown because too many files have changed in this diff. Show more