Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 6dce6cd70e style(server): format workspace filesystem assertion
Co-authored-by: Julius Marminge <[email protected]>
2026-07-15 16:11:27 +00:00
Cursor AgentandJulius Marminge 578bd20eb6 refactor(server): model bootstrap timeout with Duration
Co-authored-by: Julius Marminge <[email protected]>
2026-07-15 16:09:01 +00:00
Cursor AgentandJulius Marminge 7c8c0b673c refactor(server): use Effect filesystem for workspace reads
Co-authored-by: Julius Marminge <[email protected]>
2026-07-15 16:08:56 +00:00
124 changed files with 608 additions and 8309 deletions

No files matched your search

@@ -1,134 +0,0 @@
name: Mobile Showcase Screenshots
on:
workflow_dispatch:
inputs:
platform:
description: Device platforms to capture
required: true
default: all
type: choice
options:
- all
- ios
- android
appearance:
description: System appearances to capture
required: true
default: both
type: choice
options:
- both
- dark
- light
permissions:
contents: read
env:
NODE_OPTIONS: --max-old-space-size=8192
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload iOS screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: app-store-connect-screenshots
path: artifacts/app-store/screenshots/apple/
if-no-files-found: warn
retention-days: 14
android:
name: Android phone, 7-inch tablet, and 10-inch tablet
if: inputs.platform == 'all' || inputs.platform == 'android'
runs-on: blacksmith-16vcpu-ubuntu-2404
timeout-minutes: 60
env:
T3_SHOWCASE_ANDROID_ABI: x86_64
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Setup Gradle cache
uses: gradle/actions/setup-gradle@v5
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Capture Android showcase
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 36
target: google_apis
arch: x86_64
profile: pixel_7_pro
avd-name: Pixel_10_Pro
cores: 8
ram-size: 4096M
disable-animations: false
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
- name: Validate Google Play assets
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload Android screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: google-play-screenshots
path: artifacts/app-store/screenshots/google-play/
if-no-files-found: warn
retention-days: 14
-3
View File
@@ -27,9 +27,6 @@ squashfs-root/
.gstack/
dist-electron/
.electron-runtime/
.showcase/
apps/mobile/.showcase/
artifacts/app-store/screenshots/
node_modules/
.alchemy/
*.log
@@ -10,7 +10,6 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
autoInstallOnAppQuit: true,
channel: "latest",
disableDifferentialDownload: false,
fullChangelog: false,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve([])),
on: vi.fn(),
@@ -34,7 +33,6 @@ describe("ElectronUpdater", () => {
autoUpdaterMock.autoInstallOnAppQuit = true;
autoUpdaterMock.channel = "latest";
autoUpdaterMock.disableDifferentialDownload = false;
autoUpdaterMock.fullChangelog = false;
autoUpdaterMock.checkForUpdates.mockClear();
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
autoUpdaterMock.downloadUpdate.mockClear();
@@ -100,18 +98,6 @@ describe("ElectronUpdater", () => {
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("sets full changelog mode", () =>
Effect.gen(function* () {
const updater = yield* ElectronUpdater.ElectronUpdater;
yield* updater.setFullChangelog(true);
assert.equal(autoUpdaterMock.fullChangelog, true);
yield* updater.setFullChangelog(false);
assert.equal(autoUpdaterMock.fullChangelog, false);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
@@ -66,7 +66,6 @@ export class ElectronUpdater extends Context.Service<
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
@@ -113,11 +112,6 @@ export const make = ElectronUpdater.of({
autoUpdater.allowDowngrade = value;
return Effect.void;
}),
setFullChangelog: (value) =>
Effect.suspend(() => {
autoUpdater.fullChangelog = value;
return Effect.void;
}),
setDisableDifferentialDownload: (value) =>
Effect.suspend(() => {
autoUpdater.disableDifferentialDownload = value;
@@ -35,7 +35,6 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
pickFolder,
setTheme,
@@ -49,7 +48,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
-2
View File
@@ -4,8 +4,6 @@ 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 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";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
+1 -21
View File
@@ -1,14 +1,10 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
import { getLocalEnvironmentBootstraps } from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
@@ -130,19 +126,3 @@ describe("getLocalEnvironmentBootstraps", () => {
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
});
});
describe("getWindowFullscreenState", () => {
it.effect("reads the current native window state", () => {
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
return Effect.gen(function* () {
assert.isTrue(yield* getWindowFullscreenState.handler());
}).pipe(
Effect.provide(
Layer.mock(ElectronWindow.ElectronWindow)({
currentMainOrFirst: Effect.succeed(Option.some(window)),
}),
),
);
});
});
-10
View File
@@ -55,16 +55,6 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = yield* electronWindow.currentMainOrFirst;
return Option.isSome(window) && window.value.isFullScreen();
}),
});
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
-13
View File
@@ -116,19 +116,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
getWindowFullscreenState: () =>
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
onWindowFullscreenStateChange: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
if (typeof fullscreen !== "boolean") return;
listener(fullscreen);
};
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) =>
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
@@ -38,7 +38,6 @@ const flushCallbacks = Effect.yieldNow;
function makeHarness(options: UpdatesHarnessOptions = {}) {
let checkCount = 0;
let allowDowngrade = false;
let fullChangelog = false;
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
const sentStates: DesktopUpdateState[] = [];
@@ -74,10 +73,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setFullChangelog: (value) =>
Effect.sync(() => {
fullChangelog = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
@@ -191,7 +186,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
layer,
checkCount: () => checkCount,
feedUrls: () => feedUrls,
fullChangelog: () => fullChangelog,
listenerCount: () =>
Array.from(listeners.values()).reduce(
(total, eventListeners) => total + eventListeners.size,
@@ -293,49 +287,6 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.setChannel("nightly");
assert.equal(harness.fullChangelog(), true);
harness.emit("update-available", {
version: "1.2.4-nightly.20260709.766",
releaseNotes: [
{
version: "1.2.4-nightly.20260709.766",
note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
},
{
version: "1.2.4-nightly.20260709.765",
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
},
],
});
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "available");
assert.deepEqual(state.releaseNotes, [
{
version: "1.2.4-nightly.20260709.766",
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
},
{
version: "1.2.4-nightly.20260709.765",
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
},
]);
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
+2 -13
View File
@@ -27,7 +27,6 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
import {
createInitialDesktopUpdateState,
@@ -50,10 +49,6 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
const UpdateInfo = Schema.Struct({
version: Schema.String,
// Left unvalidated on purpose: a malformed release-notes payload must never
// fail the decode and block the update state transition. The shape is
// validated defensively in normalizeDesktopUpdateReleaseNotes.
releaseNotes: Schema.optional(Schema.Unknown),
});
const DownloadProgressInfo = Schema.Struct({
@@ -335,12 +330,10 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.setChannel(channel);
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
yield* electronUpdater.setFullChangelog(allowsPrerelease);
yield* logUpdaterInfo("using update channel", {
channel,
allowPrerelease: allowsPrerelease,
allowDowngrade: allowsPrerelease,
fullChangelog: allowsPrerelease,
});
});
@@ -574,15 +567,11 @@ export const make = Effect.gen(function* () {
}
const checkedAt = yield* currentIsoTimestamp;
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
yield* setState(
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
);
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
yield* logUpdaterInfo("update available", {
version: info.version,
releaseNoteGroups: releaseNotes.length,
});
yield* logUpdaterInfo("update available", { version: info.version });
}),
),
Effect.catchCause((cause) => {
@@ -1,67 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
describe("normalizeDesktopUpdateReleaseNotes", () => {
it("splits a plain string note into items under the fallback version", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
"## What's changed\n- First fix\n- Second fix",
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
});
it("keeps per-version groups and drops empty ones", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Newer change" },
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
{ version: "1.2.1", note: "- Older change" },
],
"1.2.3",
);
expect(notes).toEqual([
{ version: "1.2.3", items: ["Newer change"] },
{ version: "1.2.1", items: ["Older change"] },
]);
});
it("decodes valid HTML entities", () => {
const notes = normalizeDesktopUpdateReleaseNotes("- Fix &amp; polish &#128512;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
});
it("ignores malformed entries instead of throwing", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Valid change" },
{ version: 42, note: "- Bad version type" },
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
"not an object",
null,
],
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
});
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
version: `1.3.${9 - index}`,
note: "Full changelog: https://example.com/compare/x...y",
}));
const notes = normalizeDesktopUpdateReleaseNotes(
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
"1.3.9",
);
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
});
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
expect(() =>
normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0"),
).not.toThrow();
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity &#9999999999;"] }]);
});
});
-125
View File
@@ -1,125 +0,0 @@
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
interface ElectronReleaseNoteInfo {
readonly version: string;
readonly note: string | null | undefined;
}
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
if (typeof value !== "object" || value === null) return false;
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
return (
typeof candidate.version === "string" &&
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
);
}
const MAX_RELEASE_NOTE_GROUPS = 6;
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
amp: "&",
apos: "'",
gt: ">",
lt: "<",
nbsp: " ",
quot: '"',
};
function decodeCodePoint(codePoint: number, entity: string): string {
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
// Number.isFinite alone lets oversized values (e.g. &#9999999999;) through.
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
return `&${entity};`;
}
return String.fromCodePoint(codePoint);
}
function decodeHtmlEntity(entity: string): string {
const named = HTML_ENTITY_REPLACEMENTS[entity];
if (named) return named;
if (entity.startsWith("#x")) {
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
}
if (entity.startsWith("#")) {
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
}
return `&${entity};`;
}
function decodeHtmlEntities(input: string): string {
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
decodeHtmlEntity(entity),
);
}
function stripMarkup(input: string): string {
return decodeHtmlEntities(
input
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<li\b[^>]*>/gi, "\n- ")
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
.replace(/<[^>]*>/g, "")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1"),
);
}
function truncateReleaseNoteItem(item: string): string {
if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
}
function isIgnoredReleaseNoteLine(line: string): boolean {
const normalized = line
.toLowerCase()
.replace(/[*_`#]/g, "")
.trim();
return (
normalized === "" ||
normalized === "what's changed" ||
normalized === "whats changed" ||
normalized === "full changelog" ||
normalized === "new contributors" ||
normalized.startsWith("compare: ") ||
normalized.includes("/compare/")
);
}
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
if (!note) return [];
const items: string[] = [];
for (const rawLine of stripMarkup(note).split("\n")) {
const item = rawLine
.trim()
.replace(/^[-*]\s+/, "")
.replace(/^\d+[.)]\s+/, "")
.replace(/\s+/g, " ");
if (isIgnoredReleaseNoteLine(item)) continue;
items.push(truncateReleaseNoteItem(item));
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
}
return items;
}
export function normalizeDesktopUpdateReleaseNotes(
releaseNotes: unknown,
fallbackVersion: string,
): ReadonlyArray<DesktopUpdateReleaseNote> {
const rawNotes =
typeof releaseNotes === "string"
? [{ version: fallbackVersion, note: releaseNotes }]
: Array.isArray(releaseNotes)
? releaseNotes.filter(isElectronReleaseNoteInfo)
: [];
return rawNotes
.map((entry) => ({
version: entry.version,
items: extractReleaseNoteItems(entry.note),
}))
.filter((entry) => entry.items.length > 0)
.slice(0, MAX_RELEASE_NOTE_GROUPS);
}
@@ -118,12 +118,6 @@ describe("updateMachine", () => {
});
it("tracks available, download start, and progress cleanly", () => {
const releaseNotes = [
{
version: "1.1.0",
items: ["feat: add update release notes"],
},
];
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
@@ -132,33 +126,15 @@ describe("updateMachine", () => {
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
releaseNotes,
);
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(available.releaseNotes).toBe(releaseNotes);
expect(downloading.releaseNotes).toBe(releaseNotes);
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
expect(progress.errorContext).toBeNull();
});
it("clears release notes when checking again", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
enabled: true,
status: "available",
availableVersion: "1.1.0-nightly.1",
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
},
"2026-03-04T00:00:00.000Z",
);
expect(state.releaseNotes).toEqual([]);
});
});
@@ -1,7 +1,6 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateReleaseNote,
DesktopUpdateState,
} from "@t3tools/contracts";
@@ -30,7 +29,6 @@ export function createInitialDesktopUpdateState(
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt: null,
message: null,
@@ -47,7 +45,6 @@ export function reduceDesktopUpdateStateOnCheckStart(
...state,
status: "checking",
checkedAt,
releaseNotes: [],
message: null,
downloadPercent: null,
errorContext: null,
@@ -75,14 +72,12 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
state: DesktopUpdateState,
version: string,
checkedAt: string,
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
): DesktopUpdateState {
return {
...state,
status: "available",
availableVersion: version,
downloadedVersion: null,
releaseNotes,
downloadPercent: null,
checkedAt,
message: null,
@@ -100,7 +95,6 @@ export function reduceDesktopUpdateStateOnNoUpdate(
status: "up-to-date",
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt,
message: null,
+2 -38
View File
@@ -28,7 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -46,7 +46,6 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
@@ -67,13 +66,10 @@ function makeFakeBrowserWindow() {
close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isFullScreen: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
loadURL: vi.fn(() => Promise.resolve()),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
on: vi.fn(),
once: vi.fn(),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
@@ -92,7 +88,6 @@ function makeFakeBrowserWindow() {
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
windowListeners,
};
}
@@ -343,37 +338,6 @@ describe("DesktopWindow", () => {
}),
);
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
if (!enterFullscreen || !leaveFullscreen) {
return yield* Effect.die("fullscreen listeners were not registered");
}
enterFullscreen();
leaveFullscreen();
assert.deepEqual(fakeWindow.send.mock.calls, [
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+1 -10
View File
@@ -15,7 +15,7 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
const TITLEBAR_HEIGHT = 40;
@@ -365,15 +365,6 @@ export const make = Effect.gen(function* () {
window.setTitle(environment.displayName);
});
if (environment.platform === "darwin") {
window.on("enter-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
});
window.on("leave-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
});
}
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
+2 -2
View File
@@ -35,8 +35,8 @@ vp run ios:dev
```
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
reduced-capability local build. Personal Team builds omit the widget and share extensions, push
entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
```bash
T3CODE_IOS_PERSONAL_TEAM=1 \
+3 -33
View File
@@ -84,9 +84,6 @@ function resolveAppVariant(value: string | undefined): AppVariant {
}
const variant = VARIANT_CONFIG[APP_VARIANT];
const iosBundleIdentifier = isIosPersonalTeamBuild
? personalTeamBundleIdentifier!
: variant.iosBundleIdentifier;
const dmSansFonts = {
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
@@ -97,8 +94,8 @@ const dmSansFonts = {
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
"expo-widgets",
{
bundleIdentifier: `${iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${iosBundleIdentifier}`,
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
@@ -114,30 +111,6 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
},
];
const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
"expo-sharing",
{
ios: {
// Personal Teams cannot sign App Groups or extension targets. Keep the
// reduced-capability local build usable while release builds expose the
// real system share target.
enabled: !isIosPersonalTeamBuild,
extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
appGroupId: `group.${iosBundleIdentifier}`,
activationRule: {
supportsText: true,
supportsWebUrlWithMaxCount: 1,
supportsImageWithMaxCount: 8,
},
},
android: {
enabled: true,
singleShareMimeTypes: ["text/plain", "image/*"],
multipleShareMimeTypes: ["image/*"],
},
},
];
// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
@@ -167,7 +140,7 @@ const config: ExpoConfig = {
ios: {
icon: variant.assets.iosIcon,
supportsTablet: true,
bundleIdentifier: iosBundleIdentifier,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
@@ -229,9 +202,6 @@ const config: ExpoConfig = {
],
"expo-secure-store",
"expo-sqlite",
...(isIosPersonalTeamBuild
? [sharingPlugin]
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
[
"expo-notifications",
{
-5
View File
@@ -1,6 +1,5 @@
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import { LogBox } from "react-native";
import { featureFlags } from "react-native-screens";
import App from "./src/App";
@@ -9,8 +8,4 @@ import App from "./src/App";
// native stack is rendered inside a non-fitToContents formSheet.
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
LogBox.ignoreAllLogs();
}
registerRootComponent(App);
@@ -7,32 +7,6 @@ class T3NativeControlsModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3NativeControls")
Function("getShowcasePairingUrl") {
appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
}
Function("getShowcaseScene") {
val storedScene = appContext.reactContext
?.filesDir
?.resolve("t3-showcase-scene")
?.takeIf { it.isFile }
?.readText()
?.trim()
?.takeIf { it.isNotEmpty() }
storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
}
Function("prepareShowcaseCapture") {
// Android app data is cleared by the host runner before launch.
}
Function("markShowcaseReady") { scene: String ->
appContext.reactContext
?.filesDir
?.resolve("t3-showcase-ready")
?.writeText(scene)
}
View(T3HeaderButtonView::class) {
Prop("label") { view: T3HeaderButtonView, label: String ->
view.setLabel(label)
@@ -1,48 +1,9 @@
import ExpoModulesCore
import Security
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3NativeControls")
Function("getShowcasePairingUrl") {
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
Function("getShowcaseScene") { () -> String? in
let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
.trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
return storedScene
}
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
Function("prepareShowcaseCapture") {
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
}
}
Function("markShowcaseReady") { (scene: String) in
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
}
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
@@ -30,10 +30,6 @@ class T3TerminalModule : Module() {
view.focusRequest = focusRequest
}
Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
view.autoFocus = autoFocus
}
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
view.appearanceScheme = appearanceScheme
}
@@ -76,17 +76,6 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
}
var autoFocus: Boolean = true
set(value) {
field = value
if (value) {
requestKeyboardFocus()
} else {
inputView.clearFocus()
hideKeyboard()
}
}
var backgroundColorHex: String = "#24292E"
set(value) {
field = value
@@ -379,13 +368,6 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
}
private fun hideKeyboard() {
val inputMethodManager = context.getSystemService(
Context.INPUT_METHOD_SERVICE
) as? InputMethodManager
inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
}
private fun applyTheme() {
setBackgroundColor(backgroundColorValue)
container.setBackgroundColor(backgroundColorValue)
@@ -7,7 +7,7 @@ public class T3TerminalModule: Module {
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
// logs so a stale native binary is distinguishable from a broken key pipeline.
Constants([
"hardwareKeyRevision": 3,
"hardwareKeyRevision": 2,
])
View(T3TerminalView.self) {
@@ -27,10 +27,6 @@ public class T3TerminalModule: Module {
view.focusRequest = focusRequest
}
Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in
view.autoFocus = autoFocus
}
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
view.appearanceScheme = appearanceScheme
}
@@ -119,21 +119,6 @@ private enum TerminalHardwareKeyEncoder {
}
}
private enum TerminalInputSequence {
/// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
/// which raw-mode TUIs may interpret as the literal J key.
static let carriageReturn = "\r"
static func normalizingReturn(_ input: String) -> String {
switch input {
case "\n", "\r\n":
return carriageReturn
default:
return input
}
}
}
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
@@ -248,17 +233,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
var autoFocus = true {
didSet {
guard oldValue != autoFocus else { return }
if autoFocus {
requestKeyboardFocus()
} else {
inputField.resignFirstResponder()
}
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
@@ -370,7 +344,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
public override func didMoveToWindow() {
super.didMoveToWindow()
guard window != nil, autoFocus else { return }
guard window != nil else { return }
DispatchQueue.main.async { [weak self] in
self?.requestKeyboardFocus()
}
@@ -378,9 +352,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if !string.isEmpty {
// Some software keyboards deliver Return through this delegate instead of
// textFieldShouldReturn, so normalize that path too.
emitInput(TerminalInputSequence.normalizingReturn(string))
emitInput(string)
return false
}
@@ -388,7 +360,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
emitInput(TerminalInputSequence.carriageReturn)
emitInput("\n")
textField.text = ""
return false
}
-3
View File
@@ -11,8 +11,6 @@
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
"start:prod": "APP_VARIANT=production expo start",
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
"screenshots": "node ../../scripts/mobile-showcase.ts",
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
"android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
@@ -93,7 +91,6 @@
"expo-paste-input": "^0.1.15",
"expo-quick-actions": "^6.0.2",
"expo-secure-store": "~56.0.4",
"expo-sharing": "~56.0.18",
"expo-splash-screen": "~56.0.10",
"expo-sqlite": "~56.0.5",
"expo-symbols": "~56.0.6",
@@ -1,93 +0,0 @@
"use strict";
// expo-sharing intentionally uses a fixed target name and also uses that
// internal target name as CFBundleDisplayName. Brand the extension while
// leaving its initially-empty signing team intact: Expo uses that state to
// select ios.appleTeamId and enable first-time profile provisioning.
//
// ORDERING: list this plugin BEFORE expo-sharing. Expo runs same-type mods in
// reverse registration order, so this executes after the extension exists.
const fs = require("fs");
const path = require("path");
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
const TARGET_NAME = "expo-sharing-extension";
function stripComments(section) {
return Object.fromEntries(
Object.entries(section ?? {}).filter(([key]) => !key.endsWith("_comment")),
);
}
function findByName(section, name) {
return Object.entries(stripComments(section)).find(([, value]) => value?.name === name) ?? null;
}
function escapeXml(value) {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&apos;");
}
function withDisplayNamePlist(config, displayName) {
return withDangerousMod(config, [
"ios",
(cfg) => {
const plistPath = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, "Info.plist");
if (!fs.existsSync(plistPath)) {
throw new Error(
`${TARGET_NAME}/Info.plist was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
);
}
const source = fs.readFileSync(plistPath, "utf8");
const displayNamePattern = /(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/;
if (!displayNamePattern.test(source)) {
throw new Error(`Could not update CFBundleDisplayName in ${plistPath}.`);
}
const next = source.replace(displayNamePattern, `$1${escapeXml(displayName)}$2`);
if (next !== source) {
fs.writeFileSync(plistPath, next);
}
return cfg;
},
]);
}
function withExtensionDisplayNameBuildSetting(config, displayName) {
return withXcodeProject(config, (cfg) => {
const objects = cfg.modResults.hash.project.objects;
const targetEntry = findByName(objects.PBXNativeTarget, TARGET_NAME);
if (!targetEntry) {
throw new Error(
`${TARGET_NAME} Xcode target was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
);
}
const target = targetEntry[1];
const configurationList = stripComments(objects.XCConfigurationList)[
target.buildConfigurationList
];
if (!configurationList) {
throw new Error(`Could not find build configurations for ${TARGET_NAME}.`);
}
const buildConfigurations = stripComments(objects.XCBuildConfiguration);
for (const reference of configurationList.buildConfigurations ?? []) {
const buildConfiguration = buildConfigurations[reference.value];
if (buildConfiguration?.buildSettings) {
buildConfiguration.buildSettings.INFOPLIST_KEY_CFBundleDisplayName = `"${displayName}"`;
}
}
return cfg;
});
}
module.exports = function withShareExtensionDisplayName(config) {
const displayName = config.name;
return withExtensionDisplayNameBuildSetting(
withDisplayNamePlist(config, displayName),
displayName,
);
};
+5 -16
View File
@@ -11,8 +11,6 @@ import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigati
import { RegistryContext } from "@effect/atom-react";
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
@@ -22,20 +20,13 @@ import { useThemeColor } from "./lib/useThemeColor";
import "../global.css";
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
prepareNativeShowcaseCapture();
}
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
// The Expo dev client launches the app via
// <scheme>://expo-development-client/?url=<packager> — that URL addresses
// the launcher, not app navigation. Without this filter it falls through
// to the NotFound wildcard route on every dev launch.
// expo-sharing uses a private lifecycle URL only to wake the app. The
// persisted share inbox below owns navigation once the payload is durable.
filter: (url: string) =>
!url.includes("expo-development-client") && !url.includes("://expo-sharing"),
filter: (url: string) => !url.includes("expo-development-client"),
};
const Navigation = createStaticNavigation(RootStack);
@@ -67,12 +58,10 @@ export default function App() {
the system is in dark mode. */}
{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}
<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>
<IncomingShareProvider>
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
</IncomingShareProvider>
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
<ConfirmDialogHost />
</BlurTargetView>
{/* Anchored-menu overlays render here — in-window, so the
-26
View File
@@ -10,7 +10,6 @@ import {
createNativeStackScreen,
type NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { useEffect, useRef } from "react";
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
@@ -48,17 +47,11 @@ import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnv
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
SettingsLegalDocumentCloseHeaderButton,
SettingsLegalDocumentExternalHeaderButton,
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
import {
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
transitionIncomingSharePresentation,
} from "./features/sharing/incoming-share-presentation";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
@@ -282,30 +275,12 @@ function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
}) {
const navigation = useNavigation();
const { pendingShare } = useIncomingShare();
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
useAppShortcuts(props.state);
useEffect(() => {
const topRouteName = props.state.routes[props.state.index]?.name;
const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
isShareSheetPresented: topRouteName === "NewTaskSheet",
pendingShareId: pendingShare?.id ?? null,
});
sharePresentationRef.current = transition.state;
if (!transition.shareIdToPresent) {
return;
}
navigation.navigate("NewTaskSheet", {
screen: "NewTask",
params: { incomingShareId: transition.shareIdToPresent },
});
}, [navigation, pendingShare, props.state]);
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
@@ -314,7 +289,6 @@ function RootStackLayout(props: {
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ShowcaseCaptureCoordinator pathname={pathname} />
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
@@ -33,8 +33,6 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnect
export function CloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
readonly showcaseSignedIn?: boolean;
/**
* Hide the "T3 Connect" section title + refresh button for hosts that
* provide their own chrome (the onboarding sheet's native header and
@@ -45,8 +43,7 @@ export function CloudEnvironmentRows(props: {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments =
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
@@ -67,7 +64,7 @@ export function CloudEnvironmentRows(props: {
const showHeader = props.showHeader ?? true;
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
if (!isSignedIn) return null;
return (
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
@@ -1,189 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
id: "file-1",
path: "example.ts",
language: "typescript",
additions: 0,
deletions: 0,
};
function makeLine(
input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
): NativeReviewDiffRow {
return {
kind: "line",
fileId: TYPESCRIPT_FILE.id,
...input,
};
}
function makeHunk(id: string): NativeReviewDiffRow {
return {
kind: "hunk",
id,
fileId: TYPESCRIPT_FILE.id,
text: "@@",
};
}
function highlight(
rows: ReadonlyArray<NativeReviewDiffRow>,
alreadyHighlightedRowIds?: ReadonlySet<string>,
) {
return highlightNativeReviewDiffVisibleRows({
rows,
files: [TYPESCRIPT_FILE],
scheme: "dark",
engine: "javascript",
firstRowIndex: 0,
lastRowIndex: rows.length - 1,
overscanRows: 0,
maxRows: 100,
alreadyHighlightedRowIds,
});
}
describe("highlightNativeReviewDiffVisibleRows", () => {
it("does not carry grammar state across hunk boundaries", async () => {
const exportRow = makeLine({
id: "export-row",
content: "export async function run() {}",
change: "add",
oldLineNumber: null,
newLineNumber: 100,
});
const rows = [
makeHunk("hunk-1"),
makeLine({
id: "import-open",
content: "import {",
change: "context",
oldLineNumber: 1,
newLineNumber: 1,
}),
makeLine({
id: "import-entry",
content: " Model,",
change: "context",
oldLineNumber: 2,
newLineNumber: 2,
}),
makeHunk("hunk-2"),
exportRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows),
highlight([makeHunk("standalone-hunk"), exportRow]),
]);
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
});
it("keeps grammar state across inline comment rows", async () => {
const openingRow = makeLine({
id: "template-open",
content: "const message = `open",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
});
const closingRow = makeLine({
id: "template-close",
content: "closed`;",
change: "add",
oldLineNumber: null,
newLineNumber: 2,
});
const trailingRow = makeLine({
id: "trailing-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 3,
});
const commentRow: NativeReviewDiffRow = {
kind: "comment",
id: "comment-1",
fileId: TYPESCRIPT_FILE.id,
commentText: "Review note",
};
const [withComment, contiguous] = await Promise.all([
highlight([openingRow, commentRow, closingRow, trailingRow]),
highlight([openingRow, closingRow, trailingRow]),
]);
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
});
it("does not join unhighlighted rows across cached gaps", async () => {
const trailingRow = makeLine({
id: "trailing-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 3,
});
const rows = [
makeLine({
id: "template-open",
content: "const message = `open",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
}),
makeLine({
id: "template-close",
content: "closed`;",
change: "add",
oldLineNumber: null,
newLineNumber: 2,
}),
trailingRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows, new Set(["template-close"])),
highlight([trailingRow]),
]);
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
standalone.tokensByRowId[trailingRow.id],
);
});
it("keeps deletion grammar state out of addition rows", async () => {
const additionRow = makeLine({
id: "addition-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
});
const rows = [
makeLine({
id: "deletion-row",
content: "const removed = `open",
change: "delete",
oldLineNumber: 1,
newLineNumber: null,
}),
additionRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows),
highlight([additionRow]),
]);
expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
standalone.tokensByRowId[additionRow.id],
);
});
});
@@ -56,11 +56,6 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
readonly content: string;
}
interface IndexedNativeReviewDiffLineRow {
readonly row: NativeReviewDiffLineRow;
readonly rowIndex: number;
}
export interface NativeReviewDiffTokenChunk {
readonly chunkIndex: number;
readonly fileId: string;
@@ -313,58 +308,6 @@ function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDi
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
}
function hasConsecutiveLineNumbers(
previous: number | null | undefined,
next: number | null | undefined,
): boolean {
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
}
function hasOnlyCommentRowsBetween(
rows: ReadonlyArray<NativeReviewDiffRow>,
previousRowIndex: number,
nextRowIndex: number,
): boolean {
for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
if (rows[rowIndex]?.kind !== "comment") {
return false;
}
}
return true;
}
function canShareGrammarContext(
previous: IndexedNativeReviewDiffLineRow,
next: IndexedNativeReviewDiffLineRow,
rows: ReadonlyArray<NativeReviewDiffRow>,
): boolean {
if (
next.row.fileId !== previous.row.fileId ||
!hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
) {
return false;
}
if (previous.row.change === "delete" || next.row.change === "delete") {
return (
previous.row.change !== "add" &&
next.row.change !== "add" &&
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
);
}
if (previous.row.change === "add" || next.row.change === "add") {
return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
}
return (
previous.row.change === "context" &&
next.row.change === "context" &&
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
);
}
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
for (const row of rows) {
@@ -417,7 +360,7 @@ export async function highlightNativeReviewDiffVisibleRows(
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
const selectedRows: NativeReviewDiffLineRow[] = [];
for (
let rowIndex = startIndex;
@@ -431,12 +374,12 @@ export async function highlightNativeReviewDiffVisibleRows(
!input.alreadyHighlightedRowIds?.has(row.id) &&
fileMap.has(row.fileId)
) {
selectedRows.push({ row, rowIndex });
selectedRows.push(row);
}
}
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
let segmentRows: NativeReviewDiffLineRow[] = [];
let segmentFile: NativeReviewDiffFile | undefined;
const flushSegment = () => {
@@ -446,34 +389,27 @@ export async function highlightNativeReviewDiffVisibleRows(
return;
}
const code = segmentRows.map(({ row }) => row.content).join("\n");
const code = segmentRows.map((row) => row.content).join("\n");
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
segmentRows.forEach(({ row }, rowIndex) => {
segmentRows.forEach((row, rowIndex) => {
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
});
segmentRows = [];
segmentFile = undefined;
};
for (const selectedRow of selectedRows) {
const { row } = selectedRow;
for (const row of selectedRows) {
const file = fileMap.get(row.fileId);
if (!file) {
continue;
}
const previousRow = segmentRows.at(-1);
if (
segmentFile &&
(segmentFile.id !== file.id ||
(previousRow !== undefined &&
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
) {
if (segmentFile && segmentFile.id !== file.id) {
flushSegment();
}
segmentFile = file;
segmentRows.push(selectedRow);
segmentRows.push(row);
}
flushSegment();
@@ -96,22 +96,5 @@ describe("isPendingNativeViewRegistration", () => {
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
),
).toBe(false);
expect(
isPendingNativeViewRegistration(
new Error(
"Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
),
),
).toBe(true);
});
});
describe("isNativeReviewDiffDrawEvent", () => {
it("accepts only native events emitted after diff rows draw", async () => {
const { isNativeReviewDiffDrawEvent } = await import("./nativeReviewDiffSurface");
expect(isNativeReviewDiffDrawEvent({ message: "draw-metrics" })).toBe(true);
expect(isNativeReviewDiffDrawEvent({ message: "visible-range" })).toBe(true);
expect(isNativeReviewDiffDrawEvent({ message: "rows-decoded" })).toBe(false);
});
});
@@ -149,10 +149,6 @@ export interface NativeReviewDiffViewHandle {
readonly scrollToTop: (animated?: boolean) => Promise<void>;
}
export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
return payload.message === "draw-metrics" || payload.message === "visible-range";
}
interface NativeReviewDiffViewRef {
readonly setRowsJson: (rowsJson: string) => Promise<void>;
readonly setTokensJson: (tokensJson: string) => Promise<void>;
@@ -174,11 +170,9 @@ let nativeReviewDiffViewResolutionFailed = false;
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
export function isPendingNativeViewRegistration(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
(error.message.includes("Unable to find the class") &&
error.message.includes("T3ReviewDiffView view with tag"))
error instanceof Error &&
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
);
}
@@ -167,6 +167,7 @@ export function HomeScreen(props: HomeScreenProps) {
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
@@ -56,7 +56,6 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { ThreadGitMenu } from "../threads/ThreadGitControls";
import { useReviewCacheForThread } from "./reviewState";
import {
isNativeReviewDiffDrawEvent,
type NativeReviewDiffViewHandle,
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
@@ -72,10 +71,8 @@ import { resolveReviewAvailability } from "./reviewAvailability";
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
import { buildReviewSectionMenu } from "./review-section-menu";
import type { ReviewSectionItem } from "./reviewModel";
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
const REVIEW_HEADER_SPACING = 0;
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
return (
@@ -397,7 +394,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
});
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
const showcasedReviewDrawRef = useRef<string | null>(null);
// Native pull-to-refresh on the diff surface (replaces the old Refresh menu item).
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
@@ -439,25 +435,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
selectedRowIds: commentSelection.selectedRowIds,
canHighlight: parsedDiff.kind === "files",
});
const showcaseReviewKey =
SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}`
: null;
const handleNativeDebug = useCallback(
(event: NativeSyntheticEvent<Record<string, unknown>>) => {
nativeBridge.onDebug(event);
if (
showcaseReviewKey === null ||
showcasedReviewDrawRef.current === showcaseReviewKey ||
!isNativeReviewDiffDrawEvent(event.nativeEvent)
) {
return;
}
showcasedReviewDrawRef.current = showcaseReviewKey;
markNativeShowcaseReady("review");
},
[nativeBridge.onDebug, showcaseReviewKey],
);
const handleSelectFile = useCallback(
(fileId: string | null) => {
@@ -811,7 +788,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
tokensPatchJson={nativeBridge.tokensPatchJson}
tokensResetKey={nativeBridge.tokensResetKey}
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
onDebug={handleNativeDebug}
onDebug={nativeBridge.onDebug}
onPressLine={commentSelection.onPressLine}
onVisibleFileChange={handleVisibleFileChange}
onToggleComment={nativeBridge.onToggleComment}
@@ -2,7 +2,7 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stac
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useState } from "react";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -15,15 +15,6 @@ import { splitEnvironmentSections } from "../connection/environmentSections";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import {
applyShowcaseLocalEnvironmentDisplayUrls,
resolveShowcaseEnvironmentUpdateDisplayUrl,
SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS,
} from "../showcase/showcaseEnvironmentRows";
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
export function SettingsEnvironmentsRouteScreen() {
const {
@@ -34,56 +25,18 @@ export function SettingsEnvironmentsRouteScreen() {
} = useRemoteConnections();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const environmentSections = splitEnvironmentSections({
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
const localEnvironments = SHOWCASE_ENABLED
? applyShowcaseLocalEnvironmentDisplayUrls(environmentSections.localEnvironments)
: environmentSections.localEnvironments;
const connectedCloudEnvironments = SHOWCASE_ENABLED
? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS
: environmentSections.connectedCloudEnvironments;
const hasLocalEnvironments = localEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const accentColor = useThemeColor("--color-icon-muted");
const headerIconColor = useThemeColor("--color-icon");
useEffect(() => {
if (!SHOWCASE_ENABLED) return;
const timer = setTimeout(() => markNativeShowcaseReady("environments"), 500);
return () => clearTimeout(timer);
}, []);
const handleToggle = useCallback((environmentId: EnvironmentId) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
const handleUpdateEnvironment = useCallback(
(
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
) => {
if (!SHOWCASE_ENABLED) return onUpdateEnvironment(environmentId, updates);
const actualEnvironment = environmentSections.localEnvironments.find(
(environment) => environment.environmentId === environmentId,
);
const presentedEnvironment = localEnvironments.find(
(environment) => environment.environmentId === environmentId,
);
return onUpdateEnvironment(environmentId, {
...updates,
displayUrl:
actualEnvironment && presentedEnvironment
? resolveShowcaseEnvironmentUpdateDisplayUrl({
actualDisplayUrl: actualEnvironment.displayUrl,
presentedDisplayUrl: presentedEnvironment.displayUrl,
submittedDisplayUrl: updates.displayUrl,
})
: updates.displayUrl,
});
},
[environmentSections.localEnvironments, localEnvironments, onUpdateEnvironment],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -139,7 +92,7 @@ export function SettingsEnvironmentsRouteScreen() {
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={handleUpdateEnvironment}
onUpdate={onUpdateEnvironment}
/>
</View>
))}
@@ -161,16 +114,10 @@ export function SettingsEnvironmentsRouteScreen() {
</View>
)}
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
{hasCloudPublicConfig() ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
{...(SHOWCASE_ENABLED
? {
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
showcaseSignedIn: true,
}
: {})}
/>
) : null}
</ScrollView>
@@ -1,310 +0,0 @@
import Constants from "expo-constants";
import * as Crypto from "expo-crypto";
import {
clearSharedPayloads,
getResolvedSharedPayloadsAsync,
getSharedPayloads,
type ResolvedSharePayload,
type SharePayload,
} from "expo-sharing";
import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { Alert, AppState, Platform } from "react-native";
import {
buildIncomingShareDraft,
type IncomingShareDestination,
type IncomingShareDraft,
} from "./incoming-share-model";
import { IncomingShareInbox } from "./incoming-share-inbox";
import {
loadIncomingShareDrafts,
removeIncomingShareDraft,
writeIncomingShareDraft,
} from "./incoming-share-storage";
type IncomingShareContextValue = {
readonly pendingShare: IncomingShareDraft | null;
readonly isLoading: boolean;
readonly error: Error | null;
readonly getShare: (shareId: string) => IncomingShareDraft | null;
readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
readonly releaseShareReservation: (
shareId: string,
expectedDestination: IncomingShareDestination,
) => Promise<void>;
readonly consumeShare: (shareId: string) => Promise<void>;
readonly refresh: () => Promise<void>;
};
const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
function receiveSharingEnabled(): boolean {
if (Platform.OS === "android") {
return true;
}
if (Platform.OS !== "ios") {
return false;
}
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
}
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
try {
return await getResolvedSharedPayloadsAsync();
} catch (error) {
// iOS already gives the containing app a copied file:// URL, so raw
// payloads remain usable. Android normally resolves content:// into a
// private cache file; its modern File API can still read the raw URI when
// resolution fails.
console.warn("[incoming-share] could not resolve shared file metadata", error);
return [];
}
}
async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
const fingerprint = JSON.stringify(
payloads.map((payload) => ({
shareType: payload.shareType,
mimeType: payload.mimeType ?? null,
value: payload.value,
})),
);
const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
return `share-${digest}`;
}
async function readBase64(uri: string): Promise<string> {
const { File } = await import("expo-file-system");
return new File(uri).base64();
}
async function removeOwnedFile(uri: string): Promise<void> {
if (!uri.startsWith("file:")) {
return;
}
try {
const { File } = await import("expo-file-system");
const file = new File(uri);
if (file.exists) {
file.delete();
}
} catch (error) {
console.warn("[incoming-share] could not remove temporary shared file", error);
}
}
async function removeReplayedImagePayloadFiles(
payloads: ReadonlyArray<SharePayload>,
): Promise<void> {
const uris = new Set<string>();
for (const payload of payloads) {
if (payload.shareType === "image") {
uris.add(payload.value);
}
}
if (uris.size === 0) {
return;
}
const resolvedPayloads = await resolvedPayloadsForImages();
for (const payload of resolvedPayloads) {
if (payload.shareType === "image" && payload.contentUri) {
uris.add(payload.contentUri);
}
}
await Promise.all([...uris].map(removeOwnedFile));
}
// Keep one operation queue across provider remounts (including development
// Strict Mode remounts) so two app lifecycle notifications cannot ingest the
// same native handoff independently.
const incomingShareInbox = new IncomingShareInbox({
loadDrafts: loadIncomingShareDrafts,
writeDraft: writeIncomingShareDraft,
removeDraft: removeIncomingShareDraft,
getPayloads: getSharedPayloads,
clearPayloads: clearSharedPayloads,
buildDraft: async ({ payloads, id, createdAt }) => {
const cleanupUris = new Set<string>();
const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")
? await resolvedPayloadsForImages()
: [];
const draft = await buildIncomingShareDraft({
payloads,
resolvedPayloads,
fileReader: {
readBase64,
removeOwnedFile: (uri) => {
cleanupUris.add(uri);
},
},
id,
createdAt,
});
return {
draft,
cleanup: async () => {
await Promise.all([...cleanupUris].map(removeOwnedFile));
},
};
},
cleanupReplayedPayloads: removeReplayedImagePayloadFiles,
idForPayloads: incomingShareIdForPayloads,
now: () => new Date().toISOString(),
onClearError: (error) => {
console.warn("[incoming-share] could not acknowledge native payload", error);
},
onCleanupError: (error) => {
console.warn("[incoming-share] could not remove temporary shared file", error);
},
});
export function IncomingShareProvider(props: React.PropsWithChildren) {
const enabled = receiveSharingEnabled();
const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const refreshPromiseRef = useRef<Promise<void> | null>(null);
const mountedRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const refresh = useCallback(async () => {
if (refreshPromiseRef.current) {
return refreshPromiseRef.current;
}
const operation = (async () => {
try {
const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
if (mountedRef.current) {
setDrafts(snapshot);
setError(null);
}
} catch (cause) {
const persisted = await incomingShareInbox
.refresh({ ingestNative: false })
.catch(() => null);
if (mountedRef.current) {
if (persisted) {
setDrafts(persisted);
}
setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
}
}
})().finally(() => {
refreshPromiseRef.current = null;
});
refreshPromiseRef.current = operation;
return operation;
}, [enabled]);
useEffect(() => {
void refresh().finally(() => {
if (mountedRef.current) {
setIsLoading(false);
}
});
}, [refresh]);
const refreshOnAppActive = useEffectEvent(() => {
void refresh();
});
useEffect(() => {
if (!enabled) {
return;
}
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") {
refreshOnAppActive();
}
});
return () => subscription.remove();
}, [enabled]);
useEffect(() => {
if (!error) {
return;
}
Alert.alert("Could not import shared content", error.message, [
{ text: "Dismiss", style: "cancel", onPress: () => setError(null) },
{
text: "Retry",
onPress: () => {
setError(null);
void refresh();
},
},
]);
}, [error, refresh]);
const consumeShare = useCallback(async (shareId: string) => {
const snapshot = await incomingShareInbox.consume(shareId);
if (mountedRef.current) {
setDrafts(snapshot);
}
}, []);
const reserveShare = useCallback(
async (shareId: string, destination: IncomingShareDestination) => {
const snapshot = await incomingShareInbox.reserve(shareId, destination);
if (mountedRef.current) {
setDrafts(snapshot);
}
},
[],
);
const releaseShareReservation = useCallback(
async (shareId: string, expectedDestination: IncomingShareDestination) => {
const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
if (mountedRef.current) {
setDrafts(snapshot);
}
},
[],
);
const getShare = useCallback(
(shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
[drafts],
);
const value = useMemo<IncomingShareContextValue>(
() => ({
pendingShare: drafts[0] ?? null,
isLoading,
error,
getShare,
releaseShareReservation,
reserveShare,
consumeShare,
refresh,
}),
[
consumeShare,
drafts,
error,
getShare,
isLoading,
refresh,
releaseShareReservation,
reserveShare,
],
);
return (
<IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
);
}
export function useIncomingShare(): IncomingShareContextValue {
const value = React.use(IncomingShareContext);
if (value === null) {
throw new Error("useIncomingShare must be used within IncomingShareProvider.");
}
return value;
}
@@ -1,236 +0,0 @@
import { describe, expect, it, vi } from "@effect/vitest";
import type { SharePayload } from "expo-sharing";
import type { IncomingShareDraft } from "./incoming-share-model";
import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox";
const PAYLOAD: SharePayload = {
shareType: "text",
mimeType: "text/plain",
value: "Fix this",
};
function draft(id: string, createdAt = "2026-07-16T08:00:00.000Z"): IncomingShareDraft {
return {
schemaVersion: 1,
id,
createdAt,
text: PAYLOAD.value,
attachments: [],
warnings: [],
};
}
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((next) => {
resolve = next;
});
return { promise, resolve };
}
function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {}) {
const persisted = new Map<string, IncomingShareDraft>();
let payloads: ReadonlyArray<SharePayload> = [PAYLOAD];
const dependencies: IncomingShareInboxDependencies = {
loadDrafts: async () => [...persisted.values()],
writeDraft: async (value) => {
persisted.set(value.id, value);
},
removeDraft: async (shareId) => {
persisted.delete(shareId);
},
getPayloads: () => payloads,
clearPayloads: () => {
payloads = [];
},
buildDraft: async ({ id, createdAt }) => ({
draft: draft(id, createdAt),
cleanup: async () => undefined,
}),
idForPayloads: async () => "share-stable",
now: () => "2026-07-16T08:00:00.000Z",
...overrides,
};
return { inbox: new IncomingShareInbox(dependencies), persisted };
}
describe("IncomingShareInbox", () => {
it("coalesces a replay of an already-persisted native handoff", async () => {
const buildDraft = vi.fn(async ({ id, createdAt }) => ({
draft: draft(id, createdAt),
cleanup: async () => undefined,
}));
const cleanupReplayedPayloads = vi.fn(async () => undefined);
const { inbox, persisted } = createHarness({ buildDraft, cleanupReplayedPayloads });
persisted.set("share-stable", draft("share-stable"));
await expect(inbox.refresh({ ingestNative: true })).resolves.toEqual([draft("share-stable")]);
expect(buildDraft).not.toHaveBeenCalled();
expect(cleanupReplayedPayloads).toHaveBeenCalledWith([PAYLOAD]);
});
it("serializes concurrent refreshes so one native payload creates one inbox item", async () => {
const building = deferred();
const buildDraft = vi.fn(async ({ id, createdAt }) => {
await building.promise;
return { draft: draft(id, createdAt), cleanup: async () => undefined };
});
const { inbox } = createHarness({ buildDraft });
const first = inbox.refresh({ ingestNative: true });
const second = inbox.refresh({ ingestNative: true });
building.resolve();
await expect(Promise.all([first, second])).resolves.toEqual([
[draft("share-stable")],
[draft("share-stable")],
]);
expect(buildDraft).toHaveBeenCalledTimes(1);
});
it("orders consumption after an in-flight refresh without restoring stale state", async () => {
const building = deferred();
const { inbox, persisted } = createHarness({
buildDraft: async ({ id, createdAt }) => {
await building.promise;
return { draft: draft(id, createdAt), cleanup: async () => undefined };
},
});
const refresh = inbox.refresh({ ingestNative: true });
const consume = inbox.consume("share-stable");
building.resolve();
await expect(refresh).resolves.toEqual([draft("share-stable")]);
await expect(consume).resolves.toEqual([]);
expect([...persisted.values()]).toEqual([]);
});
it("consumes only the addressed share when another share has identical content", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-first", draft("share-first", "2026-07-16T07:59:00.000Z"));
persisted.set("share-second", draft("share-second"));
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
draft("share-second"),
draft("share-first", "2026-07-16T07:59:00.000Z"),
]);
await expect(inbox.consume("share-second")).resolves.toEqual([
draft("share-first", "2026-07-16T07:59:00.000Z"),
]);
expect([...persisted.values()]).toEqual([draft("share-first", "2026-07-16T07:59:00.000Z")]);
});
it("keeps content-identical shares addressable by their own ids", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-open-flow", draft("share-open-flow", "2026-07-16T07:59:00.000Z"));
persisted.set("share-newer", draft("share-newer"));
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
draft("share-newer"),
draft("share-open-flow", "2026-07-16T07:59:00.000Z"),
]);
});
it("does not acknowledge a supported payload when its durable write fails", async () => {
const clearPayloads = vi.fn();
const cleanup = vi.fn(async () => undefined);
const { inbox } = createHarness({
clearPayloads,
buildDraft: async ({ id, createdAt }) => ({
draft: draft(id, createdAt),
cleanup,
}),
writeDraft: async () => {
throw new Error("disk full");
},
});
await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full");
expect(clearPayloads).not.toHaveBeenCalled();
expect(cleanup).not.toHaveBeenCalled();
});
it("durably reserves a share for one project before draft import", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-stable", draft("share-stable"));
const destination = { environmentId: "environment-1", projectId: "project-1" };
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
{ ...draft("share-stable"), destination },
]);
expect(persisted.get("share-stable")?.destination).toEqual(destination);
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
{ ...draft("share-stable"), destination },
]);
});
it("rejects moving a reserved share to another project", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-stable", {
...draft("share-stable"),
destination: { environmentId: "environment-1", projectId: "project-1" },
});
await expect(
inbox.reserve("share-stable", {
environmentId: "environment-1",
projectId: "project-2",
}),
).rejects.toThrow("already reserved");
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-1");
});
it("conditionally releases a reservation when its project is unavailable", async () => {
const { inbox, persisted } = createHarness();
const destination = { environmentId: "environment-1", projectId: "project-1" };
persisted.set("share-stable", { ...draft("share-stable"), destination });
await expect(inbox.releaseReservation("share-stable", destination)).resolves.toEqual([
draft("share-stable"),
]);
expect(persisted.get("share-stable")?.destination).toBeUndefined();
await expect(
inbox.reserve("share-stable", {
environmentId: "environment-2",
projectId: "project-2",
}),
).resolves.toEqual([
{
...draft("share-stable"),
destination: { environmentId: "environment-2", projectId: "project-2" },
},
]);
});
it("does not release a reservation that changed concurrently", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-stable", {
...draft("share-stable"),
destination: { environmentId: "environment-2", projectId: "project-2" },
});
await expect(
inbox.releaseReservation("share-stable", {
environmentId: "environment-1",
projectId: "project-1",
}),
).rejects.toThrow("reservation changed");
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-2");
});
it("treats an already-removed share as an already-released reservation", async () => {
const { inbox, persisted } = createHarness();
persisted.set("share-other", draft("share-other"));
await expect(
inbox.releaseReservation("share-stable", {
environmentId: "environment-1",
projectId: "project-1",
}),
).resolves.toEqual([draft("share-other")]);
expect([...persisted.values()]).toEqual([draft("share-other")]);
});
});
@@ -1,193 +0,0 @@
import type { SharePayload } from "expo-sharing";
import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";
import {
hasIncomingShareContent,
type IncomingShareDestination,
type IncomingShareDraft,
} from "./incoming-share-model";
export interface IncomingShareInboxDependencies {
readonly loadDrafts: () => Promise<ReadonlyArray<IncomingShareDraft>>;
readonly writeDraft: (draft: IncomingShareDraft) => Promise<void>;
readonly removeDraft: (shareId: string) => Promise<void>;
readonly getPayloads: () => ReadonlyArray<SharePayload>;
readonly clearPayloads: () => void;
readonly buildDraft: (input: {
readonly payloads: ReadonlyArray<SharePayload>;
readonly id: string;
readonly createdAt: string;
}) => Promise<{
readonly draft: IncomingShareDraft;
readonly cleanup: () => Promise<void>;
}>;
readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;
readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
readonly now: () => string;
readonly onClearError?: (error: unknown) => void;
readonly onCleanupError?: (error: unknown) => void;
}
export function sortAndDedupeIncomingShares(
drafts: ReadonlyArray<IncomingShareDraft>,
): ReadonlyArray<IncomingShareDraft> {
const ids = new Set<string>();
return [...drafts]
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
.filter((draft) => {
if (ids.has(draft.id)) {
return false;
}
ids.add(draft.id);
return true;
});
}
/**
* Serializes every durable inbox mutation. This prevents a stale storage load
* or a foreground refresh from restoring an item after it has been consumed.
*/
export class IncomingShareInbox {
private readonly operations = new SerializedAsyncQueue();
constructor(private readonly dependencies: IncomingShareInboxDependencies) {}
private runExclusive<T>(operation: () => Promise<T>): Promise<T> {
return this.operations.run(operation);
}
private clearNativePayloads(): void {
try {
this.dependencies.clearPayloads();
} catch (error) {
this.dependencies.onClearError?.(error);
}
}
private async cleanup(operation: () => Promise<void>): Promise<void> {
try {
await operation();
} catch (error) {
this.dependencies.onCleanupError?.(error);
}
}
refresh(options: { readonly ingestNative: boolean }): Promise<ReadonlyArray<IncomingShareDraft>> {
return this.runExclusive(async () => {
const loaded = await this.dependencies.loadDrafts();
const persisted = sortAndDedupeIncomingShares(loaded);
if (!options.ingestNative) {
return persisted;
}
const payloads = this.dependencies.getPayloads();
if (payloads.length === 0) {
return persisted;
}
// A share extension payload remains available until the containing app
// acknowledges it. Use a content-derived id so a crash after the durable
// write but before acknowledgement reuses the same inbox item.
const shareId = await this.dependencies.idForPayloads(payloads);
if (loaded.some((draft) => draft.id === shareId)) {
if (this.dependencies.cleanupReplayedPayloads) {
await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads));
}
this.clearNativePayloads();
return persisted;
}
const built = await this.dependencies.buildDraft({
payloads,
id: shareId,
createdAt: this.dependencies.now(),
});
const { draft } = built;
if (!hasIncomingShareContent(draft)) {
// Unsupported native payloads cannot become actionable on retry and
// would otherwise reopen the project picker on every foreground.
await this.cleanup(built.cleanup);
this.clearNativePayloads();
throw new Error(
draft.warnings[0] ?? "The shared content is not supported by the composer.",
);
}
// The durable inbox write is the transaction boundary. Never clear the
// native handoff first: a process termination must leave one recoverable
// copy on one side of the boundary.
await this.dependencies.writeDraft(draft);
await this.cleanup(built.cleanup);
this.clearNativePayloads();
return sortAndDedupeIncomingShares([draft, ...persisted]);
});
}
consume(shareId: string): Promise<ReadonlyArray<IncomingShareDraft>> {
return this.runExclusive(async () => {
// The stable payload-derived id already coalesces retries of the same
// native handoff. Payload equality cannot identify duplicate handoffs:
// users may intentionally share identical content more than once.
await this.dependencies.removeDraft(shareId);
return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts());
});
}
reserve(
shareId: string,
destination: IncomingShareDestination,
): Promise<ReadonlyArray<IncomingShareDraft>> {
return this.runExclusive(async () => {
const persisted = await this.dependencies.loadDrafts();
const target = persisted.find((draft) => draft.id === shareId);
if (!target) {
throw new Error("The shared content is no longer available.");
}
if (target.destination) {
if (
target.destination.environmentId !== destination.environmentId ||
target.destination.projectId !== destination.projectId
) {
throw new Error("The shared content is already reserved for another project draft.");
}
return sortAndDedupeIncomingShares(persisted);
}
const reserved = { ...target, destination };
await this.dependencies.writeDraft(reserved);
return sortAndDedupeIncomingShares(
persisted.map((draft) => (draft.id === shareId ? reserved : draft)),
);
});
}
releaseReservation(
shareId: string,
expectedDestination: IncomingShareDestination,
): Promise<ReadonlyArray<IncomingShareDraft>> {
return this.runExclusive(async () => {
const persisted = await this.dependencies.loadDrafts();
const target = persisted.find((draft) => draft.id === shareId);
if (!target) {
// Conditional release is idempotent: if another operation already
// consumed the share, no reservation remains to clean up.
return sortAndDedupeIncomingShares(persisted);
}
if (!target.destination) {
return sortAndDedupeIncomingShares(persisted);
}
if (
target.destination.environmentId !== expectedDestination.environmentId ||
target.destination.projectId !== expectedDestination.projectId
) {
throw new Error("The shared content reservation changed before it could be released.");
}
const { destination: _destination, ...unreserved } = target;
await this.dependencies.writeDraft(unreserved);
return sortAndDedupeIncomingShares(
persisted.map((draft) => (draft.id === shareId ? unreserved : draft)),
);
});
}
}
@@ -1,196 +0,0 @@
import { describe, expect, it, vi } from "@effect/vitest";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model";
describe("incoming native shares", () => {
it("converts shared text, URLs, and images into a durable composer draft", async () => {
const image: SharePayload = {
shareType: "image",
value: "file:///shared/Screenshot.png",
mimeType: "image/png",
};
const payloads: SharePayload[] = [
{ shareType: "text", value: "Please explain this error" },
{ shareType: "url", value: "https://example.com/issue/1" },
{ shareType: "text", value: "Please explain this error" },
image,
];
const resolvedImage: ResolvedSharePayload = {
...image,
contentUri: image.value,
contentType: "image",
contentMimeType: "image/png",
contentSize: 3,
originalName: "Screenshot.png",
};
const removeOwnedFile = vi.fn(() => Promise.resolve());
const result = await buildIncomingShareDraft({
id: "share-1",
createdAt: "2026-07-15T10:00:00.000Z",
payloads,
resolvedPayloads: [resolvedImage],
fileReader: {
readBase64: async () => "YWJj",
removeOwnedFile,
},
});
expect(result).toEqual({
schemaVersion: 1,
id: "share-1",
createdAt: "2026-07-15T10:00:00.000Z",
text: "Please explain this error\n\nhttps://example.com/issue/1",
attachments: [
{
id: "share-1:image:3",
type: "image",
name: "Screenshot.png",
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
},
],
warnings: [],
});
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
expect(hasIncomingShareContent(result)).toBe(true);
});
it("skips oversized images and releases the temporary native file", async () => {
const image: SharePayload = {
shareType: "image",
value: "file:///shared/huge.png",
mimeType: "image/png",
};
const readBase64 = vi.fn(async () => "unused");
const removeOwnedFile = vi.fn(() => Promise.resolve());
const result = await buildIncomingShareDraft({
id: "share-2",
createdAt: "2026-07-15T10:00:00.000Z",
payloads: [image],
resolvedPayloads: [
{
...image,
contentUri: image.value,
contentType: "image",
contentMimeType: "image/png",
contentSize: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
originalName: "huge.png",
},
],
fileReader: { readBase64, removeOwnedFile },
});
expect(result.attachments).toEqual([]);
expect(result.warnings).toEqual(["'huge.png' exceeds the 10 MB attachment limit."]);
expect(readBase64).not.toHaveBeenCalled();
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
expect(hasIncomingShareContent(result)).toBe(false);
});
it("releases every temporary file when a share exceeds the attachment limit", async () => {
const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
shareType: "image" as const,
value: `file:///shared/${index}.png`,
mimeType: "image/png",
}));
const removeOwnedFile = vi.fn(() => Promise.resolve());
const readBase64 = vi.fn(async () => "YWJj");
const result = await buildIncomingShareDraft({
id: "share-3",
createdAt: "2026-07-15T10:00:00.000Z",
payloads,
resolvedPayloads: [],
fileReader: { readBase64, removeOwnedFile },
});
expect(result.attachments).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
expect(result.warnings).toEqual([
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
]);
expect(readBase64).toHaveBeenCalledTimes(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
expect(removeOwnedFile).toHaveBeenCalledTimes(payloads.length);
});
it("maps duplicate image payloads to distinct resolved files", async () => {
const duplicate: SharePayload = {
shareType: "image",
value: "content://shared/screenshot",
mimeType: "image/png",
};
const resolvedPayloads: ResolvedSharePayload[] = [
{
...duplicate,
contentUri: "file:///cache/first.png",
contentType: "image",
contentMimeType: "image/png",
contentSize: 3,
originalName: "first.png",
},
{
...duplicate,
contentUri: "file:///cache/second.png",
contentType: "image",
contentMimeType: "image/png",
contentSize: 3,
originalName: "second.png",
},
];
const readBase64 = vi.fn(async (uri: string) =>
uri.includes("first") ? "Zmlyc3Q=" : "c2Vjb25k",
);
const removeOwnedFile = vi.fn(async () => undefined);
const result = await buildIncomingShareDraft({
id: "share-duplicates",
createdAt: "2026-07-16T08:00:00.000Z",
payloads: [duplicate, duplicate],
resolvedPayloads,
fileReader: { readBase64, removeOwnedFile },
});
expect(readBase64.mock.calls.map(([uri]) => uri)).toEqual([
"file:///cache/first.png",
"file:///cache/second.png",
]);
expect(result.attachments.map((attachment) => attachment.name)).toEqual([
"first.png",
"second.png",
]);
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/first.png");
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/second.png");
});
it("keeps imported content when temporary-file cleanup fails", async () => {
const image: SharePayload = {
shareType: "image",
value: "file:///shared/screenshot.png",
mimeType: "image/png",
};
const result = await buildIncomingShareDraft({
id: "share-cleanup-failure",
createdAt: "2026-07-16T08:00:00.000Z",
payloads: [image],
resolvedPayloads: [],
fileReader: {
readBase64: async () => "YWJj",
removeOwnedFile: async () => {
throw new Error("file is busy");
},
},
});
expect(result.attachments).toHaveLength(1);
expect(result.warnings).toEqual([]);
});
});
@@ -1,217 +0,0 @@
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { estimateBase64ByteSize } from "../../lib/base64";
export interface IncomingShareDraft {
readonly schemaVersion: 1;
readonly id: string;
readonly createdAt: string;
readonly destination?: IncomingShareDestination;
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly warnings: ReadonlyArray<string>;
}
export interface IncomingShareDestination {
readonly environmentId: string;
readonly projectId: string;
}
const IncomingShareDestinationSchema = Schema.Struct({
environmentId: Schema.String,
projectId: Schema.String,
});
export const IncomingShareDraftSchema = Schema.Struct({
schemaVersion: Schema.Literal(1),
id: Schema.String,
createdAt: Schema.String,
destination: Schema.optional(IncomingShareDestinationSchema),
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
warnings: Schema.Array(Schema.String),
});
const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
return decodeIncomingShareDraftSync(value);
}
export interface IncomingShareFileReader {
readonly readBase64: (uri: string) => Promise<string>;
readonly removeOwnedFile: (uri: string) => Promise<void> | void;
}
function sharedText(payloads: ReadonlyArray<SharePayload>): string {
const seen = new Set<string>();
const values: string[] = [];
for (const payload of payloads) {
if (payload.shareType !== "text" && payload.shareType !== "url") {
continue;
}
const value = payload.value.trim();
if (!value || seen.has(value)) {
continue;
}
seen.add(value);
values.push(value);
}
return values.join("\n\n");
}
function resolvedImageFor(
payload: SharePayload,
index: number,
resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,
consumedIndexes: Set<number>,
): ResolvedSharePayload | undefined {
const sameIndex = resolvedPayloads[index];
if (
!consumedIndexes.has(index) &&
sameIndex?.shareType === payload.shareType &&
sameIndex.value === payload.value
) {
consumedIndexes.add(index);
return sameIndex;
}
const matchingIndex = resolvedPayloads.findIndex(
(candidate, candidateIndex) =>
!consumedIndexes.has(candidateIndex) &&
candidate.shareType === payload.shareType &&
candidate.value === payload.value,
);
if (matchingIndex < 0) {
return undefined;
}
consumedIndexes.add(matchingIndex);
return resolvedPayloads[matchingIndex];
}
async function releaseOwnedFiles(
fileReader: IncomingShareFileReader,
uris: ReadonlyArray<string | undefined>,
): Promise<void> {
for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {
try {
await fileReader.removeOwnedFile(uri);
} catch {
// Temporary-file cleanup is best-effort and must never discard content
// that was successfully converted into a durable composer attachment.
}
}
}
function fallbackName(uri: string, index: number, mimeType: string): string {
try {
const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
if (pathName) {
return decodeURIComponent(pathName);
}
} catch {
// Fall through to a deterministic attachment name.
}
const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png";
return `shared-image-${index + 1}.${extension}`;
}
export async function buildIncomingShareDraft(input: {
readonly payloads: ReadonlyArray<SharePayload>;
readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
readonly fileReader: IncomingShareFileReader;
readonly id: string;
readonly createdAt: string;
}): Promise<IncomingShareDraft> {
const attachments: DraftComposerImageAttachment[] = [];
const warnings: string[] = [];
const consumedResolvedPayloadIndexes = new Set<number>();
let warnedAttachmentLimit = false;
for (const [index, payload] of input.payloads.entries()) {
if (payload.shareType !== "image") {
continue;
}
const resolved = resolvedImageFor(
payload,
index,
input.resolvedPayloads,
consumedResolvedPayloadIndexes,
);
const uri = resolved?.contentUri ?? payload.value;
if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
if (!warnedAttachmentLimit) {
warnings.push(
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
);
warnedAttachmentLimit = true;
}
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
continue;
}
const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();
if (!uri || !mimeType.startsWith("image/")) {
warnings.push("One shared item was not a supported image.");
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
continue;
}
if (
resolved?.contentSize !== null &&
resolved?.contentSize !== undefined &&
resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
) {
warnings.push(
`'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
);
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
continue;
}
try {
const base64 = await input.fileReader.readBase64(uri);
const sizeBytes = resolved?.contentSize ?? estimateBase64ByteSize(base64);
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
warnings.push(
`'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
);
continue;
}
const dataUrl = `data:${mimeType};base64,${base64}`;
attachments.push({
id: `${input.id}:image:${index}`,
type: "image",
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
mimeType,
sizeBytes,
dataUrl,
// The share provider's file is temporary. A data-backed preview keeps
// the composer valid after its source file and App Group entry are gone.
previewUri: dataUrl,
});
} catch {
warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`);
} finally {
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
}
}
return {
schemaVersion: 1,
id: input.id,
createdAt: input.createdAt,
text: sharedText(input.payloads),
attachments,
warnings,
};
}
export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {
return draft.text.trim().length > 0 || draft.attachments.length > 0;
}
@@ -1,92 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import {
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
transitionIncomingSharePresentation,
} from "./incoming-share-presentation";
describe("incoming share presentation", () => {
it("does not reopen a dismissed share when refresh returns a new object for the same id", () => {
const presented = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
isShareSheetPresented: false,
pendingShareId: "share-1",
});
expect(presented.shareIdToPresent).toBe("share-1");
const whilePresented = transitionIncomingSharePresentation(presented.state, {
isShareSheetPresented: true,
pendingShareId: "share-1",
});
expect(whilePresented).toEqual({ state: presented.state, shareIdToPresent: null });
const dismissed = transitionIncomingSharePresentation(whilePresented.state, {
isShareSheetPresented: false,
pendingShareId: "share-1",
});
expect(dismissed.state.dismissedShareId).toBe("share-1");
expect(
transitionIncomingSharePresentation(dismissed.state, {
isShareSheetPresented: false,
pendingShareId: "share-1",
}),
).toEqual({ state: dismissed.state, shareIdToPresent: null });
});
it("presents the next queued share immediately after the previous sheet closes", () => {
const first = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
isShareSheetPresented: false,
pendingShareId: "share-1",
});
const next = transitionIncomingSharePresentation(first.state, {
isShareSheetPresented: false,
pendingShareId: "share-2",
});
expect(next.shareIdToPresent).toBe("share-2");
expect(next.state).toEqual({ presentedShareId: "share-2", dismissedShareId: null });
});
it("forgets dismissal after consumption so a later handoff may reuse the id", () => {
const dismissed = {
presentedShareId: null,
dismissedShareId: "share-1",
};
const consumed = transitionIncomingSharePresentation(dismissed, {
isShareSheetPresented: false,
pendingShareId: null,
});
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
expect(
transitionIncomingSharePresentation(consumed.state, {
isShareSheetPresented: false,
pendingShareId: "share-1",
}).shareIdToPresent,
).toBe("share-1");
});
it("forgets a consumed presentation while its sheet is still mounted", () => {
const presented = {
presentedShareId: "share-1",
dismissedShareId: null,
};
const consumed = transitionIncomingSharePresentation(presented, {
isShareSheetPresented: true,
pendingShareId: null,
});
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
const replacementWhileOpen = transitionIncomingSharePresentation(consumed.state, {
isShareSheetPresented: true,
pendingShareId: "share-1",
});
expect(replacementWhileOpen.shareIdToPresent).toBeNull();
expect(
transitionIncomingSharePresentation(replacementWhileOpen.state, {
isShareSheetPresented: false,
pendingShareId: "share-1",
}).shareIdToPresent,
).toBe("share-1");
});
});
@@ -1,71 +0,0 @@
export interface IncomingSharePresentationState {
readonly presentedShareId: string | null;
readonly dismissedShareId: string | null;
}
export interface IncomingSharePresentationTransition {
readonly state: IncomingSharePresentationState;
readonly shareIdToPresent: string | null;
}
export const EMPTY_INCOMING_SHARE_PRESENTATION_STATE: IncomingSharePresentationState = {
presentedShareId: null,
dismissedShareId: null,
};
/**
* Tracks presentation by durable share id rather than object identity. A user
* dismissal suppresses only that inbox item until it is consumed or replaced.
*/
export function transitionIncomingSharePresentation(
state: IncomingSharePresentationState,
input: {
readonly isShareSheetPresented: boolean;
readonly pendingShareId: string | null;
},
): IncomingSharePresentationTransition {
if (input.isShareSheetPresented) {
if (state.presentedShareId !== null && input.pendingShareId !== state.presentedShareId) {
// Consumption may happen while the sheet remains mounted. Forget the
// old presentation immediately so a later handoff may reuse its id.
return {
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
shareIdToPresent: null,
};
}
return { state, shareIdToPresent: null };
}
let nextState = state;
if (state.presentedShareId !== null) {
if (input.pendingShareId === state.presentedShareId) {
return {
state: {
presentedShareId: null,
dismissedShareId: state.presentedShareId,
},
shareIdToPresent: null,
};
}
nextState = { ...state, presentedShareId: null };
}
if (input.pendingShareId === null) {
return {
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
shareIdToPresent: null,
};
}
if (nextState.dismissedShareId === input.pendingShareId) {
return { state: nextState, shareIdToPresent: null };
}
return {
state: {
presentedShareId: input.pendingShareId,
dismissedShareId: null,
},
shareIdToPresent: input.pendingShareId,
};
}
@@ -1,80 +0,0 @@
import * as Schema from "effect/Schema";
import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
const INCOMING_SHARE_DIRECTORY = "incoming-shares";
export class IncomingShareStorageError extends Schema.TaggedErrorClass<IncomingShareStorageError>()(
"IncomingShareStorageError",
{
operation: Schema.Literals(["load", "write", "remove"]),
shareId: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;
}
}
function fileName(shareId: string): string {
return `${encodeURIComponent(shareId)}.json`;
}
async function getDirectory() {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return directory;
}
async function getFile(shareId: string) {
const { File } = await import("expo-file-system");
return new File(await getDirectory(), fileName(shareId));
}
export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {
try {
const { File } = await import("expo-file-system");
const drafts: IncomingShareDraft[] = [];
for (const entry of (await getDirectory()).list()) {
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
continue;
}
try {
drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
} catch (cause) {
console.warn(
"[incoming-share] ignored invalid persisted share",
new IncomingShareStorageError({ operation: "load", shareId: null, cause }),
);
}
}
return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
} catch (cause) {
throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
}
}
export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
try {
const file = await getFile(draft.id);
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(draft));
} catch (cause) {
throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
}
}
export async function removeIncomingShareDraft(shareId: string): Promise<void> {
try {
const file = await getFile(shareId);
if (file.exists) {
file.delete();
}
} catch (cause) {
throw new IncomingShareStorageError({ operation: "remove", shareId, cause });
}
}
@@ -1,224 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { Keyboard, View } from "react-native";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useConnectionController } from "../connection/useConnectionController";
import { useProjects, useThreadShells } from "../../state/entities";
import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
import { useWorkspaceState } from "../../state/workspace";
import {
getNativeShowcasePairingUrls,
getNativeShowcaseScene,
markNativeShowcaseReady,
type ShowcaseScene,
} from "./nativeShowcaseScene";
import {
buildShowcasePendingTasks,
SHOWCASE_PENDING_TASK_DEFINITIONS,
} from "./showcasePendingTasks";
import { retryShowcaseOperation } from "./showcaseRetry";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const SHOWCASE_THREAD_ID = "remote-command-center";
function sceneFromPathname(pathname: string): ShowcaseScene | null {
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
return "environments";
}
if (routePath.endsWith("/terminal")) return "terminal";
if (routePath.endsWith("/review")) return "review";
if (routePath.startsWith("/threads/")) return "thread";
if (routePath === "/") return "threads";
return null;
}
export function ShowcaseCaptureCoordinator(props: { readonly pathname: string }) {
const navigation = useNavigation();
const { connectPairingUrl } = useConnectionController();
const workspace = useWorkspaceState();
const projects = useProjects();
const threads = useThreadShells();
const attemptedPairingRef = useRef(new Set<string>());
const seededPendingTaskIdsRef = useRef(new Set<string>());
const [pairingUrls, setPairingUrls] = useState<ReadonlyArray<string>>([]);
const [pendingTasksReady, setPendingTasksReady] = useState(false);
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
useEffect(() => {
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
const readPairingUrls = () => {
const values = getNativeShowcasePairingUrls();
if (values.length > 0) setPairingUrls(values);
};
readPairingUrls();
const interval = setInterval(readPairingUrls, 250);
return () => clearInterval(interval);
}, [pairingUrls.length]);
useEffect(() => {
if (!SHOWCASE_ENABLED) return;
const readRequestedScene = () => {
const value = getNativeShowcaseScene();
if (value) setRequestedScene(value);
};
readRequestedScene();
const interval = setInterval(readRequestedScene, 250);
return () => clearInterval(interval);
}, []);
useEffect(() => {
if (!SHOWCASE_ENABLED || pairingUrls.length === 0) return;
let cancelled = false;
void (async () => {
await Promise.all(
pairingUrls.map(async (pairingUrl) => {
if (cancelled || attemptedPairingRef.current.has(pairingUrl)) return;
const paired = await retryShowcaseOperation(
async () => AsyncResult.isSuccess(await connectPairingUrl(pairingUrl)),
{ isCancelled: () => cancelled },
);
if (paired) attemptedPairingRef.current.add(pairingUrl);
}),
);
})();
return () => {
cancelled = true;
};
}, [connectPairingUrl, pairingUrls]);
const scene = sceneFromPathname(props.pathname);
const hasServerFixture =
workspace.state.hasReadyEnvironment &&
workspace.environments.length >= 3 &&
projects.length >= 3 &&
threads.some((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
const hasFixture = hasServerFixture && pendingTasksReady;
const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
useEffect(() => {
if (!SHOWCASE_ENABLED || !hasServerFixture || pendingTasksReady) return;
const pendingTasks = buildShowcasePendingTasks(projects, Date.now());
if (pendingTasks.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return;
let cancelled = false;
for (const task of pendingTasks) holdEditingQueuedMessage(task.messageId);
void (async () => {
const results = await Promise.all(
pendingTasks.map(async (task) => {
const messageId = String(task.messageId);
if (seededPendingTaskIdsRef.current.has(messageId)) return true;
const seeded = await retryShowcaseOperation(
async () => {
await enqueueThreadOutboxMessage(task);
return true;
},
{ isCancelled: () => cancelled },
);
if (seeded) seededPendingTaskIdsRef.current.add(messageId);
return seeded;
}),
);
if (!cancelled && results.every(Boolean)) setPendingTasksReady(true);
})();
return () => {
cancelled = true;
};
}, [hasServerFixture, pendingTasksReady, projects]);
useEffect(() => {
if (!SHOWCASE_ENABLED || requestedScene === null || !hasFixture || !showcaseThread) return;
if (scene === requestedScene) return;
const params = {
environmentId: String(showcaseThread.environmentId),
threadId: SHOWCASE_THREAD_ID,
};
if (requestedScene === "threads") {
navigation.dispatch(StackActions.popToTop());
return;
}
const routes: Array<{
name: string;
params?: Record<string, unknown>;
state?: { index: number; routes: Array<{ name: string }> };
}> = [{ name: "Home" }];
if (requestedScene === "environments") {
routes.push({
name: "SettingsSheet",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
});
} else {
routes.push({ name: "Thread", params });
if (requestedScene === "terminal") {
routes.push({
name: "ThreadTerminal",
params: { ...params, terminalId: "term-1" },
});
} else if (requestedScene === "review") {
routes.push({ name: "ThreadReview", params });
}
}
navigation.dispatch(
CommonActions.reset({
index: routes.length - 1,
routes,
}),
);
}, [hasFixture, navigation, requestedScene, scene, showcaseThread]);
useEffect(() => {
if (
!SHOWCASE_ENABLED ||
scene === null ||
requestedScene === null ||
scene !== requestedScene ||
!hasFixture
) {
setReadyScene(null);
return;
}
// Review owns its readiness marker because route activation happens before
// the VCS request is parsed and the native diff surface is mounted.
if (scene === "review") {
setReadyScene(null);
return;
}
if (scene === "terminal") Keyboard.dismiss();
let renderFrame: number | null = null;
let readyFrame: number | null = null;
const settleTimer = setTimeout(() => {
renderFrame = requestAnimationFrame(() => {
readyFrame = requestAnimationFrame(() => {
markNativeShowcaseReady(scene);
setReadyScene(scene);
});
});
}, 500);
return () => {
clearTimeout(settleTimer);
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
};
}, [hasFixture, requestedScene, scene]);
if (!SHOWCASE_ENABLED || readyScene === null) return null;
return (
<View
pointerEvents="none"
testID={`showcase-ready-${readyScene}`}
style={{ position: "absolute", width: 1, height: 1, opacity: 0.01 }}
/>
);
}
@@ -1,68 +0,0 @@
import { requireOptionalNativeModule } from "expo";
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
interface NativeShowcaseControls {
readonly getShowcasePairingUrl?: () => string | null;
readonly getShowcaseScene?: () => string | null;
readonly prepareShowcaseCapture?: () => void;
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
}
function nativeShowcaseControls(): NativeShowcaseControls | null {
return requireOptionalNativeModule<NativeShowcaseControls>("T3NativeControls");
}
export function getNativeShowcasePairingUrls(): ReadonlyArray<string> {
try {
let raw = nativeShowcaseControls()?.getShowcasePairingUrl?.()?.trim();
if (!raw) return [];
if (raw.startsWith("json-uri:")) {
try {
raw = decodeURIComponent(raw.slice("json-uri:".length));
} catch {
return [];
}
}
try {
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) {
return parsed.filter(
(candidate): candidate is string =>
typeof candidate === "string" && candidate.trim().length > 0,
);
}
} catch {
// Older runners pass a single URL rather than a JSON array.
}
return [raw];
} catch {
return [];
}
}
export function getNativeShowcaseScene(): ShowcaseScene | null {
try {
const scene = nativeShowcaseControls()?.getShowcaseScene?.()?.trim();
return SHOWCASE_SCENES.find((candidate) => candidate === scene) ?? null;
} catch {
return null;
}
}
export function prepareNativeShowcaseCapture(): void {
try {
nativeShowcaseControls()?.prepareShowcaseCapture?.();
} catch {
// The harness still works when a development build predates this helper.
}
}
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
try {
nativeShowcaseControls()?.markShowcaseReady?.(scene);
} catch {
// The readiness marker is capture-runner metadata, never app functionality.
}
}
@@ -1,70 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import {
applyShowcaseLocalEnvironmentDisplayUrls,
resolveShowcaseEnvironmentUpdateDisplayUrl,
} from "./showcaseEnvironmentRows";
function environment(
environmentId: string,
environmentLabel: string,
displayUrl = "http://127.0.0.1:3773/",
): ConnectedEnvironmentSummary {
return {
environmentId: EnvironmentId.make(environmentId),
environmentLabel,
displayUrl,
isRelayManaged: false,
connectionState: "connected",
connectionError: null,
connectionErrorTraceId: null,
};
}
it("presents showcase transports as remote endpoints", () => {
const environments = applyShowcaseLocalEnvironmentDisplayUrls([
environment("runtime-id-1", "Moonbase Terminal"),
environment("runtime-id-2", "Suspense Station"),
environment("runtime-id-3", "Kernel Cabin"),
]);
assert.deepStrictEqual(
environments.map(({ displayUrl }) => displayUrl),
[
"https://moonbase.tail9f3a.ts.net/",
"https://suspense-vps.hel1.t3.sh/",
"http://100.82.16.5:3773/",
],
);
});
it("leaves environments outside the showcase fixture unchanged", () => {
const original = environment(
"runtime-id-4",
"My Workstation",
"https://workstation.example.test/",
);
assert.deepStrictEqual(applyShowcaseLocalEnvironmentDisplayUrls([original]), [original]);
});
it("does not persist a cosmetic showcase URL when only the label is saved", () => {
assert.equal(
resolveShowcaseEnvironmentUpdateDisplayUrl({
actualDisplayUrl: "http://127.0.0.1:3773/",
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
submittedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
}),
"http://127.0.0.1:3773/",
);
assert.equal(
resolveShowcaseEnvironmentUpdateDisplayUrl({
actualDisplayUrl: "http://127.0.0.1:3773/",
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
submittedDisplayUrl: "https://new-host.example.com/",
}),
"https://new-host.example.com/",
);
});
@@ -1,70 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import type { RelayEnvironmentView } from "../connection/useConnectionController";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
const SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS: Readonly<Record<string, string>> = {
"Moonbase Terminal": "https://moonbase.tail9f3a.ts.net/",
"Suspense Station": "https://suspense-vps.hel1.t3.sh/",
"Kernel Cabin": "http://100.82.16.5:3773/",
};
export function applyShowcaseLocalEnvironmentDisplayUrls(
environments: ReadonlyArray<ConnectedEnvironmentSummary>,
): ReadonlyArray<ConnectedEnvironmentSummary> {
return environments.map((environment) => ({
...environment,
displayUrl:
SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS[environment.environmentLabel] ??
environment.displayUrl,
}));
}
export function resolveShowcaseEnvironmentUpdateDisplayUrl(input: {
readonly actualDisplayUrl: string;
readonly presentedDisplayUrl: string;
readonly submittedDisplayUrl: string;
}): string {
return input.submittedDisplayUrl === input.presentedDisplayUrl
? input.actualDisplayUrl
: input.submittedDisplayUrl;
}
const pocketPiId = EnvironmentId.make("showcase-pocket-pi");
const pocketPiEndpoint = {
httpBaseUrl: "https://pocket-pi.t3.sh",
wsBaseUrl: "wss://pocket-pi.t3.sh",
providerKind: "t3_relay" as const,
};
export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray<ConnectedEnvironmentSummary> = [
{
environmentId: EnvironmentId.make("showcase-aurora-gpu"),
environmentLabel: "Aurora GPU Pod",
displayUrl: "https://aurora-gpu.t3.sh",
isRelayManaged: true,
connectionState: "connected",
connectionError: null,
connectionErrorTraceId: null,
},
];
export const SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS: ReadonlyArray<RelayEnvironmentView> = [
{
environment: {
environmentId: pocketPiId,
label: "Pocket Pi",
endpoint: pocketPiEndpoint,
linkedAt: "2026-07-16T08:00:00.000Z",
},
availability: "online",
status: {
environmentId: pocketPiId,
endpoint: pocketPiEndpoint,
status: "online",
checkedAt: "2026-07-16T08:41:00.000Z",
},
error: null,
traceId: null,
},
];
@@ -1,72 +0,0 @@
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import {
buildShowcasePendingTasks,
SHOWCASE_PENDING_TASK_DEFINITIONS,
} from "./showcasePendingTasks";
const projects: ReadonlyArray<EnvironmentProject> = [
{
environmentId: EnvironmentId.make("moonbase-terminal"),
id: ProjectId.make("t3code"),
title: "T3 Code",
workspaceRoot: "/workspace/t3code",
repositoryIdentity: null,
defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
scripts: [],
createdAt: "2026-07-16T08:00:00.000Z",
updatedAt: "2026-07-16T08:00:00.000Z",
},
{
environmentId: EnvironmentId.make("suspense-station"),
id: ProjectId.make("react"),
title: "React",
workspaceRoot: "/workspace/react",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-16T08:00:00.000Z",
updatedAt: "2026-07-16T08:00:00.000Z",
},
];
it("builds sendable-looking pending tasks against real showcase projects", () => {
const tasks = buildShowcasePendingTasks(projects, Date.parse("2026-07-16T09:00:00.000Z"));
assert.equal(tasks.length, SHOWCASE_PENDING_TASK_DEFINITIONS.length);
assert.deepStrictEqual(
tasks.map((task) => ({
environmentId: String(task.environmentId),
projectId: task.creation ? String(task.creation.projectId) : undefined,
title: task.creation?.projectTitle,
branch: task.creation?.branch,
createdAt: task.createdAt,
})),
[
{
environmentId: "moonbase-terminal",
projectId: "t3code",
title: "T3 Code",
branch: "feat/offline-launchpad",
createdAt: "2026-07-16T08:52:00.000Z",
},
{
environmentId: "suspense-station",
projectId: "react",
title: "React",
branch: "perf/tunnel-handoff",
createdAt: "2026-07-16T08:33:00.000Z",
},
],
);
assert.equal(
tasks.every((task) => task.modelSelection !== undefined),
true,
);
});
it("waits until every referenced project has hydrated", () => {
assert.equal(buildShowcasePendingTasks(projects.slice(0, 1), Date.now()).length, 1);
});
@@ -1,66 +0,0 @@
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
export const SHOWCASE_PENDING_TASK_DEFINITIONS = [
{
projectId: "t3code",
id: "offline-launch-checklist",
text: "Ship the offline launch checklist before touchdown ✈️",
branch: "feat/offline-launchpad",
minutesAgo: 8,
},
{
projectId: "react",
id: "train-tunnel-suspense",
text: "Polish the Suspense handoff for the train tunnel 🚇",
branch: "perf/tunnel-handoff",
minutesAgo: 27,
},
] as const;
const FALLBACK_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
} as const;
export function buildShowcasePendingTasks(
projects: ReadonlyArray<EnvironmentProject>,
now: number,
): ReadonlyArray<QueuedThreadMessage> {
return SHOWCASE_PENDING_TASK_DEFINITIONS.flatMap((definition) => {
const project = projects.find((candidate) => String(candidate.id) === definition.projectId);
if (!project) return [];
return [
{
environmentId: project.environmentId,
threadId: ThreadId.make(`showcase-pending-${definition.id}`),
messageId: MessageId.make(`showcase-pending-message-${definition.id}`),
commandId: CommandId.make(`showcase-pending-command-${definition.id}`),
text: definition.text,
attachments: [],
modelSelection: project.defaultModelSelection ?? FALLBACK_MODEL_SELECTION,
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
creation: {
projectId: project.id,
projectTitle: project.title,
projectCwd: project.workspaceRoot,
workspaceMode: "local" as const,
branch: definition.branch,
worktreePath: project.workspaceRoot,
},
createdAt: new Date(now - definition.minutesAgo * 60_000).toISOString(),
},
];
});
}
@@ -1,44 +0,0 @@
import { assert, it } from "@effect/vitest";
import { retryShowcaseOperation } from "./showcaseRetry";
it("retries a failed showcase operation until it succeeds", async () => {
let attempts = 0;
const succeeded = await retryShowcaseOperation(
async () => {
attempts += 1;
return attempts === 3;
},
{ isCancelled: () => false, retryDelayMs: 0 },
);
assert.equal(succeeded, true);
assert.equal(attempts, 3);
});
it("recovers when a showcase operation attempt hangs", async () => {
let attempts = 0;
const succeeded = await retryShowcaseOperation(
() => {
attempts += 1;
return attempts === 1 ? new Promise<boolean>(() => undefined) : Promise.resolve(true);
},
{ isCancelled: () => false, attemptTimeoutMs: 1, retryDelayMs: 0 },
);
assert.equal(succeeded, true);
assert.equal(attempts, 2);
});
it("stops retrying when the owning showcase effect is cancelled", async () => {
let cancelled = false;
const succeeded = await retryShowcaseOperation(
async () => {
cancelled = true;
return false;
},
{ isCancelled: () => cancelled, retryDelayMs: 0 },
);
assert.equal(succeeded, false);
});
@@ -1,46 +0,0 @@
export interface ShowcaseRetryOptions {
readonly isCancelled: () => boolean;
readonly attemptTimeoutMs?: number;
readonly retryDelayMs?: number;
}
const DEFAULT_ATTEMPT_TIMEOUT_MS = 10_000;
const DEFAULT_RETRY_DELAY_MS = 500;
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function runAttemptWithTimeout(
operation: () => Promise<boolean>,
timeoutMs: number,
): Promise<boolean> {
let timeout: ReturnType<typeof setTimeout> | null = null;
try {
return await Promise.race([
operation(),
new Promise<boolean>((resolve) => {
timeout = setTimeout(() => resolve(false), timeoutMs);
}),
]);
} catch {
return false;
} finally {
if (timeout !== null) clearTimeout(timeout);
}
}
/** Retry transient showcase setup work until it succeeds or the owning effect unmounts. */
export async function retryShowcaseOperation(
operation: () => Promise<boolean>,
options: ShowcaseRetryOptions,
): Promise<boolean> {
const attemptTimeoutMs = options.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
while (!options.isCancelled()) {
if (await runAttemptWithTimeout(operation, attemptTimeoutMs)) return true;
if (!options.isCancelled()) await delay(retryDelayMs);
}
return false;
}
@@ -37,7 +37,6 @@ interface TerminalSurfaceProps extends ViewProps {
readonly buffer: string;
readonly fontSize?: number;
readonly isRunning: boolean;
readonly autoFocus?: boolean;
readonly keyboardFocusRequest?: number;
readonly theme?: TerminalTheme;
readonly onInput: (data: string) => void;
@@ -146,8 +145,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
onSubmitEditing={(event) => {
const text = event.nativeEvent.text;
if (text.length > 0) {
// Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
props.onInput(`${text}\r`);
props.onInput(`${text}\n`);
}
}}
/>
@@ -216,7 +214,6 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
<View style={props.style}>
<NativeTerminalSurfaceView
appearanceScheme={appearanceScheme}
autoFocus={props.autoFocus ?? true}
backgroundColor={theme.background}
focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
foregroundColor={theme.foreground}
@@ -70,7 +70,6 @@ import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiSt
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
const TERMINAL_ACCESSORY_HEIGHT = 52;
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
type PendingModifier = "ctrl" | "meta";
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
@@ -1219,7 +1218,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
<>
<View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
<TerminalSurface
autoFocus={!SHOWCASE_ENABLED}
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
@@ -23,7 +23,6 @@ interface TerminalResizeEvent {
export interface NativeTerminalSurfaceProps extends ViewProps {
readonly appearanceScheme?: "light" | "dark";
readonly autoFocus?: boolean;
readonly focusRequest?: number;
readonly themeConfig?: string;
readonly backgroundColor?: string;
@@ -9,7 +9,6 @@ type NewTaskDraftRouteParams = {
readonly projectId?: string | string[];
readonly title?: string | string[];
readonly pendingTaskId?: string | string[];
readonly incomingShareId?: string | string[];
};
export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
@@ -37,9 +36,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
/>
<NewTaskDraftScreen
initialProjectRef={initialProjectRef}
incomingShareId={
Array.isArray(params.incomingShareId) ? params.incomingShareId[0] : params.incomingShareId
}
pendingTaskId={
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
}
@@ -1,5 +1,5 @@
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
@@ -35,13 +35,7 @@ import {
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
getComposerDraftSnapshot,
mergeComposerDraftContent,
restoreComposerDraftSnapshot,
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
@@ -49,7 +43,6 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
@@ -70,20 +63,11 @@ export function NewTaskDraftScreen(props: {
};
/** Queued outbox message id when editing an existing pending task. */
readonly pendingTaskId?: string;
/** Durable native share inbox item to merge into this project draft. */
readonly incomingShareId?: string;
}) {
const projects = useProjects();
const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow();
const navigation = useNavigation();
const {
consumeShare,
getShare,
isLoading: isIncomingShareInboxLoading,
releaseShareReservation,
reserveShare,
} = useIncomingShare();
const insets = useSafeAreaInsets();
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
@@ -98,94 +82,10 @@ export function NewTaskDraftScreen(props: {
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
const [shareImportAttempt, setShareImportAttempt] = useState(0);
const startedShareImportKeyRef = useRef<string | null>(null);
const cancellingShareImportKeyRef = useRef<string | null>(null);
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
const activeShareImportTokenRef = useRef<symbol | null>(null);
const shareImportMountedRef = useRef(true);
const latestDraftKeyRef = useRef(flow.draftKey);
const latestIncomingShareIdRef = useRef(props.incomingShareId);
latestDraftKeyRef.current = flow.draftKey;
latestIncomingShareIdRef.current = props.incomingShareId;
const isImportingShare = importingShareKey !== null;
const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
const requestedInitialProjectAvailable = Boolean(
props.initialProjectRef?.environmentId &&
props.initialProjectRef.projectId &&
projects.some(
(project) =>
project.environmentId === props.initialProjectRef?.environmentId &&
project.id === props.initialProjectRef?.projectId,
),
);
const isProjectPickerReturnActive =
isReturningToProjectPicker && !requestedInitialProjectAvailable;
const isIncomingShareTransferPending = Boolean(
incomingShare && cancelledIncomingShareId !== props.incomingShareId,
);
usePreventRemove(
(isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
() => undefined,
);
const hasImportedIncomingShare = Boolean(
props.incomingShareId &&
flow.draftKey &&
getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),
);
const isIncomingShareUnavailable = Boolean(
props.incomingShareId &&
!isIncomingShareInboxLoading &&
!incomingShare &&
!hasImportedIncomingShare,
);
const isIncomingShareReady =
!props.incomingShareId ||
(hasImportedIncomingShare && !incomingShare) ||
isIncomingShareUnavailable;
const appliedInitialProjectKeyRef = useRef<string | null>(null);
useEffect(() => {
if (cancelledIncomingShareId === props.incomingShareId) {
navigation.goBack();
}
}, [cancelledIncomingShareId, navigation, props.incomingShareId]);
useEffect(() => {
if (!isReturningToProjectPicker) {
return;
}
if (requestedInitialProjectAvailable) {
setIsReturningToProjectPicker(false);
return;
}
// Let usePreventRemove commit its disabled state before replacing this
// route, otherwise the transfer guard can swallow the fallback action.
const frame = requestAnimationFrame(() => {
navigation.dispatch(
StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
);
});
return () => cancelAnimationFrame(frame);
}, [
isReturningToProjectPicker,
navigation,
props.incomingShareId,
requestedInitialProjectAvailable,
]);
useEffect(() => {
if (!shareImportMountedRef.current) {
startedShareImportKeyRef.current = null;
}
shareImportMountedRef.current = true;
return () => {
appliedInitialProjectKeyRef.current = null;
shareImportMountedRef.current = false;
activeShareImportTokenRef.current = null;
cancellingShareImportKeyRef.current = null;
};
}, []);
@@ -263,14 +163,6 @@ export function NewTaskDraftScreen(props: {
setProject(directProject);
return;
}
if (projects.length > 0) {
// Never fall through to the flow provider's temporary first-project
// default. Return to the picker with the share id intact so the user
// can choose an available destination.
setIsReturningToProjectPicker(true);
}
return;
}
if (selectedProject) {
@@ -287,7 +179,6 @@ export function NewTaskDraftScreen(props: {
logicalProjects,
projects,
props.initialProjectRef,
props.incomingShareId,
props.pendingTaskId,
navigation,
selectedProject,
@@ -307,205 +198,6 @@ export function NewTaskDraftScreen(props: {
void flow.loadBranches();
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
const shareId = props.incomingShareId;
const draftKey = flow.draftKey;
const destinationProject = selectedProject;
const initialEnvironmentId = props.initialProjectRef?.environmentId;
const initialProjectId = props.initialProjectRef?.projectId;
const selectedProjectMatchesRoute =
!initialEnvironmentId ||
!initialProjectId ||
(destinationProject?.environmentId === initialEnvironmentId &&
destinationProject.id === initialProjectId);
if (
!shareId ||
!draftKey ||
!destinationProject ||
!selectedProjectMatchesRoute ||
cancelledIncomingShareId === shareId
) {
return;
}
const importKey = `${shareId}:${draftKey}`;
if (
startedShareImportKeyRef.current === importKey ||
cancellingShareImportKeyRef.current === importKey
) {
return;
}
if (!incomingShare) {
if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
alertedUnavailableIncomingShareIdRef.current = shareId;
Alert.alert(
"Shared content unavailable",
"The shared content is no longer in the inbox. You can continue editing this task draft.",
);
}
return;
}
if (alertedUnavailableIncomingShareIdRef.current === shareId) {
alertedUnavailableIncomingShareIdRef.current = null;
}
startedShareImportKeyRef.current = importKey;
const draftBackup =
shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
shareImportDraftBackupRef.current.set(importKey, draftBackup);
const importToken = Symbol(importKey);
let didReserveShare = false;
let needsDraftRestore = false;
activeShareImportTokenRef.current = importToken;
setImportingShareKey(importKey);
void (async () => {
await reserveShare(shareId, {
environmentId: String(destinationProject.environmentId),
projectId: String(destinationProject.id),
});
didReserveShare = true;
if (
!shareImportMountedRef.current ||
activeShareImportTokenRef.current !== importToken ||
latestDraftKeyRef.current !== draftKey ||
latestIncomingShareIdRef.current !== shareId
) {
return;
}
needsDraftRestore = true;
const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
text: incomingShare.text,
attachments: incomingShare.attachments,
sourceShareId: shareId,
});
if (
!shareImportMountedRef.current ||
activeShareImportTokenRef.current !== importToken ||
latestDraftKeyRef.current !== draftKey ||
latestIncomingShareIdRef.current !== shareId
) {
// The durable reservation makes an interrupted transfer resume only
// in this project instead of copying into a second project draft.
return;
}
await consumeShare(shareId);
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
return;
}
const warnings = [...incomingShare.warnings];
if (skippedAttachmentCount > 0) {
warnings.push(
`${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
);
}
if (warnings.length > 0) {
Alert.alert("Some shared content was skipped", warnings.join("\n"));
}
shareImportDraftBackupRef.current.delete(importKey);
})()
.catch((error) => {
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
return;
}
Alert.alert(
"Could not import shared content",
error instanceof Error ? error.message : "The shared content could not be saved.",
[
{
text: "Cancel import",
style: "cancel",
onPress: () => {
const cancelImport = async (): Promise<void> => {
if (!shareImportMountedRef.current) {
return;
}
// Latch synchronously before restoring the draft. The
// restore publishes atom state and can re-run the import
// effect before React commits the cancelling state update.
cancellingShareImportKeyRef.current = importKey;
setIsCancellingShareImport(true);
try {
if (needsDraftRestore) {
await restoreComposerDraftSnapshot(draftKey, draftBackup);
needsDraftRestore = false;
}
if (didReserveShare) {
await releaseShareReservation(shareId, {
environmentId: String(destinationProject.environmentId),
projectId: String(destinationProject.id),
});
}
shareImportDraftBackupRef.current.delete(importKey);
if (shareImportMountedRef.current) {
setIsCancellingShareImport(false);
setCancelledIncomingShareId(shareId);
}
} catch (cancelError) {
if (!shareImportMountedRef.current) {
return;
}
Alert.alert(
"Could not cancel import",
cancelError instanceof Error
? cancelError.message
: "The shared content could not be restored safely.",
[
{
text: "Retry import",
onPress: () => {
cancellingShareImportKeyRef.current = null;
setIsCancellingShareImport(false);
setShareImportAttempt((attempt) => attempt + 1);
},
},
{
text: "Retry cancel",
onPress: () => void cancelImport(),
},
],
{ cancelable: false },
);
}
};
void cancelImport();
},
},
{
text: "Retry",
onPress: () => setShareImportAttempt((attempt) => attempt + 1),
},
],
{ cancelable: false },
);
})
.finally(() => {
if (startedShareImportKeyRef.current === importKey) {
// Every terminal path, including an invalidated operation, must
// release the synchronous start latch so this transfer can retry.
startedShareImportKeyRef.current = null;
}
if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
activeShareImportTokenRef.current = null;
setImportingShareKey(null);
}
});
}, [
consumeShare,
cancelledIncomingShareId,
flow.draftKey,
hasImportedIncomingShare,
incomingShare,
isIncomingShareInboxLoading,
isIncomingShareUnavailable,
props.incomingShareId,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
releaseShareReservation,
reserveShare,
selectedProject,
shareImportAttempt,
]);
useEffect(() => {
// Android starts with the collapsed composer pill (like an open thread)
// and only expands/focuses when tapped.
@@ -531,11 +223,10 @@ export function NewTaskDraftScreen(props: {
flow.environments.map((environment) => ({
id: `environment:${environment.environmentId}`,
title: environment.environmentLabel,
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
state:
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
})),
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
[flow.environments, flow.selectedEnvironmentId],
);
const modelMenuActions = useMemo(
@@ -700,23 +391,20 @@ export function NewTaskDraftScreen(props: {
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
if (!event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
if (!event.startsWith("environment:")) {
return;
}
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
@@ -736,9 +424,6 @@ export function NewTaskDraftScreen(props: {
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
if (event.startsWith("workspace:mode:")) {
flow.setWorkspaceMode(
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
@@ -759,9 +444,6 @@ export function NewTaskDraftScreen(props: {
}
async function handlePickImages(): Promise<void> {
if (isIncomingShareTransferPending) {
return;
}
const result = await pickComposerImages({ existingCount: flow.attachments.length });
if (result.images.length > 0) {
flow.appendAttachments(result.images);
@@ -844,7 +526,8 @@ export function NewTaskDraftScreen(props: {
if (editingPendingTask) {
flow.finishEditingPendingTask();
} else {
clearComposerDraftContent(draftKey);
flow.setPrompt("");
flow.clearAttachments();
}
navigation.getParent()?.goBack();
return;
@@ -902,7 +585,8 @@ export function NewTaskDraftScreen(props: {
}
flow.finishEditingPendingTask();
} else {
clearComposerDraftContent(draftKey);
flow.setPrompt("");
flow.clearAttachments();
}
navigation.dispatch(
StackActions.replace("Thread", {
@@ -936,15 +620,12 @@ export function NewTaskDraftScreen(props: {
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
flow.prompt.trim().length > 0 &&
isIncomingShareReady &&
!isImportingShare &&
!flow.submitting &&
!(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
const promptEditor = (
<ComposerEditor
ref={promptInputRef}
autoFocus={!isAndroid}
editable={!isIncomingShareTransferPending}
multiline
scrollEnabled={isExpanded}
value={flow.prompt}
@@ -979,7 +660,6 @@ export function NewTaskDraftScreen(props: {
icon="plus"
onPress={() => void handlePickImages()}
showChevron={false}
disabled={isIncomingShareTransferPending}
/>
<ControlPillMenu
actions={modelMenuActions}
@@ -987,7 +667,6 @@ export function NewTaskDraftScreen(props: {
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
@@ -998,7 +677,6 @@ export function NewTaskDraftScreen(props: {
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
@@ -1009,7 +687,6 @@ export function NewTaskDraftScreen(props: {
>
<ComposerToolbarTrigger
accessibilityLabel="Environment"
disabled={isIncomingShareTransferPending}
icon="desktopcomputer"
label={selectedEnvironmentLabel}
/>
@@ -1020,7 +697,6 @@ export function NewTaskDraftScreen(props: {
>
<ComposerToolbarTrigger
accessibilityLabel="Workspace"
disabled={isIncomingShareTransferPending}
icon="point.topleft.down.curvedto.point.bottomright.up"
label={workspaceLabel}
/>
@@ -1087,9 +763,7 @@ export function NewTaskDraftScreen(props: {
<View className="pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
}
onRemove={flow.removeAttachment}
/>
</View>
) : null}
@@ -1133,7 +807,7 @@ export function NewTaskDraftScreen(props: {
<View className="px-4 pt-3">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
onRemove={flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
@@ -1,9 +1,9 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef } from "react";
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
import { useMemo } from "react";
import { ActivityIndicator, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { cn } from "../../lib/cn";
@@ -16,11 +16,6 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
};
function deriveProjectEmptyState(catalogState: WorkspaceState): {
readonly title: string;
@@ -77,29 +72,15 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
};
}
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
export function NewTaskRouteScreen() {
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const navigation = useNavigation();
const isFocused = useIsFocused();
const { layout } = useAdaptiveWorkspaceLayout();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const { getShare, releaseShareReservation } = useIncomingShare();
const routeShareId = Array.isArray(route.params?.incomingShareId)
? route.params.incomingShareId[0]
: route.params?.incomingShareId;
const incomingShare = routeShareId ? getShare(routeShareId) : null;
const incomingShareSubtitle = incomingShare
? incomingShare.attachments.length === 0
? "Choose a project for what you shared"
: incomingShare.attachments.length === 1
? "Choose a project for the image you shared"
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
: null;
const screenTitle = incomingShare ? "Start a task" : "Choose project";
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
@@ -128,70 +109,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
return nextItems;
}, [repositoryGroups]);
const projectEmptyState = deriveProjectEmptyState(catalogState);
const resumedDestinationKeyRef = useRef<string | null>(null);
const reservedDestinationProject = incomingShare?.destination
? (projects.find(
(project) =>
project.environmentId === incomingShare.destination?.environmentId &&
project.id === incomingShare.destination?.projectId,
) ?? null)
: null;
async function selectProject(item: (typeof items)[number]): Promise<void> {
if (incomingShare?.destination && !reservedDestinationProject) {
try {
await releaseShareReservation(incomingShare.id, incomingShare.destination);
} catch (error) {
Alert.alert(
"Could not change project",
error instanceof Error
? error.message
: "The shared content reservation could not be updated.",
);
return;
}
}
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
incomingShareId: incomingShare?.id,
},
});
}
useEffect(() => {
const destination = incomingShare?.destination;
if (!destination) {
resumedDestinationKeyRef.current = null;
return;
}
if (!isFocused) {
// Returning from the reserved draft is a fresh resume attempt. Keeping
// this latch set would leave every project row disabled with no route.
resumedDestinationKeyRef.current = null;
return;
}
const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
if (resumedDestinationKeyRef.current === destinationKey) {
return;
}
if (!reservedDestinationProject) {
return;
}
resumedDestinationKeyRef.current = destinationKey;
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: reservedDestinationProject.environmentId,
projectId: reservedDestinationProject.id,
title: reservedDestinationProject.title,
incomingShareId: incomingShare.id,
},
});
}, [incomingShare, isFocused, navigation, reservedDestinationProject]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -200,8 +117,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
{/* Android renders its own in-screen header instead of the native bar. */}
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader
title={screenTitle}
subtitle={incomingShareSubtitle}
title="Choose project"
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
actions={[
{
@@ -213,29 +129,21 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
/>
</>
) : (
<>
<NativeStackScreenOptions
options={{
title: screenTitle,
unstable_headerSubtitle: incomingShareSubtitle ?? undefined,
}}
/>
<NativeHeaderToolbar placement="right">
{layout.usesSplitView ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Close new task"
icon="xmark"
onPress={() => navigation.goBack()}
separateBackground
/>
) : null}
<NativeHeaderToolbar placement="right">
{layout.usesSplitView ? (
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
accessibilityLabel="Close new task"
icon="xmark"
onPress={() => navigation.goBack()}
separateBackground
/>
</NativeHeaderToolbar>
</>
) : null}
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
separateBackground
/>
</NativeHeaderToolbar>
)}
<ScrollView
@@ -244,7 +152,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingHorizontal: 20,
paddingTop: 8,
}}
@@ -287,8 +194,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
return (
<Pressable
key={item.key}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(item)}
onPress={() =>
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
},
})
}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
-4
View File
@@ -1,4 +0,0 @@
export function estimateBase64ByteSize(base64: string): number {
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return Math.floor((base64.length * 3) / 4) - padding;
}
+1 -31
View File
@@ -36,37 +36,7 @@ vi.mock("./uuid", () => ({
uuidv4: () => "attachment-id",
}));
import {
convertPastedImagesToAttachments,
isOwnedPastedImageUri,
toUploadChatImageAttachments,
} from "./composerImages";
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==",
},
]);
});
});
import { convertPastedImagesToAttachments, isOwnedPastedImageUri } from "./composerImages";
describe("native pasted image cleanup", () => {
beforeEach(() => {
+5 -14
View File
@@ -3,7 +3,6 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import { estimateBase64ByteSize } from "./base64";
import { uuidv4 } from "./uuid";
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
@@ -11,21 +10,13 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
readonly previewUri: string;
}
/** 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,
}));
}
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
function estimateBase64ByteSize(base64: string): number {
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return Math.floor((base64.length * 3) / 4) - padding;
}
async function loadImagePicker() {
try {
return await import("expo-image-picker");
@@ -8,7 +8,7 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
import type { DraftComposerImageAttachment } from "./composerImages";
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
@@ -55,7 +55,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
messageId: MessageId.make(spec.messageId),
role: "user" as const,
text: spec.text,
attachments: toUploadChatImageAttachments(spec.attachments),
attachments: spec.attachments,
},
modelSelection: spec.modelSelection,
titleSeed: title,
@@ -1,45 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import { SerializedAsyncQueue } from "./serialized-async-queue";
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((next) => {
resolve = next;
});
return { promise, resolve };
}
describe("SerializedAsyncQueue", () => {
it("does not let a newer operation overtake an in-flight operation", async () => {
const queue = new SerializedAsyncQueue();
const firstGate = deferred();
const events: string[] = [];
const first = queue.run(async () => {
events.push("first:start");
await firstGate.promise;
events.push("first:end");
});
const second = queue.run(async () => {
events.push("second");
});
await Promise.resolve();
expect(events).toEqual(["first:start"]);
firstGate.resolve();
await Promise.all([first, second]);
expect(events).toEqual(["first:start", "first:end", "second"]);
});
it("continues after a rejected operation", async () => {
const queue = new SerializedAsyncQueue();
const first = queue.run(async () => {
throw new Error("failed");
});
const second = queue.run(async () => "recovered");
await expect(first).rejects.toThrow("failed");
await expect(second).resolves.toBe("recovered");
});
});
@@ -1,16 +0,0 @@
/**
* Runs asynchronous operations in call order while keeping the queue usable
* after an individual operation rejects.
*/
export class SerializedAsyncQueue {
private tail: Promise<void> = Promise.resolve();
run<T>(operation: () => Promise<T>): Promise<T> {
const result = this.tail.then(operation, operation);
this.tail = result.then(
() => undefined,
() => undefined,
);
return result;
}
}
+1 -2
View File
@@ -195,7 +195,7 @@ function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
if (typeName === "NativeHeaderToolbarButton") {
return {
type: "button",
label: typeof child.props.label === "string" ? child.props.label : "",
label: "",
accessibilityLabel:
typeof child.props.accessibilityLabel === "string"
? child.props.accessibilityLabel
@@ -293,7 +293,6 @@ function NativeHeaderToolbarButton(_props: {
readonly accessibilityLabel?: string;
readonly disabled?: boolean;
readonly icon?: string;
readonly label?: string;
readonly onPress?: () => void;
readonly separateBackground?: boolean;
readonly tintColor?: ColorValue;
@@ -101,10 +101,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
cause,
});
}
setMessages([
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
message,
]);
setMessages([...currentMessages(), message]);
});
// Rewrites an already-queued message. A no-op when the message has been
@@ -294,31 +294,6 @@ describe("thread outbox", () => {
registry.dispose();
});
it("replaces an existing message when an enqueue retry uses the same id", async () => {
const registry = AtomRegistry.make();
const manager = createThreadOutboxManager({
registry,
storage: {
load: async () => [],
write: async () => undefined,
remove: async () => undefined,
},
});
const message = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const retried = { ...message, text: "retried" };
await manager.enqueue(message);
await manager.enqueue(retried);
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
"environment-1:thread-1": [retried],
});
registry.dispose();
});
it("updates a queued message in place but never resurrects a removed one", async () => {
const registry = AtomRegistry.make();
const stored = new Map<MessageId, QueuedThreadMessage>();
@@ -8,9 +8,7 @@ import {
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
mergeComposerDraftContentState,
removeComposerDraftsForEnvironment,
restoreComposerDraftSnapshotState,
} from "./use-composer-drafts";
const DRAFT: ComposerDraft = {
@@ -96,7 +94,6 @@ describe("mobile composer drafts", () => {
const draft: ComposerDraft = {
text: "send this",
attachments: [],
importedShareIds: ["share-1"],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
@@ -111,8 +108,7 @@ describe("mobile composer drafts", () => {
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
[draftKey]: {
modelSelection: draft.modelSelection,
workspaceSelection: draft.workspaceSelection,
...draft,
text: "",
attachments: [],
},
@@ -135,90 +131,6 @@ describe("mobile composer drafts", () => {
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
});
it("merges shared content into a project draft without duplicating retries", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedAttachment = {
id: "share-1:image:0",
type: "image" as const,
name: "Screenshot.png",
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
};
const existing: Record<string, ComposerDraft> = {
[draftKey]: { text: "Existing context", attachments: [] },
};
const content = {
text: "Shared note",
attachments: [sharedAttachment],
sourceShareId: "share-1",
};
const merged = mergeComposerDraftContentState(existing, draftKey, content);
expect(merged[draftKey]).toMatchObject({
text: "Existing context\n\nShared note",
attachments: [sharedAttachment],
importedShareIds: ["share-1"],
});
expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
const edited = {
...merged,
[draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
};
expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
});
it("preserves existing images when shared content exceeds the draft attachment limit", () => {
const draftKey = "new-task:environment-1:project-1";
const image = (id: string) => ({
id,
type: "image" as const,
name: `${id}.png`,
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
});
const existingImage = image("existing");
const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
const merged = mergeComposerDraftContentState(
{ [draftKey]: { text: "", attachments: [existingImage] } },
draftKey,
{ text: "", attachments: sharedImages },
);
expect(merged[draftKey]?.attachments).toHaveLength(8);
expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
});
it("restores the exact draft captured before an interrupted share import", () => {
const draftKey = "new-task:environment-1:project-1";
const beforeImport: ComposerDraft = {
text: "Existing context",
attachments: [],
runtimeMode: "approval-required",
};
const imported: ComposerDraft = {
...beforeImport,
text: "Existing context\n\nShared note",
importedShareIds: ["share-1"],
};
expect(
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
).toEqual({ [draftKey]: beforeImport });
expect(
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
text: "",
attachments: [],
}),
).toEqual({});
});
it("removes only drafts owned by the selected environment", () => {
const environmentId = EnvironmentId.make("environment-cloud");
const retainedEnvironmentId = EnvironmentId.make("environment-local");
+2 -146
View File
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import {
ModelSelection as ModelSelectionSchema,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
@@ -15,7 +14,6 @@ import { Atom } from "effect/unstable/reactivity";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
import { appAtomRegistry } from "./atom-registry";
const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
@@ -40,19 +38,12 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly importedShareIds?: ReadonlyArray<string>;
readonly modelSelection?: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
}
export interface ComposerDraftContent {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly sourceShareId?: string;
}
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
@@ -75,7 +66,6 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
const ComposerDraftSchema = Schema.Struct({
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
importedShareIds: Schema.optional(Schema.Array(Schema.String)),
modelSelection: Schema.optional(ModelSelectionSchema),
runtimeMode: Schema.optional(RuntimeModeSchema),
interactionMode: Schema.optional(ProviderInteractionModeSchema),
@@ -103,7 +93,6 @@ export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).p
let loadPromise: Promise<void> | null = null;
let persistTimer: ReturnType<typeof setTimeout> | null = null;
const persistenceQueue = new SerializedAsyncQueue();
function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
if (!draft) {
@@ -204,7 +193,7 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
try {
await persistenceQueue.run(() => writePersistedComposerDrafts(drafts));
await writePersistedComposerDrafts(drafts);
} catch (error) {
console.warn("[composer-drafts] failed to persist drafts", error);
// Draft persistence is best-effort; in-memory drafts still keep working.
@@ -377,9 +366,8 @@ export function clearComposerDraftContentState(
if (!existing) {
return current;
}
const { importedShareIds: _importedShareIds, ...retained } = existing;
const draft = {
...retained,
...existing,
text: "",
attachments: [],
};
@@ -394,138 +382,6 @@ export function clearComposerDraftContentState(
};
}
export function restoreComposerDraftSnapshotState(
current: Record<string, ComposerDraft>,
draftKey: string,
snapshot: ComposerDraft,
): Record<string, ComposerDraft> {
const next = { ...current };
if (isEmptyDraft(snapshot)) {
delete next[draftKey];
} else {
next[draftKey] = snapshot;
}
return next;
}
function mergeComposerDraftText(existing: string, incoming: string): string {
if (incoming.length === 0) {
return existing;
}
if (existing.length === 0) {
return incoming;
}
// Import retries are possible after an interrupted native handoff. Keep the
// operation idempotent when the same shared text is already present.
if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
return existing;
}
return `${existing}\n\n${incoming}`;
}
export function mergeComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
content: ComposerDraftContent,
): Record<string, ComposerDraft> {
const existing = normalizeDraft(current[draftKey]);
if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
return current;
}
const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
const incomingAttachments = content.attachments.filter((attachment) => {
if (attachmentIds.has(attachment.id)) {
return false;
}
attachmentIds.add(attachment.id);
return true;
});
const attachments = [...existing.attachments, ...incomingAttachments].slice(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
);
const text = mergeComposerDraftText(existing.text, content.text);
const importedShareIds = content.sourceShareId
? [...(existing.importedShareIds ?? []), content.sourceShareId]
: existing.importedShareIds;
if (
text === existing.text &&
attachments.length === existing.attachments.length &&
importedShareIds === existing.importedShareIds
) {
return current;
}
return {
...current,
[draftKey]: {
...existing,
text,
attachments,
...(importedShareIds ? { importedShareIds } : {}),
},
};
}
/**
* Atomically moves an incoming share into a project-scoped composer draft.
* The durable write happens before the share inbox item can be acknowledged.
*/
export async function mergeComposerDraftContent(
draftKey: string,
content: ComposerDraftContent,
): Promise<{ readonly skippedAttachmentCount: number }> {
ensureComposerDraftsLoaded();
if (loadPromise !== null) {
await loadPromise;
}
if (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
}
const current = appAtomRegistry.get(composerDraftsAtom);
const next = mergeComposerDraftContentState(current, draftKey, content);
const currentAttachmentIds = new Set(
normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
);
const nextAttachmentIds = new Set(
normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
);
const skippedAttachmentCount = content.attachments.filter(
(attachment) =>
!currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
).length;
// Publish the content and its import receipt together before the filesystem
// await. Typing during persistence then builds on the receipt-bearing state,
// and its debounced write is serialized after this transaction.
if (next !== current) {
appAtomRegistry.set(composerDraftsAtom, next);
}
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
return { skippedAttachmentCount };
}
/** Restores the exact content/settings captured before an interrupted import. */
export async function restoreComposerDraftSnapshot(
draftKey: string,
snapshot: ComposerDraft,
): Promise<void> {
ensureComposerDraftsLoaded();
if (loadPromise !== null) {
await loadPromise;
}
if (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
}
const next = restoreComposerDraftSnapshotState(
appAtomRegistry.get(composerDraftsAtom),
draftKey,
snapshot,
);
appAtomRegistry.set(composerDraftsAtom, next);
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
}
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
}
@@ -17,7 +17,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { scopedThreadKey } from "../lib/scopedEntities";
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
import { toUploadChatImageAttachments } from "../lib/composerImages";
import { randomHex } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { useProjects, useThreadShells } from "./entities";
@@ -222,7 +221,7 @@ export function useThreadOutboxDrain(): void {
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
attachments: queuedMessage.attachments,
},
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
+11 -7
View File
@@ -74,7 +74,9 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
assertSome(payload, {
mode: "desktop",
});
@@ -100,7 +102,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
assertSome(payload, {
mode: "desktop",
@@ -125,7 +127,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.errorCode = "EIO";
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
assert.instanceOf(error, BootstrapInputStreamOpenError);
@@ -149,7 +151,9 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const fd = NodeFS.openSync("/dev/null", "r");
NodeFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
assertNone(payload);
}),
);
@@ -164,7 +168,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
fstatSyncInterceptor.failFd = fd;
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapFdStatError);
@@ -188,7 +192,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapEnvelopeDecodeError);
@@ -227,7 +231,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
+4 -3
View File
@@ -4,6 +4,7 @@ import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
@@ -75,7 +76,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeoutMs?: number;
timeout?: Duration.Input;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
@@ -83,7 +84,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
const stream = yield* makeBootstrapInputStream(fd);
const timeoutMs = options?.timeoutMs ?? 1000;
const timeout = options?.timeout ?? Duration.seconds(1);
return yield* Effect.callback<
Option.Option<A>,
@@ -142,7 +143,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
}).pipe(Effect.timeoutOption(timeout), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
@@ -6,7 +6,6 @@ import type {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
import * as Effect from "effect/Effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -72,30 +71,6 @@ export function requireProjectAbsent(input: {
);
}
export function requireActiveProjectWorkspaceRootAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly workspaceRoot: string;
readonly exceptProjectId?: ProjectId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
const existingProject = input.readModel.projects.find(
(project) =>
project.deletedAt === null &&
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
project.id !== input.exceptProjectId,
);
if (existingProject === undefined) {
return Effect.void;
}
return Effect.fail(
invariantError(
input.command.type,
`Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,
),
);
}
export function requireThread(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
@@ -94,117 +94,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
}),
);
it.effect("rejects project.create for an active workspace root that already exists", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-existing"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-existing"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-duplicate-root"),
projectId: asProjectId("project-duplicate-root"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project/",
createdAt: now,
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-existing' already exists for workspace root '/tmp/project'.",
);
}),
);
it.effect("rejects project.meta.update when moving onto another active workspace root", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withFirstProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-first"),
aggregateKind: "project",
aggregateId: asProjectId("project-first"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-first"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-first"),
metadata: {},
payload: {
projectId: asProjectId("project-first"),
title: "First",
workspaceRoot: "/tmp/project-first",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withFirstProject, {
sequence: 2,
eventId: asEventId("evt-project-create-second"),
aggregateKind: "project",
aggregateId: asProjectId("project-second"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-second"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-second"),
metadata: {},
payload: {
projectId: asProjectId("project-second"),
title: "Second",
workspaceRoot: "/tmp/project-second",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-duplicate-root"),
projectId: asProjectId("project-second"),
workspaceRoot: "/tmp/project-first",
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-first' already exists for workspace root '/tmp/project-first'.",
);
}),
);
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
-15
View File
@@ -12,7 +12,6 @@ import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireActiveProjectWorkspaceRootAbsent,
requireProject,
requireProjectAbsent,
requireThread,
@@ -112,12 +111,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
return {
...(yield* withEventBase({
@@ -145,14 +138,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
if (command.workspaceRoot !== undefined) {
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -31,7 +31,7 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
const resolved = path.resolve(NodeOS.homedir(), ".claude-work");
expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved);
expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved);
expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved);
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
`claude\0${resolved}`,
@@ -24,13 +24,7 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return {
...resolvedBaseEnv,
// Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.
// Overriding HOME also relocates the macOS login keychain lookup
// ($HOME/Library/Keychains), so the spawned CLI can't find its stored
// OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points
// Claude Code at its config dir directly while leaving HOME (and the
// keychain) intact.
CLAUDE_CONFIG_DIR: resolvedHomePath,
HOME: resolvedHomePath,
};
});
@@ -418,7 +418,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("runs Claude SDK sessions with the configured CLAUDE_CONFIG_DIR", () => {
it.effect("runs Claude SDK sessions with the configured Claude HOME", () => {
const harness = makeHarness({ claudeConfig: { homePath: "~/.claude-work" } });
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -433,10 +433,7 @@ describe("ClaudeAdapterLive", () => {
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(
createInput?.options.env?.CLAUDE_CONFIG_DIR,
NodePath.join(NodeOS.homedir(), ".claude-work"),
);
assert.equal(createInput?.options.env?.HOME, NodePath.join(NodeOS.homedir(), ".claude-work"));
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -974,13 +974,8 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "request.opened" && event.requestId && !interrupted) {
if (event.type === "request.opened" && !interrupted) {
interrupted = true;
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(event.requestId)),
"cancel",
);
yield* adapter.interruptTurn(threadId);
return;
}
@@ -1035,10 +1030,15 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "cancelled";
const cancelRequests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
const approvalResponses = yield* waitForJsonLogMatch(
requestLogPath,
isCancelledApprovalResponse,
);
assert.isTrue(cancelRequests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(approvalResponses.some(isCancelledApprovalResponse));
yield* adapter.stopSession(threadId);
@@ -38,7 +38,6 @@ import {
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
buildOpenCodePermissionRules,
isOpenCodeRuntimeError,
OpenCodeRuntime,
OpenCodeRuntimeError,
openCodeQuestionId,
@@ -132,7 +131,7 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: isOpenCodeRuntimeError(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
cause,
});
@@ -1719,8 +1719,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
),
);
it.effect("runs Claude status probes with the configured CLAUDE_CONFIG_DIR", () => {
const claudeConfigDir = "/tmp/t3code-claude-home";
it.effect("runs Claude status probes with the configured Claude HOME", () => {
const claudeHome = "/tmp/t3code-claude-home";
const recorded = recordingMockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
@@ -1737,14 +1737,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const status = yield* checkClaudeProviderStatus(
{
...defaultClaudeSettings,
homePath: claudeConfigDir,
homePath: claudeHome,
},
claudeCapabilities(),
);
assert.strictEqual(status.status, "ready");
assert.deepStrictEqual(
recorded.commands.map((command) => command.env?.CLAUDE_CONFIG_DIR),
[claudeConfigDir],
recorded.commands.map((command) => command.env?.HOME),
[claudeHome],
);
}).pipe(Effect.provide(recorded.layer));
});
+13 -12
View File
@@ -13,12 +13,14 @@ import {
} from "@opencode-ai/sdk/v2";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Deferred from "effect/Deferred";
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 Option from "effect/Option";
import * as P from "effect/Predicate";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
@@ -48,16 +50,15 @@ export interface OpenCodeServerConnection {
readonly external: boolean;
}
export class OpenCodeRuntimeError extends Schema.TaggedErrorClass<OpenCodeRuntimeError>()(
"OpenCodeRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect()),
detail: Schema.String,
},
) {}
export const isOpenCodeRuntimeError = Schema.is(OpenCodeRuntimeError);
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
readonly operation: string;
readonly cause?: unknown;
readonly detail: string;
}> {
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
}
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
@@ -65,7 +66,7 @@ function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
}
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (isOpenCodeRuntimeError(cause)) return cause.detail;
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
if (cause && typeof cause === "object") {
// SDK v2 throws { response, request, error? } shapes — extract what's useful
@@ -269,7 +270,7 @@ function ensureRuntimeError(
detail: string,
cause: unknown,
): OpenCodeRuntimeError {
return isOpenCodeRuntimeError(cause)
return OpenCodeRuntimeError.is(cause)
? cause
: new OpenCodeRuntimeError({ operation, detail, cause });
}
-58
View File
@@ -5607,64 +5607,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("buffers thread events published while the initial snapshot loads", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
const messageEvent = {
sequence: 2,
eventId: EventId.make("event-message"),
aggregateKind: "thread",
aggregateId: defaultThreadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId: defaultThreadId,
messageId: MessageId.make("message-1"),
role: "user",
text: "First message",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:01.000Z",
updatedAt: "2026-01-01T00:00:01.000Z",
},
} satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;
yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
streamDomainEvents: Stream.fromPubSub(liveEvents),
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.gen(function* () {
yield* Effect.sleep("25 millis");
yield* PubSub.publish(liveEvents, messageEvent);
return Option.some({ snapshotSequence: 1, thread });
}),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
}).pipe(Stream.take(2), Stream.runCollect),
),
).pipe(Effect.timeout("2 seconds"));
assert.equal(items[0]?.kind, "snapshot");
assert.equal(items[1]?.kind, "event");
assert.equal(items[1]?.kind === "event" ? items[1].event.sequence : null, 2);
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
it.effect("enriches replayed project events with repository identity metadata", () =>
Effect.gen(function* () {
const repositoryIdentity = {
@@ -51,8 +51,8 @@ function makeFakeClaudeBinary(dir: string) {
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ] && [ "$CLAUDE_CONFIG_DIR" != "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ]; then',
' printf "%s\\n" "CLAUDE_CONFIG_DIR was $CLAUDE_CONFIG_DIR" >&2',
'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then',
' printf "%s\\n" "HOME was $HOME" >&2',
" exit 5",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
@@ -76,7 +76,7 @@ function withFakeClaudeEnv<A, E, R>(
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
configDirMustBe?: string;
homeMustBe?: string;
claudeConfig?: Partial<ClaudeSettings>;
},
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
@@ -92,7 +92,7 @@ function withFakeClaudeEnv<A, E, R>(
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
yield* Effect.acquireRelease(
Effect.sync(() => {
@@ -129,10 +129,10 @@ function withFakeClaudeEnv<A, E, R>(
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
if (input.configDirMustBe !== undefined) {
process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
if (input.homeMustBe !== undefined) {
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe;
} else {
delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
}
}),
() =>
@@ -175,10 +175,10 @@ function withFakeClaudeEnv<A, E, R>(
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
}
if (previousConfigDirMustBe === undefined) {
delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
if (previousHomeMustBe === undefined) {
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
} else {
process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe;
}
}),
);
@@ -286,10 +286,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
),
);
it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
it.effect("runs Claude text generation with the configured Claude HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
const claudeHome = path.join(process.cwd(), ".claude-work-test");
return yield* withFakeClaudeEnv(
{
// @effect-diagnostics-next-line preferSchemaOverJson:off
@@ -298,8 +298,8 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
title: "Use Claude home",
},
}),
configDirMustBe: claudeConfigDir,
claudeConfig: { homePath: claudeConfigDir },
homeMustBe: claudeHome,
claudeConfig: { homePath: claudeHome },
},
(textGeneration) =>
Effect.gen(function* () {
@@ -1,13 +1,13 @@
import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as NetService from "@t3tools/shared/Net";
import { beforeEach } from "vite-plus/test";
import { beforeEach, expect } from "vite-plus/test";
import * as ServerConfig from "../config.ts";
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
@@ -39,7 +39,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestLayer = Layer.mock(OpenCodeRuntime.OpenCodeRuntime)({
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
@@ -57,6 +57,13 @@ const OpenCodeRuntimeTestLayer = Layer.mock(OpenCodeRuntime.OpenCodeRuntime)({
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
@@ -92,7 +99,15 @@ const OpenCodeRuntimeTestLayer = Layer.mock(OpenCodeRuntime.OpenCodeRuntime)({
},
},
}) as unknown as ReturnType<OpenCodeRuntime.OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
});
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("opencode"),
@@ -108,7 +123,10 @@ const DEFAULT_COMMIT_MESSAGE_INPUT = {
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = OpenCodeRuntimeTestLayer.pipe(
const OpenCodeTextGenerationTestLayer = Layer.succeed(
OpenCodeRuntime.OpenCodeRuntime,
OpenCodeRuntimeTestDouble,
).pipe(
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
@@ -118,7 +136,10 @@ const OpenCodeTextGenerationTestLayer = OpenCodeRuntimeTestLayer.pipe(
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeRuntimeTestLayer.pipe(
const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
OpenCodeRuntime.OpenCodeRuntime,
OpenCodeRuntimeTestDouble,
).pipe(
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
@@ -176,16 +197,16 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
assert.deepStrictEqual(runtimeMock.state.startCalls, ["fake-opencode"]);
assert.deepStrictEqual(runtimeMock.state.promptUrls, [
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4301",
]);
assert.deepStrictEqual(runtimeMock.state.closeCalls, []);
expect(runtimeMock.state.closeCalls).toEqual([]);
yield* advanceIdleClock;
assert.deepStrictEqual(runtimeMock.state.closeCalls, ["http://127.0.0.1:4301"]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}),
).pipe(Effect.provide(TestClock.layer())),
);
@@ -211,12 +232,12 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
assert.deepStrictEqual(runtimeMock.state.startCalls, ["fake-opencode", "fake-opencode"]);
assert.deepStrictEqual(runtimeMock.state.promptUrls, [
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4302",
]);
assert.deepStrictEqual(runtimeMock.state.closeCalls, ["http://127.0.0.1:4301"]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}),
).pipe(Effect.provide(TestClock.layer())),
);
@@ -231,13 +252,15 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
assert.instanceOf(error, TextGenerationError);
assert.include(error.message, "OpenCode session.create request failed.");
const cause = error.cause;
assert.instanceOf(cause, OpenCodeTextGeneration.OpenCodeTextGenerationSessionRequestError);
assert.strictEqual(cause.operation, "generateCommitMessage");
assert.strictEqual(cause.cwd, process.cwd());
assert.strictEqual(cause.cause, sdkCause);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.message).toContain("OpenCode session.create request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
@@ -251,12 +274,13 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
assert.include(error.message, "OpenCode session.create returned no session payload.");
const cause = error.cause;
assert.instanceOf(cause, OpenCodeTextGeneration.OpenCodeTextGenerationSessionPayloadError);
assert.strictEqual(cause.operation, "generateCommitMessage");
assert.strictEqual(cause.cwd, process.cwd());
assert.notProperty(cause, "cause");
expect(error.message).toContain("OpenCode session.create returned no session payload.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionPayloadError",
operation: "generateCommitMessage",
cwd: process.cwd(),
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -271,15 +295,17 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
assert.include(error.message, "OpenCode session.prompt request failed.");
const cause = error.cause;
assert.instanceOf(cause, OpenCodeTextGeneration.OpenCodeTextGenerationPromptRequestError);
assert.strictEqual(cause.operation, "generateCommitMessage");
assert.strictEqual(cause.cwd, process.cwd());
assert.strictEqual(cause.sessionId, "http://127.0.0.1:4301/session");
assert.strictEqual(cause.providerId, "openai");
assert.strictEqual(cause.modelId, "gpt-5");
assert.strictEqual(cause.cause, sdkCause);
expect(error.message).toContain("OpenCode session.prompt request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
@@ -297,17 +323,18 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
assert.include(error.message, "OpenCode returned empty output.");
const cause = error.cause;
assert.instanceOf(cause, OpenCodeTextGeneration.OpenCodeTextGenerationEmptyOutputError);
assert.strictEqual(cause.operation, "generateCommitMessage");
assert.strictEqual(cause.cwd, process.cwd());
assert.strictEqual(cause.sessionId, "http://127.0.0.1:4301/session");
assert.strictEqual(cause.providerId, "openai");
assert.strictEqual(cause.modelId, "gpt-5");
assert.strictEqual(cause.responsePartCount, 3);
assert.strictEqual(cause.textPartCount, 1);
assert.notProperty(cause, "cause");
expect(error.message).toContain("OpenCode returned empty output.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationEmptyOutputError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
responsePartCount: 3,
textPartCount: 1,
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -334,7 +361,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
assert.deepStrictEqual(result, {
expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
@@ -363,17 +390,18 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
assert.include(error.message, "Model did not produce structured output");
const cause = error.cause;
assert.instanceOf(cause, OpenCodeTextGeneration.OpenCodeTextGenerationPromptResponseError);
assert.strictEqual(cause.operation, "generateCommitMessage");
assert.strictEqual(cause.cwd, process.cwd());
assert.strictEqual(cause.sessionId, "http://127.0.0.1:4301/session");
assert.strictEqual(cause.providerId, "openai");
assert.strictEqual(cause.modelId, "gpt-5");
assert.strictEqual(cause.providerErrorName, "StructuredOutputError");
assert.strictEqual(cause.providerMessage, "Model did not produce structured output");
assert.notProperty(cause, "cause");
expect(error.message).toContain("Model did not produce structured output");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptResponseError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
providerErrorName: "StructuredOutputError",
providerMessage: "Model did not produce structured output",
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -400,19 +428,19 @@ it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
assert.deepStrictEqual(runtimeMock.state.startCalls, []);
assert.deepStrictEqual(runtimeMock.state.promptUrls, [
expect(runtimeMock.state.startCalls).toEqual([]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
assert.deepStrictEqual(runtimeMock.state.authHeaders, [
expect(runtimeMock.state.authHeaders).toEqual([
`Basic ${btoa("opencode:secret-password")}`,
`Basic ${btoa("opencode:secret-password")}`,
]);
yield* advanceIdleClock;
assert.deepStrictEqual(runtimeMock.state.closeCalls, []);
expect(runtimeMock.state.closeCalls).toEqual([]);
}),
).pipe(Effect.provide(TestClock.layer())),
);
@@ -389,21 +389,19 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
? { serverPassword: openCodeSettings.serverPassword }
: {}),
});
const session = yield* OpenCodeRuntime.runOpenCodeSdk("session.create", () =>
client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
}),
).pipe(
Effect.mapError(
(cause) =>
new OpenCodeTextGenerationSessionRequestError({
operation: input.operation,
cwd: input.cwd,
cause: cause.cause,
}),
),
);
const session = yield* Effect.tryPromise({
try: () =>
client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
}),
catch: (cause) =>
new OpenCodeTextGenerationSessionRequestError({
operation: input.operation,
cwd: input.cwd,
cause,
}),
});
if (!session.data) {
return yield* new OpenCodeTextGenerationSessionPayloadError({
operation: input.operation,
@@ -420,23 +418,21 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
modelId: parsedModel.modelID,
};
const result = yield* OpenCodeRuntime.runOpenCodeSdk("session.prompt", () =>
client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
}),
).pipe(
Effect.mapError(
(cause) =>
new OpenCodeTextGenerationPromptRequestError({
...promptContext,
cause: cause.cause,
}),
),
);
const result = yield* Effect.tryPromise({
try: () =>
client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
}),
catch: (cause) =>
new OpenCodeTextGenerationPromptRequestError({
...promptContext,
cause,
}),
});
const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
if (promptFailure) {
return yield* new OpenCodeTextGenerationPromptResponseError({
@@ -6,9 +6,6 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
@@ -23,21 +20,6 @@ const TestLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(NodeServices.layer),
);
const makeNonRepositoryHandle = () =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.encodeText(Stream.make("fatal: not a git repository")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeTmpDir = (
prefix = "git-vcs-driver-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
@@ -95,62 +77,7 @@ const initRepoWithCommit = (
return { initialBranch };
});
it.effect("uses stable diagnostics for every parsed non-repository command", () => {
const commands: Array<{ readonly args: ReadonlyArray<string>; readonly lcAll?: string }> = [];
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
if (!ChildProcess.isStandardCommand(command)) {
return assert.fail("expected a standard Git command");
}
commands.push({
args: command.args,
...(command.options.env?.LC_ALL ? { lcAll: command.options.env.LC_ALL } : {}),
});
return makeNonRepositoryHandle();
}),
);
const nodeServicesLayer = Layer.merge(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const layer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfigLayer),
Layer.provideMerge(nodeServicesLayer),
);
return Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
const cwd = "/repo";
yield* driver.statusDetailsLocal(cwd);
yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false });
yield* driver.listRefs({ cwd });
assert.deepStrictEqual(commands, [
{ args: ["status", "--porcelain=2", "--branch"], lcAll: "C" },
{ args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" },
{ args: ["branch", "--no-color", "--no-column"], lcAll: "C" },
]);
}).pipe(Effect.provide(layer));
});
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
describe("process environment", () => {
it.effect("preserves the caller locale for general Git subprocesses", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const locale = yield* git(
cwd,
["-c", 'alias.print-locale=!printf "%s" "$LC_ALL"', "print-locale"],
{ LC_ALL: "zh_CN.UTF-8" },
);
assert.equal(locale, "zh_CN.UTF-8");
}),
);
});
describe("structured errors", () => {
it.effect("preserves structured spawn context and the platform cause", () =>
Effect.gen(function* () {
@@ -693,24 +620,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
assert.notInclude(status, "a.txt");
}),
);
it.effect("treats selected file paths literally", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* writeTextFile(cwd, "selected[1].txt", "literal\n");
yield* writeTextFile(cwd, "selected1.txt", "pattern match\n");
yield* driver.prepareCommitContext(cwd, ["selected[1].txt"]);
assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), "selected[1].txt");
const status = yield* git(cwd, ["status", "--porcelain"]);
assert.include(status, "?? selected1.txt");
}),
);
});
describe("remote operations", () => {
+3 -18
View File
@@ -830,20 +830,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}),
);
const executeGitWithStableDiagnostics = (
operation: string,
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>
executeGit(operation, cwd, args, {
...options,
env: {
...options.env,
LC_ALL: "C",
},
});
const runGit = (
operation: string,
cwd: string,
@@ -1198,7 +1184,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
const branchResult = yield* executeGitWithStableDiagnostics(
const branchResult = yield* executeGit(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
@@ -1318,7 +1304,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
const statusResult = yield* executeGitWithStableDiagnostics(
const statusResult = yield* executeGit(
"GitVcsDriver.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
@@ -1538,7 +1524,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}),
);
yield* runGit("GitVcsDriver.prepareCommitContext.addSelected", cwd, [
"--literal-pathspecs",
"add",
"-A",
"--",
@@ -2000,7 +1985,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.orElseSucceed(() => new Map<string, number>()),
);
const localBranchResult = yield* executeGitWithStableDiagnostics(
const localBranchResult = yield* executeGit(
"GitVcsDriver.listRefs.branchNoColor",
input.cwd,
["branch", "--no-color", "--no-column"],
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } 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 ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -73,6 +74,24 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("limits previews while preserving the full file byte length", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
const contents = "a".repeat(1024 * 1024 + 1);
yield* writeTextFile(cwd, "large.txt", contents);
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.strictEqual(result.contents.length, 1024 * 1024);
assert.strictEqual(result.byteLength, contents.length);
assert.strictEqual(result.truncated, true);
}),
);
it.effect("rejects reads outside the workspace root", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -177,16 +196,25 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "missing.txt" })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError);
expect(error).toMatchObject({
workspaceRoot: cwd,
relativePath: "missing.txt",
resolvedPath,
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
assert.instanceOf(error, WorkspaceFileSystem.WorkspaceFileSystemOperationError);
assert.deepEqual(
{
workspaceRoot: error.workspaceRoot,
relativePath: error.relativePath,
resolvedPath: error.resolvedPath,
operationPath: error.operationPath,
operation: error.operation,
},
{
workspaceRoot: cwd,
relativePath: "missing.txt",
resolvedPath,
operationPath: resolvedPath,
operation: "realpath-target",
},
);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.strictEqual(error.cause.reason._tag, "NotFound");
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -140,30 +137,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,24 +177,24 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
),
);
const stat = yield* file.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -204,20 +203,22 @@ export const make = Effect.gen(function* () {
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
const byteLength = Number(stat.size);
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
const buffer = new Uint8Array(bytesToRead);
const bytesRead = yield* file.read(buffer).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -226,36 +227,24 @@ export const make = Effect.gen(function* () {
operation: "read",
cause,
}),
),
);
const fileBytes = buffer.subarray(0, Number(bytesRead));
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
};
}),
);
});
+23 -23
View File
@@ -1166,14 +1166,6 @@ const makeWsRpcLayer = (
})),
);
// Attach live delivery before reading either replay or snapshot state.
// Otherwise an event published while the snapshot is loading is lost.
const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const bufferedLiveStream = Stream.fromQueue(liveBuffer);
// When the client already loaded the snapshot over HTTP it passes
// that snapshot's sequence, and we resume the live subscription by
// replaying persisted events after it instead of re-sending the
@@ -1193,20 +1185,28 @@ const makeWsRpcLayer = (
// so a global cap could otherwise omit this thread's events.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to replay thread ${input.threadId} events`,
cause,
}),
),
);
return Stream.concat(catchUpStream, bufferedLiveStream);
return Stream.unwrap(
Effect.gen(function* () {
const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to replay thread ${input.threadId} events`,
cause,
}),
),
);
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
}),
);
}
const snapshot = yield* projectionSnapshotQuery
@@ -1233,7 +1233,7 @@ const makeWsRpcLayer = (
kind: "snapshot" as const,
snapshot: snapshot.value,
}),
bufferedLiveStream,
liveStream,
);
}),
{ "rpc.aggregate": "orchestration" },
@@ -25,89 +25,6 @@ describe("browser target resolver", () => {
});
});
it("maps localhost URL navigation onto a remote Tailscale IPv4 host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "http://localhost:5173/dashboard?mode=test#results",
}),
).toEqual({
requestedUrl: "http://localhost:5173/dashboard?mode=test#results",
resolvedUrl: "http://100.65.180.100:5173/dashboard?mode=test#results",
resolutionKind: "direct-private-network",
environmentId: "environment-1",
});
});
it("preserves URL credentials when mapping localhost onto a remote host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "http://user:p%40ss@localhost:5173/dashboard",
}).resolvedUrl,
).toBe("http://user:p%[email protected]:5173/dashboard");
});
it("maps credentialed localhost URLs onto private IPv6 hosts", async () => {
readPreparedConnection.mockReturnValue({
httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773",
});
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "http://user:p%40ss@localhost:5173/dashboard?mode=test#results",
}).resolvedUrl,
).toBe("http://user:p%40ss@[fd7a:115c:a1e0::53]:5173/dashboard?mode=test#results");
});
it("maps schemeless localhost navigation onto a remote environment host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.1.25:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "localhost:3000/app",
}).resolvedUrl,
).toBe("http://192.168.1.25:3000/app");
});
it("keeps localhost navigation local for a local environment", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "localhost:3000/app",
}),
).toEqual({
requestedUrl: "localhost:3000/app",
resolvedUrl: "localhost:3000/app",
resolutionKind: "direct",
environmentId: "environment-1",
});
});
it("keeps localhost navigation local for the full IPv4 loopback range", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.2:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "http://localhost:3000/app",
}),
).toEqual({
requestedUrl: "http://localhost:3000/app",
resolvedUrl: "http://localhost:3000/app",
resolutionKind: "direct",
environmentId: "environment-1",
});
});
it("refuses public relay hosts until the authenticated gateway exists", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
@@ -117,12 +34,6 @@ describe("browser target resolver", () => {
port: 5173,
}),
).toThrow(/authenticated preview gateway/);
expect(() =>
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "url",
url: "http://localhost:5173",
}),
).toThrow(/authenticated preview gateway/);
});
it("normalizes schemeless localhost server-picker values", async () => {
@@ -152,9 +63,7 @@ describe("browser target resolver", () => {
});
it("supports private IPv6 environment hosts", async () => {
readPreparedConnection.mockReturnValue({
httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773",
});
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
@@ -162,18 +71,7 @@ describe("browser target resolver", () => {
port: 5173,
path: "/app?mode=test",
}).resolvedUrl,
).toBe("http://[fd7a:115c:a1e0::53]:5173/app?mode=test");
});
it("supports a local IPv6 environment host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
}).resolvedUrl,
).toBe("http://[::1]:5173/");
).toBe("http://[::1]:5173/app?mode=test");
});
it("leaves malformed input for the normal navigation error path", async () => {
+50 -99
View File
@@ -7,86 +7,26 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { readPreparedConnection } from "~/state/session";
const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
const parseIpv4Address = (host: string): readonly number[] | null => {
const parts = normalizeHostname(host).split(".").map(Number);
return parts.length === 4 &&
parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
? parts
: null;
};
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (normalized === "localhost" || normalized === "::1") return true;
return parseIpv4Address(normalized)?.[0] === 127;
};
const isPrivateNetworkHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) {
return true;
}
if (normalized.endsWith(".ts.net")) return true;
const parts = parseIpv4Address(normalized);
if (parts) {
return (
parts[0] === 10 ||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
(parts[0] === 169 && parts[1] === 254)
);
}
const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
const parts = normalized.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
return (
Number.isInteger(firstIpv6Hextet) &&
((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80)
parts[0] === 10 ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
parts[0] === 127 ||
(parts[0] === 169 && parts[1] === 254)
);
};
const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
return new URL(connection.httpBaseUrl);
};
const resolveEnvironmentPortTarget = (
environmentId: EnvironmentId,
target: Extract<BrowserNavigationTarget, { readonly kind: "environment-port" }>,
environmentUrl: URL,
requestedUrl?: string,
sourceUrl?: URL,
): PreviewUrlResolution => {
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
throw new Error(
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
);
}
const protocol = target.protocol ?? "http";
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
const resolvedHost = normalizedEnvironmentHost.includes(":")
? `[${normalizedEnvironmentHost}]`
: normalizedEnvironmentHost;
const resolved = sourceUrl
? new URL(sourceUrl)
: new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
if (sourceUrl) {
resolved.hostname = resolvedHost;
resolved.port = String(target.port);
}
return {
requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`,
resolvedUrl: resolved.toString(),
resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost)
? "direct"
: "direct-private-network",
environmentId,
};
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
};
export function resolveBrowserNavigationTarget(
@@ -94,30 +34,6 @@ export function resolveBrowserNavigationTarget(
target: BrowserNavigationTarget,
): PreviewUrlResolution {
if (target.kind === "url") {
let parsed: URL | null = null;
try {
parsed = new URL(normalizePreviewUrl(target.url));
} catch {
// Preserve the existing direct-navigation behavior so the preview host
// reports malformed URL errors through its normal navigation path.
}
if (parsed && isLoopbackHost(parsed.hostname)) {
const environmentUrl = readEnvironmentUrl(environmentId);
if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) {
return resolveEnvironmentPortTarget(
environmentId,
{
kind: "environment-port",
port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
protocol: parsed.protocol === "https:" ? "https" : "http",
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
},
environmentUrl,
target.url,
parsed,
);
}
}
return {
requestedUrl: target.url,
resolvedUrl: target.url,
@@ -125,15 +41,50 @@ export function resolveBrowserNavigationTarget(
environmentId,
};
}
return resolveEnvironmentPortTarget(environmentId, target, readEnvironmentUrl(environmentId));
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
throw new Error(
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
);
}
const protocol = target.protocol ?? "http";
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
const requestedUrl = `${protocol}://localhost:${target.port}${path}`;
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
const resolvedHost = normalizedEnvironmentHost.includes(":")
? `[${normalizedEnvironmentHost}]`
: normalizedEnvironmentHost;
const resolved = new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
return {
requestedUrl,
resolvedUrl: resolved.toString(),
resolutionKind:
normalizedEnvironmentHost === "localhost" || normalizedEnvironmentHost === "127.0.0.1"
? "direct"
: "direct-private-network",
environmentId,
};
}
export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
try {
const normalizedUrl = normalizePreviewUrl(rawUrl);
const parsed = new URL(normalizedUrl);
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
return normalizedUrl;
}
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
return resolveBrowserNavigationTarget(environmentId, {
kind: "url",
url: normalizedUrl,
kind: "environment-port",
port,
protocol: parsed.protocol === "https:" ? "https" : "http",
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
}).resolvedUrl;
} catch {
return rawUrl;
+2 -26
View File
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useEffect, type CSSProperties, type ReactNode } from "react";
import { useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
@@ -55,35 +55,11 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
? getWindowFullscreenState()
: false;
});
const macosWindowControlsStyle =
isMacosDesktop && !isWindowFullscreen
isElectron && isMacPlatform(navigator.platform)
? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
: undefined;
useEffect(() => {
if (!isMacosDesktop) return;
const bridge = window.desktopBridge;
if (!bridge) return;
const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
if (
typeof getWindowFullscreenState !== "function" ||
typeof onWindowFullscreenStateChange !== "function"
) {
return;
}
const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
setIsWindowFullscreen(getWindowFullscreenState());
return unsubscribe;
}, [isMacosDesktop]);
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
+5 -22
View File
@@ -32,7 +32,7 @@ import React, {
useState,
type ReactNode,
} from "react";
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
@@ -60,7 +60,6 @@ import {
serializeTableElementToCsv,
serializeTableElementToMarkdown,
} from "../markdown-clipboard";
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
@@ -165,24 +164,6 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
},
} satisfies Parameters<typeof rehypeSanitize>[0];
const CHAT_MARKDOWN_REMARK_PLUGINS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkBreaks,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
rehypeRaw,
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
@@ -1564,9 +1545,11 @@ function ChatMarkdown({
>
<ReactMarkdown
remarkPlugins={
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
lineBreaks
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
: [remarkGfm, remarkPreserveCodeMeta]
}
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
+1 -2
View File
@@ -3183,9 +3183,8 @@ export default function Sidebar() {
return buildPhysicalToLogicalProjectKeyMap({
projects: orderedProjects,
settings: projectGroupingSettings,
primaryEnvironmentId,
});
}, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
}, [orderedProjects, projectGroupingSettings]);
const projectPhysicalKeyByScopedRef = useMemo(
() =>
new Map(
@@ -1,6 +1,5 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
type EnvironmentConnectionPresentation,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
@@ -11,7 +10,7 @@ import {
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { environmentCatalog } from "~/connection/catalog";
import { cn } from "~/lib/utils";
@@ -23,12 +22,6 @@ import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRo
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
export interface SavedCloudEnvironmentConnection {
readonly environmentId: EnvironmentId;
readonly connection: EnvironmentConnectionPresentation;
}
export function RemoteEnvironmentRowsSkeleton() {
return (
@@ -47,19 +40,19 @@ export function RemoteEnvironmentRowsSkeleton() {
/**
* The user's T3 Connect environments from relay discovery, each with a
* Connect button. The primary environment is always excluded; already-saved
* environments are hidden unless `showSavedEnvironments` renders them with
* their live connection state (used by onboarding, where the full device mesh
* should be visible).
* environments are hidden unless `showSavedAsConnected` renders them as
* connected instead (used by onboarding, where the full device mesh should be
* visible).
*/
export function CloudEnvironmentConnectRows({
primaryEnvironmentId,
savedEnvironments,
showSavedEnvironments = false,
savedEnvironmentIds,
showSavedAsConnected = false,
empty = null,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;
readonly showSavedEnvironments?: boolean;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly showSavedAsConnected?: boolean;
readonly empty?: ReactNode;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
@@ -84,9 +77,7 @@ export function CloudEnvironmentConnectRows({
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedById = new Map(
savedEnvironments.map((environment) => [environment.environmentId, environment]),
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments();
@@ -99,8 +90,8 @@ export function CloudEnvironmentConnectRows({
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment added",
description: `Connecting to ${environment.label} through T3 Connect.`,
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
@@ -130,10 +121,10 @@ export function CloudEnvironmentConnectRows({
const visibleEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
(showSavedEnvironments || !savedById.has(environment.environmentId)),
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
);
const standalone = showSavedEnvironments || savedEnvironments.length === 0;
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
if (
standalone &&
@@ -172,57 +163,31 @@ export function CloudEnvironmentConnectRows({
}
return visibleEnvironments.map(({ environment, availability, error }) => {
const savedEnvironment = savedById.get(environment.environmentId);
const savedConnection = savedEnvironment
? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
: null;
const dotClassName = savedConnection
? savedConnection.tone === "connected"
? "bg-success"
: savedConnection.tone === "connecting"
? "bg-warning"
: savedConnection.tone === "error"
? "bg-destructive"
: "bg-muted-foreground/35"
: availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35";
const statusText = savedConnection
? savedConnection.statusText
: availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");
const alreadyConnected = savedIds.has(environment.environmentId);
return (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={dotClassName}
pingClassName={
savedConnection?.tone === "connecting" ||
(savedConnection === null && availability === "checking")
? "bg-warning/60 duration-2000"
: null
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
savedConnection
? savedConnection.statusText
: availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
@@ -230,19 +195,21 @@ export function CloudEnvironmentConnectRows({
<p
className={cn(
"mt-1 truncate text-xs",
savedConnection?.tone === "error" ||
(savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
(savedConnection === null && availability === "error")
? "text-destructive"
: "text-muted-foreground",
availability === "error" ? "text-destructive" : "text-muted-foreground",
)}
>
{statusText}
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
</p>
</div>
{savedConnection ? (
{alreadyConnected ? (
<Button size="sm" variant="outline" disabled>
{savedConnection.buttonLabel}
Connected
</Button>
) : (
<Button
@@ -1,7 +1,7 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { CheckIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
@@ -411,16 +411,20 @@ function OnboardingToggleRow({
function DevicesStep() {
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const savedEnvironments = environments.filter(
(environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
const savedEnvironmentIds = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.map((environment) => environment.environmentId),
[environments],
);
return (
<div className="overflow-hidden rounded-lg border">
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
savedEnvironments={savedEnvironments}
showSavedEnvironments
savedEnvironmentIds={savedEnvironmentIds}
showSavedAsConnected
empty={
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
No other environments are published to your account yet. Publish one from another device
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more