Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge ea7294bea7 style workspace filesystem assertions
Co-authored-by: Julius Marminge <[email protected]>
2026-07-16 16:07:29 +00:00
Cursor AgentandJulius Marminge 51f3403bc5 refactor workspace reads to Effect FileSystem
Co-authored-by: Julius Marminge <[email protected]>
2026-07-16 16:06:24 +00:00
66 changed files with 213 additions and 4393 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;
@@ -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,
-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)
@@ -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
}
@@ -248,17 +248,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 +359,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()
}
-2
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",
-5
View File
@@ -11,7 +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";
@@ -22,10 +21,6 @@ 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
-2
View File
@@ -48,7 +48,6 @@ 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,
@@ -314,7 +313,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")}>
@@ -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,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;
@@ -216,7 +215,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;
@@ -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>();
@@ -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),
@@ -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));
});
-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* () {
@@ -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,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -64,7 +66,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
relativePath: "src/index.ts",
});
expect(result).toEqual({
assert.deepStrictEqual(result, {
relativePath: "src/index.ts",
contents: "export const answer = 42;\n",
byteLength: 26,
@@ -82,7 +84,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "../escape.md" })
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
}),
@@ -107,14 +110,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceFilePathEscapeError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "linked-secret.txt",
resolvedWorkspaceRoot,
resolvedPath,
});
expect("cause" in error).toBe(false);
assert.notProperty(error, "cause");
}),
);
@@ -131,13 +134,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.pipe(Effect.flip);
const resolvedPath = yield* fileSystem.realPath(path.join(cwd, "src"));
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspacePathNotFileError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "src",
resolvedPath,
});
expect("cause" in error).toBe(false);
assert.notProperty(error, "cause");
}),
);
@@ -155,14 +158,31 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.pipe(Effect.flip);
const resolvedPath = yield* fileSystem.realPath(absolutePath);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceBinaryFileError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "asset.bin",
resolvedPath,
});
expect("cause" in error).toBe(false);
expect("contents" in error).toBe(false);
assert.notProperty(error, "cause");
assert.notProperty(error, "contents");
}),
);
it.effect("reads at most the preview limit", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "large.txt", "a".repeat(1024 * 1024 + 1));
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.strictEqual(result.contents.length, 1024 * 1024);
assert.strictEqual(result.byteLength, 1024 * 1024 + 1);
assert.isTrue(result.truncated);
}),
);
@@ -177,16 +197,16 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "missing.txt" })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceFileSystemOperationError");
assert.deepInclude(error, {
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.cause, PlatformError.PlatformError);
assert.strictEqual((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
}),
);
});
@@ -207,8 +227,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
.pipe(Effect.orDie);
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
expect(saved).toBe("# Plan\n");
assert.deepStrictEqual(result, { relativePath: "plans/effect-rpc.md" });
assert.strictEqual(saved, "# Plan\n");
}),
);
@@ -220,9 +240,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
const beforeWrite = yield* workspaceEntries.list({ cwd });
expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
false,
);
assert.isFalse(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
yield* workspaceFileSystem.writeFile({
cwd,
@@ -231,10 +249,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
});
const afterWrite = yield* workspaceEntries.list({ cwd });
expect(afterWrite.entries).toEqual(
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
);
expect(afterWrite.truncated).toBe(false);
assert.isTrue(afterWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
assert.isFalse(afterWrite.truncated);
}),
);
@@ -253,15 +269,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
})
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
const escapedPath = path.resolve(cwd, "..", "escape.md");
const escapedStat = yield* fileSystem
.stat(escapedPath)
.pipe(Effect.orElseSucceed(() => null));
expect(escapedStat).toBeNull();
const escapedStat = yield* fileSystem.stat(escapedPath).pipe(Effect.option);
assert.isTrue(Option.isNone(escapedStat));
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,7 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
@@ -19,6 +17,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +139,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 +179,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 handle = 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* handle.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -204,20 +205,21 @@ 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 maybeFileBytes = yield* handle.readAlloc(bytesToRead).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -226,36 +228,24 @@ export const make = Effect.gen(function* () {
operation: "read",
cause,
}),
),
);
const fileBytes = Option.getOrElse(maybeFileBytes, () => new Uint8Array());
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" },
+23 -4
View File
@@ -93,6 +93,7 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -108,7 +109,6 @@ import {
type Thread,
type TurnDiffSummary,
} from "../types";
import { useMarkActiveThreadVisited } from "../hooks/useMarkActiveThreadVisited";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteContext";
@@ -1036,9 +1036,9 @@ function ChatViewContent(props: ChatViewProps) {
const composerDraftTarget: ScopedThreadRef | DraftId =
routeKind === "server" ? routeThreadRef : props.draftId;
const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);
useMarkActiveThreadVisited(
routeKind === "server" ? routeThreadKey : null,
serverThread?.latestTurn?.completedAt ?? null,
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore((store) =>
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
);
const settings = useEnvironmentSettings(environmentId);
const setStickyComposerModelSelection = useComposerDraftStore(
@@ -1599,6 +1599,25 @@ function ChatViewContent(props: ChatViewProps) {
[openOrReuseProjectDraftThread],
);
useEffect(() => {
if (!serverThread?.id) return;
const threadUpdatedAt = Date.parse(serverThread.updatedAt);
if (Number.isNaN(threadUpdatedAt)) return;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
markThreadVisited(
scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
serverThread.updatedAt,
);
}, [
activeThreadLastVisitedAt,
markThreadVisited,
serverThread?.environmentId,
serverThread?.id,
serverThread?.updatedAt,
]);
const selectedProviderByThreadId = composerActiveProvider ?? null;
const threadProvider =
activeThread?.modelSelection.instanceId ??
@@ -24,7 +24,6 @@ const baseState: DesktopUpdateState = {
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt: null,
message: null,
@@ -15,48 +15,8 @@ import {
shouldToastDesktopUpdateActionResult,
} from "../desktopUpdate.logic";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { Separator } from "../ui/separator";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
function SidebarUpdateReleaseNotesTooltip({
state,
tooltip,
}: {
readonly state: NonNullable<ReturnType<typeof useDesktopUpdateState>>;
readonly tooltip: string;
}) {
if (state.channel !== "nightly" || state.releaseNotes.length === 0) {
return <>{tooltip}</>;
}
return (
<div className="w-120 max-w-[calc(100vw-2rem)] text-left">
<div className="px-1">
<div className="text-sm leading-5 font-medium">{tooltip}</div>
</div>
<div className="pointer-events-auto max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
{state.releaseNotes.map((releaseNote, index) => (
<div key={releaseNote.version}>
{index > 0 && <Separator className="my-3 bg-border/60" />}
<section>
<h3 className="text-muted-foreground text-xs leading-4 font-semibold">
{index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
</h3>
<ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
{releaseNote.items.map((item, itemIndex) => (
<li className="list-disc break-words" key={`${releaseNote.version}-${itemIndex}`}>
{item}
</li>
))}
</ul>
</section>
</div>
))}
</div>
</div>
);
}
export function SidebarUpdatePill() {
const state = useDesktopUpdateState();
const [dismissed, setDismissed] = useState(false);
@@ -191,21 +151,7 @@ export function SidebarUpdatePill() {
</button>
}
/>
<TooltipPopup
align="start"
className={
state?.channel === "nightly" && state.releaseNotes.length > 0
? "max-w-none text-balance"
: undefined
}
side="top"
>
{state ? (
<SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
) : (
tooltip
)}
</TooltipPopup>
<TooltipPopup side="top">{tooltip}</TooltipPopup>
</Tooltip>
{action === "download" && (
<Tooltip>
@@ -1,17 +0,0 @@
import { useEffect } from "react";
import { useUiStateStore } from "../uiStateStore";
export function useMarkActiveThreadVisited(
threadKey: string | null,
latestTurnCompletedAt: string | null,
): void {
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
useEffect(() => {
if (threadKey === null || latestTurnCompletedAt === null) {
return;
}
markThreadVisited(threadKey, latestTurnCompletedAt);
}, [latestTurnCompletedAt, markThreadVisited, threadKey]);
}
-1
View File
@@ -15,7 +15,6 @@ const baseState: DesktopUpdateState = {
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt: null,
message: null,
@@ -1,159 +0,0 @@
# Mobile app-store screenshot harness
The screenshot harness runs the real mobile application against three disposable local T3
environments. It creates an isolated base directory and server for each environment, real Git
projects with deterministic content, seeded orchestration projections, and persisted terminal
history. The app pairs with every server through its normal connection flow and React Navigation
opens the production Home, Thread, ThreadTerminal, ThreadReview, and SettingsEnvironments routes.
No screenshot-specific screen recreates application UI. `EXPO_PUBLIC_SHOWCASE=1` only enables the
non-rendering pairing/readiness coordinator, disables terminal autofocus so captures do not contain
the software keyboard, and supplies deterministic T3 Connect discovery rows to the real
Environments screen. The local environment cards always come from real paired servers.
## Capture the default matrix
From the repository root:
pnpm screenshots:mobile
The command:
1. Creates three temporary T3 base directories and starts a local server for each on an available
port.
2. Creates T3 Code, React, and Linux Git repositories with recognizable favicons, feature branches,
and a deterministic T3 Code review diff.
3. Seeds each server's migrated SQLite database with playful threads, messages, activities, and
terminal history, then adds two persisted mobile-outbox tasks waiting to send.
4. Starts an isolated Metro server, builds the selected native apps, and boots each device.
5. Pairs each clean app installation with Moonbase Terminal, Suspense Station, and Kernel Cabin.
6. Navigates to the real application route for every requested scene.
7. Sets the requested system appearance and normalizes status bars, converts captures to 24-bit RGB PNGs without alpha, and
validates dimensions, aspect ratio, file size, and screenshot count before succeeding.
8. Writes store-ready folders beneath `artifacts/app-store/screenshots/` that can be uploaded
directly to App Store Connect or Google Play Console.
The servers, Metro, temporary root directory, and devices started by the runner are cleaned up after
capture. Pass `--keep-running` to retain them for inspection; the runner prints the base-directory
paths and server ports.
Captures wait for the real environment snapshot to hydrate and for the requested route to become
active. Both platforms record readiness in the simulator/emulator app container. A final settle
delay allows native terminal and Git review data to finish rendering.
A full capture regenerates the selected native project with Expo's clean development prebuild before
building it. Use --skip-build for repeated captures after the first build.
The harness uses its own Metro port (8199 by default), so an ordinary mobile server or another
worktree cannot accidentally provide the bundle being photographed.
The default matrix is:
| Output folder | Capture target | Upload dimensions | Store slot |
| ------------------------------------- | ------------------------- | ----------------- | ----------------------------------------- |
| `apple/iphone-6.9/{light,dark}/` | iPhone 17 Pro Max | 1320×2868 | App Store Connect iPhone 6.9-inch |
| `apple/iphone-6.5/{light,dark}/` | disposable iPhone 14 Plus | 1284×2778 | App Store Connect iPhone 6.5-inch |
| `apple/ipad-13/{light,dark}/` | iPad Pro 13-inch (M5) | 2064×2752 | App Store Connect iPad 13-inch |
| `google-play/phone/{light,dark}/` | Pixel AVD at 420 dpi | 1080×1920 | Google Play phone, portrait 9:16 |
| `google-play/tablet-7/{light,dark}/` | Pixel AVD at 600dp width | 1080×1920 | Google Play 7-inch tablet, portrait 9:16 |
| `google-play/tablet-10/{light,dark}/` | Pixel AVD at 800dp width | 1440×2560 | Google Play 10-inch tablet, portrait 9:16 |
Each target captures thread, terminal, review, thread list, and environments, producing 30 PNG
files for one appearance or 60 for both. Each appearance folder's five screenshots satisfy the configured Apple limit of 1–10, Google
phone requirement of 2–8, and Google tablet recommendation/slot minimum of 4 with a maximum of 8.
The generated tree is deliberately aligned with the store upload fields:
artifacts/app-store/screenshots/
├── apple/
│ ├── iphone-6.9/{light,dark}/{thread,terminal,review,threads,environments}.png
│ ├── iphone-6.5/{light,dark}/{thread,terminal,review,threads,environments}.png
│ └── ipad-13/{light,dark}/{thread,terminal,review,threads,environments}.png
└── google-play/
├── phone/{light,dark}/{thread,terminal,review,threads,environments}.png
├── tablet-7/{light,dark}/{thread,terminal,review,threads,environments}.png
└── tablet-10/{light,dark}/{thread,terminal,review,threads,environments}.png
Edit [mobile-showcase.config.ts](../../scripts/mobile-showcase.config.ts) to change simulator or AVD
names, light/dark appearance, scenes, output directory, capture delay, Android ABI, or viewport.
## Capture in GitHub Actions
Run the `Mobile Showcase Screenshots` workflow from GitHub's Actions tab, choose `all`, `ios`, or
`android`, and select `light`, `dark`, or `both`. The default dispatch captures both appearances and
runs iOS and Android concurrently: iPhone and iPad capture on a
12-vCPU Blacksmith macOS runner, while Android phone, 7-inch tablet, and 10-inch tablet capture on a
16-vCPU Blacksmith Linux runner with a KVM-accelerated x86_64 emulator.
Every job uploads its PNGs even when a later capture fails, which makes partial runs useful for
diagnosis. Download `app-store-connect-screenshots` and `google-play-screenshots` from the workflow
run's Artifacts section. Each job runs validation again immediately before upload. Artifacts are
retained for 14 days.
The workflow uses the same checked-in device and scene matrix as local capture. Android remains
ARM64 by default for local Apple Silicon development; CI sets `T3_SHOWCASE_ANDROID_ABI=x86_64` so the
debug APK matches its accelerated emulator.
## Fast iteration
Capture one scene or device:
pnpm screenshots:mobile --device iphone-6.9 --scene thread
pnpm screenshots:mobile --platform android --scene review
Override the configured appearance or capture both variants:
pnpm screenshots:mobile --appearance light
pnpm screenshots:mobile --appearance dark
pnpm screenshots:mobile --appearance both
Reuse the native build and retain the disposable environment:
pnpm screenshots:mobile --device ipad-13 --skip-build --keep-running
Run Metro separately:
pnpm --filter @t3tools/mobile showcase
pnpm screenshots:mobile --skip-build --skip-metro --device iphone-6.9
List the matrix and flags:
pnpm screenshots:mobile --list
Validate existing files without starting Metro, servers, simulators, or emulators:
pnpm screenshots:mobile --validate-only
pnpm screenshots:mobile --platform ios --validate-only
## Customize the seeded environment
- Project repository, thread projections, conversation, terminal transcript, and Git changes:
[mobile-showcase-environment.ts](../../scripts/mobile-showcase-environment.ts)
- Device and capture matrix:
[mobile-showcase.config.ts](../../scripts/mobile-showcase.config.ts)
- Simulator/emulator orchestration:
[mobile-showcase.ts](../../scripts/mobile-showcase.ts)
Fixture timestamps are generated relative to capture startup so every route shows stable relative
labels while the server still receives valid current data. The same deterministic three-environment
ensemble serves iPhone, iPad, Android phone, and Android tablet captures; responsive differences
come entirely from the production app layout.
The Pending rows use the production offline outbox and point at the real T3 Code and React fixture
projects. Showcase coordination holds those two entries in the outbox for capture, just like a task
currently open for editing, so reconnecting the seeded environments cannot deliver and remove them
before the screenshot is taken.
The Environments capture presents the three local fixture transports as a Tailscale HTTPS hostname,
a Helsinki VPS hostname, and a Tailnet IPv4 address. This display-only substitution keeps the cards
remote-first while the harness retains reliable loopback connections to its ephemeral servers.
## Local prerequisites
- iOS: Xcode command-line tools, the configured simulator runtimes, and installed CocoaPods.
- Android: ANDROID_HOME (or the default macOS SDK path), adb, emulator, and the configured AVD.
The harness is the source of truth for upload dimensions; do not resize its output. If store rules
change, update the target's `storeAsset` specification. Capture fails when a PNG is the wrong size,
has alpha, is not 8-bit RGB, exceeds the configured file-size limit, violates Google Play's 9:16
shape/bounds, or leaves a full output set below its store minimum.
-1
View File
@@ -13,7 +13,6 @@
"start:desktop": "vp run --filter @t3tools/desktop start",
"start:marketing": "vp run --filter @t3tools/marketing preview",
"start:mock-update-server": "node scripts/mock-update-server.ts",
"screenshots:mobile": "node scripts/mobile-showcase.ts",
"build": "vp run --filter './apps/*' --filter './packages/*' --filter './oxlint-plugin-t3code' --filter './scripts' build",
"build:marketing": "vp run --filter @t3tools/marketing build",
"build:desktop": "vp run --filter @t3tools/desktop --filter t3 build",
-12
View File
@@ -213,7 +213,6 @@ export interface DesktopUpdateState {
runningUnderArm64Translation: boolean;
availableVersion: string | null;
downloadedVersion: string | null;
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote>;
downloadPercent: number | null;
checkedAt: string | null;
message: string | null;
@@ -221,16 +220,6 @@ export interface DesktopUpdateState {
canRetry: boolean;
}
export interface DesktopUpdateReleaseNote {
version: string;
items: ReadonlyArray<string>;
}
export const DesktopUpdateReleaseNoteSchema = Schema.Struct({
version: Schema.String,
items: Schema.Array(Schema.String),
});
export const DesktopUpdateStateSchema = Schema.Struct({
enabled: Schema.Boolean,
status: DesktopUpdateStatusSchema,
@@ -241,7 +230,6 @@ export const DesktopUpdateStateSchema = Schema.Struct({
runningUnderArm64Translation: Schema.Boolean,
availableVersion: Schema.NullOr(Schema.String),
downloadedVersion: Schema.NullOr(Schema.String),
releaseNotes: Schema.Array(DesktopUpdateReleaseNoteSchema),
downloadPercent: Schema.NullOr(Schema.Number),
checkedAt: Schema.NullOr(Schema.String),
message: Schema.NullOr(Schema.String),
+3 -3
View File
@@ -218,10 +218,10 @@ export const ClaudeSettings = makeProviderSettingsSchema(
homePath: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "CLAUDE_CONFIG_DIR path",
title: "Claude HOME path",
description:
"Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
"Custom HOME used when running this Claude instance. Keeps .claude.json and .claude separate.",
providerSettingsForm: { placeholder: "~", clearWhenEmpty: "omit" },
}),
),
customModels: Schema.Array(Schema.String).pipe(
+3 -20
View File
@@ -66,7 +66,7 @@ overrides:
vite: npm:@voidzero-dev/[email protected]
yaml: ^2.9.0
packageExtensionsChecksum: sha256-CUzzeefpj3gNFrCKNBhV9FOaniNbrLdKyIhWQyXuaiE=
packageExtensionsChecksum: sha256-FV3+2NW/9MFbunJaPsMxvO0LAzyfccoPtPiKoIXAwUU=
patchedDependencies:
'@effect/[email protected]': 42b87cc47e70d74e62496e7a8261b3fd298ecad4464d209348ab04b96f853a5f
@@ -193,7 +193,7 @@ importers:
version: 0.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@clerk/expo':
specifier: 3.7.2
version: 3.7.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
version: 3.7.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@effect/atom-react':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
@@ -902,9 +902,6 @@ importers:
effect:
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
pngjs:
specifier: 7.0.0
version: 7.0.0
yaml:
specifier: ^2.9.0
version: 2.9.0
@@ -912,9 +909,6 @@ importers:
'@effect/vitest':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=42b87cc47e70d74e62496e7a8261b3fd298ecad4464d209348ab04b96f853a5f)([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
'@types/pngjs':
specifier: 6.0.5
version: 6.0.5
vite-plus:
specifier: 'catalog:'
version: 0.2.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])
@@ -4904,9 +4898,6 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==}
'@types/[email protected]':
resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}
'@types/[email protected]':
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
peerDependencies:
@@ -11481,12 +11472,11 @@ snapshots:
electron-store: 8.2.0
react-dom: 19.2.6([email protected])
'@clerk/[email protected]([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':
'@clerk/[email protected]([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
dependencies:
'@clerk/clerk-js': 6.25.1([email protected]([email protected]))([email protected])
'@clerk/react': 6.12.1([email protected]([email protected]))([email protected])
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
'@expo/config-plugins': 56.0.9([email protected])
base-64: 1.0.0
expo: 56.0.12(8895228379997a2a064f9644cda56ed0)
react: 19.2.3
@@ -11500,9 +11490,6 @@ snapshots:
expo-secure-store: 56.0.4([email protected])
expo-web-browser: 56.0.5([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- supports-color
- typescript
'@clerk/[email protected]([email protected]([email protected]))([email protected])':
dependencies:
@@ -14938,10 +14925,6 @@ snapshots:
dependencies:
undici-types: 7.16.0
'@types/[email protected]':
dependencies:
'@types/node': 24.12.4
'@types/[email protected](@types/[email protected])':
dependencies:
'@types/react': 19.2.16
-3
View File
@@ -92,9 +92,6 @@ overrides:
yaml: "catalog:"
packageExtensions:
"@clerk/expo@*":
dependencies:
"@expo/config-plugins": 56.0.9
"@effect/vitest@*":
dependencies:
vite-plus: "catalog:"
-569
View File
@@ -1,569 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off globalDate:off - This host-side fixture creates an isolated local T3 environment.
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodeSqlite from "node:sqlite";
import * as NodeUtil from "node:util";
const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
export const SHOWCASE_PROJECT_ID = "t3code";
export const SHOWCASE_THREAD_ID = "remote-command-center";
export const SHOWCASE_TERMINAL_ID = "term-1";
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
const PROJECTOR_NAMES = [
"projection.projects",
"projection.threads",
"projection.thread-messages",
"projection.thread-proposed-plans",
"projection.thread-activities",
"projection.thread-sessions",
"projection.thread-turns",
"projection.checkpoints",
"projection.pending-approvals",
] as const;
const MODEL_SELECTION = JSON.stringify({ instanceId: "codex", model: "gpt-5.4" });
const PROJECT_SCRIPTS = JSON.stringify([
{
id: "dev",
name: "Dev",
command: "pnpm dev",
icon: "play",
runOnWorktreeCreate: false,
},
{
id: "test",
name: "Tests",
command: "pnpm test",
icon: "test",
runOnWorktreeCreate: false,
},
]);
export const SHOWCASE_TERMINAL_BUFFER = [
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
"$ vp test run --changed",
"",
" \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
" \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
" \u001b[38;5;221mserver\u001b[0m 165 passed",
"",
"\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
"",
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
].join("\r\n");
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
return \`${"${count}"} environments\`;
}
`;
const UPDATED_ENVIRONMENT_PRESENCE = `const PULSE = ["✦", "✧", "·", "✧"] as const;
export function environmentLabel(connected: number, total: number, frame: number): string {
const pulse = PULSE[frame % PULSE.length];
return \`${"${pulse} ${connected}/${total}"} ready\`;
}
`;
const REMOTE_HANDOFF_CARD = `import { View, Text } from "react-native";
export function RemoteHandoffCard(props: { machine: string; latencyMs: number }) {
return (
<View className="rounded-2xl bg-surface-2 p-4">
<Text className="font-semibold">Ready on {props.machine}</Text>
<Text className="text-success">Handoff in {props.latencyMs}ms</Text>
</View>
);
}
`;
const PROJECT_FAVICONS = {
t3code: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<rect width="128" height="128" rx="10" fill="#000"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="#fff"/>
</svg>`,
react: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="15" fill="#20232a"/>
<g fill="none" stroke="#61dafb" stroke-width="2.8"><ellipse cx="32" cy="32" rx="25" ry="9"/><ellipse cx="32" cy="32" rx="25" ry="9" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="25" ry="9" transform="rotate(120 32 32)"/></g>
<circle cx="32" cy="32" r="4.8" fill="#61dafb"/>
</svg>`,
linux: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="15" fill="#f7c948"/>
<ellipse cx="32" cy="35" rx="17" ry="22" fill="#202124"/>
<ellipse cx="32" cy="40" rx="12" ry="14" fill="#f5f5f2"/>
<circle cx="27" cy="24" r="5" fill="white"/><circle cx="37" cy="24" r="5" fill="white"/>
<circle cx="28" cy="25" r="2"/><circle cx="36" cy="25" r="2"/>
<path d="M27 31l5-4 5 4-5 4z" fill="#f28c28"/><path d="M16 55h14l-7-5zM34 55h14l-7-5z" fill="#f28c28"/>
</svg>`,
} as const;
export const SHOWCASE_PROJECTS = [
{
id: "t3code",
title: "T3 Code",
directory: "t3code",
repositoryUrl: "https://github.com/pingdotgg/t3code.git",
favicon: PROJECT_FAVICONS.t3code,
},
{
id: "react",
title: "React",
directory: "react",
repositoryUrl: "https://github.com/facebook/react.git",
favicon: PROJECT_FAVICONS.react,
},
{
id: "linux",
title: "Linux",
directory: "linux",
repositoryUrl: "https://github.com/torvalds/linux.git",
favicon: PROJECT_FAVICONS.linux,
},
] as const;
export const SHOWCASE_ENVIRONMENTS = [
{
id: "moonbase-terminal",
label: "Moonbase Terminal",
projectIds: ["t3code"],
},
{
id: "suspense-station",
label: "Suspense Station",
projectIds: ["react"],
},
{
id: "kernel-cabin",
label: "Kernel Cabin",
projectIds: ["linux"],
},
] as const;
export const SHOWCASE_THREADS = [
{
id: SHOWCASE_THREAD_ID,
projectId: "t3code",
title: "Make remote coding feel local ✦",
branch: "feat/remote-command-center",
minutesAgo: 3,
request:
"Give T3 Code a remote-first command center. Make three machines feel one tap away, keep agent work in sync, and make every handoff feel instant.",
response:
"T3 Code now treats every machine like it is right here in the room. ✦\n\n- Moonbase, Suspense Station, and Kernel Cabin stay live together\n- Terminal state follows you without losing a single line\n- Agent work remains perfectly in sync across devices\n- Handoffs land before your train of thought can wander\n\nI also ran the changed workspace: **612 tests passed**.",
},
{
id: "pocket-command-center",
projectId: "t3code",
title: "Put the command center in your pocket",
branch: "feat/pocket-command-center",
minutesAgo: 21,
state: "approval" as const,
request: "Make switching between desktop, phone, and tablet feel like one continuous session.",
response:
"The handoff flow preserves the selected thread, terminal buffer, and working diff. The final motion treatment is ready for approval.",
},
{
id: "buttery-suspense",
projectId: "react",
title: "Make Suspense transitions buttery",
branch: "perf/buttery-suspense",
minutesAgo: 12,
state: "working" as const,
request:
"Trace the last few dropped frames in nested Suspense transitions and make them disappear.",
response: null,
},
{
id: "hydration-haikus",
projectId: "react",
title: "Turn hydration warnings into haikus",
branch: "dev/hydration-haikus",
minutesAgo: 44,
request:
"Keep hydration errors precise, but make the development copy unexpectedly delightful.",
response:
"The diagnostics still lead with the exact mismatch and component stack. A tiny optional haiku now closes the expanded explanation.",
},
{
id: "beautiful-boot",
projectId: "linux",
title: "Make boot logs oddly beautiful",
branch: "feat/beautiful-boot",
minutesAgo: 34,
state: "plan" as const,
request:
"Design a clearer boot timeline that remains useful over serial and never hides kernel detail.",
response:
"The plan groups milestones without changing the underlying log stream, preserves plain-text output, and adds zero work to the hot path.",
},
{
id: "scheduler-breathe",
projectId: "linux",
title: "Let the scheduler breathe",
branch: "perf/scheduler-breathe",
minutesAgo: 76,
request:
"Find a calmer balancing strategy for bursty mixed workloads without hurting tail latency.",
response:
"The new heuristic reduces needless migrations during short bursts while preserving the existing latency guardrails.",
},
] as const;
function minutesBefore(now: number, minutes: number): string {
return new Date(now - minutes * 60_000).toISOString();
}
async function runGit(workspaceRoot: string, args: ReadonlyArray<string>): Promise<void> {
await execFile("git", [...args], {
cwd: workspaceRoot,
env: {
...process.env,
GIT_AUTHOR_NAME: "Alex Rivera",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "Alex Rivera",
GIT_COMMITTER_EMAIL: "[email protected]",
},
});
}
async function initializeRepository(input: {
readonly workspaceRoot: string;
readonly repositoryUrl: string;
readonly commitMessage: string;
}): Promise<void> {
await runGit(input.workspaceRoot, ["init", "-b", "main"]);
await runGit(input.workspaceRoot, ["remote", "add", "origin", input.repositoryUrl]);
await runGit(input.workspaceRoot, ["add", "."]);
await runGit(input.workspaceRoot, ["commit", "-m", input.commitMessage]);
}
async function seedT3CodeWorkspace(workspaceRoot: string): Promise<void> {
await NodeFSP.mkdir(NodePath.join(workspaceRoot, "apps/mobile/src/features/home"), {
recursive: true,
});
await NodeFSP.writeFile(
NodePath.join(workspaceRoot, "package.json"),
`${JSON.stringify({ name: "t3code", private: true, scripts: { test: "vp test" } }, null, 2)}\n`,
);
await NodeFSP.writeFile(NodePath.join(workspaceRoot, "favicon.svg"), PROJECT_FAVICONS.t3code);
await NodeFSP.writeFile(
NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
BASE_ENVIRONMENT_PRESENCE,
);
await initializeRepository({
workspaceRoot,
repositoryUrl: "https://github.com/pingdotgg/t3code.git",
commitMessage: "Show connected environments",
});
await runGit(workspaceRoot, ["checkout", "-b", "feat/remote-command-center"]);
await NodeFSP.writeFile(
NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
UPDATED_ENVIRONMENT_PRESENCE,
);
await NodeFSP.writeFile(
NodePath.join(workspaceRoot, "apps/mobile/src/features/home/RemoteHandoffCard.tsx"),
REMOTE_HANDOFF_CARD,
);
}
async function seedCompanionWorkspace(input: {
readonly workspaceRoot: string;
readonly title: string;
readonly repositoryUrl: string;
readonly favicon: string;
}): Promise<void> {
await NodeFSP.mkdir(input.workspaceRoot, { recursive: true });
await NodeFSP.writeFile(NodePath.join(input.workspaceRoot, "favicon.svg"), input.favicon);
await NodeFSP.writeFile(
NodePath.join(input.workspaceRoot, "README.md"),
`# ${input.title}\n\nSeeded by the T3 Code mobile screenshot harness.\n`,
);
await initializeRepository({
workspaceRoot: input.workspaceRoot,
repositoryUrl: input.repositoryUrl,
commitMessage: `Seed ${input.title} workspace`,
});
}
function insertThread(
database: NodeSqlite.DatabaseSync,
now: number,
input: {
readonly id: string;
readonly projectId: string;
readonly title: string;
readonly branch: string;
readonly minutesAgo: number;
readonly state?: "working" | "approval" | "plan";
readonly workspaceRoot: string;
},
): void {
const turnId = `${input.id}-turn`;
const updatedAt = minutesBefore(now, input.minutesAgo);
const isWorking = input.state === "working";
database
.prepare(
`INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
branch, worktree_path, latest_turn_id, latest_user_message_at, pending_approval_count,
pending_user_input_count, has_actionable_proposed_plan, created_at, updated_at,
archived_at, deleted_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, NULL, NULL)`,
)
.run(
input.id,
input.projectId,
input.title,
MODEL_SELECTION,
"full-access",
input.state === "plan" ? "plan" : "default",
input.branch,
input.workspaceRoot,
turnId,
minutesBefore(now, input.minutesAgo + 1),
input.state === "approval" ? 1 : 0,
input.state === "plan" ? 1 : 0,
minutesBefore(now, input.minutesAgo + 120),
updatedAt,
);
database
.prepare(
`INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, assistant_message_id, state, requested_at,
started_at, completed_at, checkpoint_turn_count, checkpoint_ref, checkpoint_status,
checkpoint_files_json, source_proposed_plan_thread_id, source_proposed_plan_id
) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, NULL, NULL, NULL, '[]', NULL, NULL)`,
)
.run(
input.id,
turnId,
isWorking ? null : `${input.id}-answer`,
isWorking ? "running" : "completed",
minutesBefore(now, input.minutesAgo + 2),
minutesBefore(now, input.minutesAgo + 2),
isWorking ? null : updatedAt,
);
database
.prepare(
`INSERT INTO projection_thread_sessions (
thread_id, status, provider_name, provider_instance_id, provider_session_id,
provider_thread_id, runtime_mode, active_turn_id, last_error, updated_at
) VALUES (?, ?, 'Codex', 'codex', NULL, NULL, 'full-access', ?, NULL, ?)`,
)
.run(input.id, isWorking ? "running" : "ready", isWorking ? turnId : null, updatedAt);
}
function seedDatabase(
dbPath: string,
workspaceRoots: ReadonlyMap<string, string>,
projects: ReadonlyArray<(typeof SHOWCASE_PROJECTS)[number]>,
threads: ReadonlyArray<(typeof SHOWCASE_THREADS)[number]>,
now: number,
): void {
const database = new NodeSqlite.DatabaseSync(dbPath);
try {
database.exec("BEGIN IMMEDIATE");
for (const table of [
"projection_pending_approvals",
"projection_thread_proposed_plans",
"projection_thread_activities",
"projection_thread_messages",
"projection_thread_sessions",
"projection_turns",
"projection_threads",
"projection_projects",
"projection_state",
]) {
database.exec(`DELETE FROM ${table}`);
}
const insertProject = database.prepare(
`INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json, scripts_json,
created_at, updated_at, deleted_at
) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
);
for (const [index, project] of projects.entries()) {
const workspaceRoot = workspaceRoots.get(project.id);
if (!workspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
const latestThreadMinutes = Math.min(
...threads
.filter((thread) => thread.projectId === project.id)
.map((thread) => thread.minutesAgo),
);
insertProject.run(
project.id,
project.title,
workspaceRoot,
MODEL_SELECTION,
PROJECT_SCRIPTS,
minutesBefore(now, 60 * 24 * (90 - index * 12)),
minutesBefore(now, latestThreadMinutes),
);
}
for (const thread of threads) {
const workspaceRoot = workspaceRoots.get(thread.projectId);
if (!workspaceRoot) throw new Error(`Missing workspace root for ${thread.projectId}.`);
insertThread(database, now, {
...thread,
...("state" in thread ? { state: thread.state } : {}),
workspaceRoot,
});
}
const insertMessage = database.prepare(
`INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, attachments_json,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, 0, NULL, ?, ?)`,
);
for (const thread of threads) {
const turnId = `${thread.id}-turn`;
const requestTime = minutesBefore(now, thread.minutesAgo + 5);
insertMessage.run(
`${thread.id}-request`,
thread.id,
turnId,
"user",
thread.request,
requestTime,
requestTime,
);
if (thread.response !== null) {
const responseTime = minutesBefore(now, thread.minutesAgo);
insertMessage.run(
`${thread.id}-answer`,
thread.id,
turnId,
"assistant",
thread.response,
responseTime,
responseTime,
);
}
}
const turnId = `${SHOWCASE_THREAD_ID}-turn`;
const insertActivity = database.prepare(
`INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
) VALUES (?, ?, ?, 'tool', 'tool.completed', ?, ?, ?, ?)`,
);
insertActivity.run(
"trace-remote-handoff",
SHOWCASE_THREAD_ID,
turnId,
"Traced the remote handoff path",
JSON.stringify({
itemType: "command_execution",
title: "Traced the remote handoff path",
detail: "Three environments, one continuous workspace",
status: "completed",
}),
1,
minutesBefore(now, 8),
);
insertActivity.run(
"sync-command-center",
SHOWCASE_THREAD_ID,
turnId,
"Synced the command center",
JSON.stringify({
itemType: "file_change",
title: "Synced the command center",
detail: "2 files changed · instant handoffs · calm reconnects",
status: "completed",
}),
2,
minutesBefore(now, 6),
);
insertActivity.run(
"run-changed-suite",
SHOWCASE_THREAD_ID,
turnId,
"Ran the changed workspace",
JSON.stringify({
itemType: "command_execution",
title: "Ran the changed workspace",
detail: "612 tests passed · 3 environments online",
status: "completed",
}),
3,
minutesBefore(now, 4),
);
for (const [index, projector] of PROJECTOR_NAMES.entries()) {
database
.prepare(
"INSERT INTO projection_state (projector, last_applied_sequence, updated_at) VALUES (?, ?, ?)",
)
.run(projector, index + 1, minutesBefore(now, 1));
}
database.exec("COMMIT");
} catch (error) {
database.exec("ROLLBACK");
throw error;
} finally {
database.close();
}
}
export async function seedShowcaseEnvironment(input: {
readonly baseDir: string;
readonly projectIds?: ReadonlyArray<string>;
readonly now?: number;
}): Promise<{ readonly dbPath: string; readonly workspaceRoot: string }> {
const now = input.now ?? Date.now();
const selectedProjectIds = new Set(
input.projectIds ?? SHOWCASE_PROJECTS.map((project) => project.id),
);
const projects = SHOWCASE_PROJECTS.filter((project) => selectedProjectIds.has(project.id));
if (projects.length === 0) throw new Error("At least one showcase project must be selected.");
const threads = SHOWCASE_THREADS.filter((thread) => selectedProjectIds.has(thread.projectId));
const workspaceBase = NodePath.join(input.baseDir, "workspace");
const workspaceRoots = new Map(
projects.map(
(project) => [project.id, NodePath.join(workspaceBase, project.directory)] as const,
),
);
const primaryProject =
projects.find((project) => project.id === SHOWCASE_PROJECT_ID) ?? projects[0];
if (!primaryProject) throw new Error("The primary showcase workspace is not configured.");
const workspaceRoot = workspaceRoots.get(primaryProject.id);
if (!workspaceRoot) throw new Error("The primary showcase workspace is not configured.");
const dbPath = NodePath.join(input.baseDir, "userdata", "state.sqlite");
if (primaryProject.id === SHOWCASE_PROJECT_ID) {
await seedT3CodeWorkspace(workspaceRoot);
}
await Promise.all(
projects
.filter((project) => project.id !== SHOWCASE_PROJECT_ID)
.map(async (project) => {
const projectWorkspaceRoot = workspaceRoots.get(project.id);
if (!projectWorkspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
await seedCompanionWorkspace({
workspaceRoot: projectWorkspaceRoot,
title: project.title,
repositoryUrl: project.repositoryUrl,
favicon: project.favicon,
});
}),
);
seedDatabase(dbPath, workspaceRoots, projects, threads, now);
const terminalDirectory = NodePath.join(input.baseDir, "userdata", "logs", "terminals");
if (selectedProjectIds.has(SHOWCASE_PROJECT_ID)) {
const safeThreadId = Buffer.from(SHOWCASE_THREAD_ID).toString("base64url");
await NodeFSP.mkdir(terminalDirectory, { recursive: true });
await NodeFSP.writeFile(
NodePath.join(terminalDirectory, `terminal_${safeThreadId}.log`),
SHOWCASE_TERMINAL_BUFFER,
);
}
return { dbPath, workspaceRoot };
}
-206
View File
@@ -1,206 +0,0 @@
import { SHOWCASE_SCENES, type ShowcaseScene } from "./mobile-showcase-environment.ts";
export { SHOWCASE_SCENES };
export type { ShowcaseScene };
export type ShowcaseAppearance = "light" | "dark";
export interface ShowcaseStoreAssetSpec {
readonly store: "apple" | "google-play";
/** Device directory relative to ShowcaseConfig.outputDirectory. */
readonly directory: string;
readonly width: number;
readonly height: number;
readonly minimumUploadCount: number;
readonly maximumUploadCount: number;
readonly maximumFileSizeBytes?: number;
}
export interface ShowcaseIosDevice {
readonly id: string;
readonly platform: "ios";
/** Exact name from `xcrun simctl list devices available`. */
readonly simulator: string;
/** Device type used to create a disposable simulator when the named one is absent. */
readonly simulatorDeviceType?: string;
/** Appearance used when the CLI does not pass --appearance. */
readonly appearance: ShowcaseAppearance;
readonly scenes: ReadonlyArray<ShowcaseScene>;
readonly storeAsset: ShowcaseStoreAssetSpec;
}
export interface ShowcaseAndroidDevice {
readonly id: string;
readonly platform: "android";
/** Exact name from `emulator -list-avds`. */
readonly avd: string;
/** Appearance used when the CLI does not pass --appearance. */
readonly appearance: ShowcaseAppearance;
/** Native ABI used by the AVD, from its config.ini `abi.type`. */
readonly abi?: "arm64-v8a" | "x86_64" | "x86" | "armeabi-v7a";
readonly scenes: ReadonlyArray<ShowcaseScene>;
/** Optional capture viewport. Omit to use the AVD's native size and density. */
readonly viewport?: {
readonly width: number;
readonly height: number;
readonly density?: number;
};
readonly storeAsset: ShowcaseStoreAssetSpec;
}
export type ShowcaseDevice = ShowcaseIosDevice | ShowcaseAndroidDevice;
export interface ShowcaseConfig {
readonly outputDirectory: string;
readonly metroPort: number;
readonly settleDelayMs: number;
readonly devices: ReadonlyArray<ShowcaseDevice>;
}
const ANDROID_ABIS = ["arm64-v8a", "x86_64", "x86", "armeabi-v7a"] as const;
export function resolveShowcaseAndroidAbi(
value: string | undefined,
): NonNullable<ShowcaseAndroidDevice["abi"]> {
if (!value) return "arm64-v8a";
if (ANDROID_ABIS.some((abi) => abi === value)) {
return value as NonNullable<ShowcaseAndroidDevice["abi"]>;
}
throw new Error(
`Unsupported T3_SHOWCASE_ANDROID_ABI '${value}'. Use ${ANDROID_ABIS.join(", ")}.`,
);
}
/**
* The defaults cover every App Store Connect and Google Play upload slot used
* by the mobile app. Edit this matrix (or pass --device / --scene) without
* changing the runner. Every target declares and validates its exact upload
* dimensions so SDK or emulator changes cannot silently produce invalid files.
*/
const config: ShowcaseConfig = {
outputDirectory: "artifacts/app-store/screenshots",
// Dedicated port so the harness cannot attach to a normal mobile dev server
// (or a second worktree) and capture the wrong bundle.
metroPort: 8199,
settleDelayMs: 2_500,
devices: [
{
id: "iphone-6.9",
platform: "ios",
simulator: "iPhone 17 Pro Max",
simulatorDeviceType: "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro-Max",
appearance: "dark",
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "apple",
directory: "apple/iphone-6.9",
width: 1320,
height: 2868,
minimumUploadCount: 1,
maximumUploadCount: 10,
},
},
{
id: "iphone-6.5",
platform: "ios",
simulator: "T3 Showcase iPhone 14 Plus",
simulatorDeviceType: "com.apple.CoreSimulator.SimDeviceType.iPhone-14-Plus",
appearance: "dark",
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "apple",
directory: "apple/iphone-6.5",
width: 1284,
height: 2778,
minimumUploadCount: 1,
maximumUploadCount: 10,
},
},
{
id: "ipad-13",
platform: "ios",
simulator: "iPad Pro 13-inch (M5)",
simulatorDeviceType: "com.apple.CoreSimulator.SimDeviceType.iPad-Pro-13-inch-M5-16GB",
appearance: "dark",
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "apple",
directory: "apple/ipad-13",
width: 2064,
height: 2752,
minimumUploadCount: 1,
maximumUploadCount: 10,
},
},
{
id: "pixel",
platform: "android",
avd: "Pixel_10_Pro",
// Apple Silicon uses ARM64 locally; CI overrides this with x86_64 so its
// Blacksmith Linux runner can use KVM acceleration.
abi: resolveShowcaseAndroidAbi(process.env.T3_SHOWCASE_ANDROID_ABI),
appearance: "dark",
viewport: {
width: 1080,
height: 1920,
density: 420,
},
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "google-play",
directory: "google-play/phone",
width: 1080,
height: 1920,
minimumUploadCount: 2,
maximumUploadCount: 8,
maximumFileSizeBytes: 8 * 1024 * 1024,
},
},
{
id: "android-tablet-7",
platform: "android",
avd: "Pixel_10_Pro",
abi: resolveShowcaseAndroidAbi(process.env.T3_SHOWCASE_ANDROID_ABI),
appearance: "dark",
viewport: {
width: 1080,
height: 1920,
density: 288,
},
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "google-play",
directory: "google-play/tablet-7",
width: 1080,
height: 1920,
minimumUploadCount: 4,
maximumUploadCount: 8,
maximumFileSizeBytes: 8 * 1024 * 1024,
},
},
{
id: "android-tablet-10",
platform: "android",
avd: "Pixel_10_Pro",
abi: resolveShowcaseAndroidAbi(process.env.T3_SHOWCASE_ANDROID_ABI),
appearance: "dark",
viewport: {
width: 1440,
height: 2560,
density: 288,
},
scenes: ["thread", "terminal", "review", "threads", "environments"],
storeAsset: {
store: "google-play",
directory: "google-play/tablet-10",
width: 1440,
height: 2560,
minimumUploadCount: 4,
maximumUploadCount: 8,
maximumFileSizeBytes: 8 * 1024 * 1024,
},
},
],
};
export default config;
-296
View File
@@ -1,296 +0,0 @@
import { assert, it } from "@effect/vitest";
import { PNG } from "pngjs";
import showcaseConfig, {
resolveShowcaseAndroidAbi,
type ShowcaseConfig,
type ShowcaseStoreAssetSpec,
} from "./mobile-showcase.config.ts";
import {
SHOWCASE_ENVIRONMENTS,
SHOWCASE_PROJECTS,
SHOWCASE_THREADS,
} from "./mobile-showcase-environment.ts";
import {
encodeAndroidPairingUrls,
normalizeStorePng,
parseShowcaseCliArgs,
parsePairingCredentialOutput,
planShowcaseCaptures,
readPngDimensions,
readPngMetadata,
resolveAndroidSdkRoot,
selectLanIpv4Address,
showcaseCaptureDirectory,
showcaseSceneUrl,
validateStoreAsset,
validateStoreAssetCount,
} from "./mobile-showcase.ts";
const appleSpec: ShowcaseStoreAssetSpec = {
store: "apple",
directory: "apple/iphone-test",
width: 1284,
height: 2778,
minimumUploadCount: 1,
maximumUploadCount: 10,
};
const googleSpec: ShowcaseStoreAssetSpec = {
store: "google-play",
directory: "google-play/phone",
width: 1080,
height: 1920,
minimumUploadCount: 2,
maximumUploadCount: 8,
maximumFileSizeBytes: 8 * 1024 * 1024,
};
const config: ShowcaseConfig = {
outputDirectory: "artifacts",
metroPort: 8199,
settleDelayMs: 1,
devices: [
{
id: "phone",
platform: "ios",
simulator: "iPhone Test",
appearance: "dark",
scenes: ["thread", "review"],
storeAsset: appleSpec,
},
{
id: "pixel",
platform: "android",
avd: "Pixel_Test",
appearance: "light",
scenes: ["thread", "terminal"],
storeAsset: googleSpec,
},
],
};
it("parses repeatable capture filters", () => {
const options = parseShowcaseCliArgs([
"--platform",
"ios",
"--device",
"phone",
"--scene",
"review",
"--appearance",
"both",
"--skip-build",
]);
assert.deepStrictEqual([...options.platforms], ["ios"]);
assert.deepStrictEqual([...options.deviceIds], ["phone"]);
assert.deepStrictEqual([...options.scenes], ["review"]);
assert.deepStrictEqual([...options.appearances], ["light", "dark"]);
assert.equal(options.skipBuild, true);
});
it("rejects unsupported system appearances", () => {
assert.throws(
() => parseShowcaseCliArgs(["--appearance", "sepia"]),
/Unsupported appearance 'sepia'/u,
);
});
it("parses validation-only mode", () => {
assert.equal(parseShowcaseCliArgs(["--validate-only"]).validateOnly, true);
});
it("selects an explicit CI Android ABI without changing the local default", () => {
assert.equal(resolveShowcaseAndroidAbi(undefined), "arm64-v8a");
assert.equal(resolveShowcaseAndroidAbi("x86_64"), "x86_64");
assert.throws(() => resolveShowcaseAndroidAbi("mips"), /Unsupported T3_SHOWCASE_ANDROID_ABI/u);
});
it("uses platform-correct default Android SDK roots", () => {
assert.equal(
resolveAndroidSdkRoot({ HOME: "/Users/showcase" }, "darwin"),
"/Users/showcase/Library/Android/sdk",
);
assert.equal(
resolveAndroidSdkRoot({ HOME: "/home/showcase" }, "linux"),
"/home/showcase/Android/Sdk",
);
assert.equal(
resolveAndroidSdkRoot(
{ HOME: "/home/showcase", ANDROID_SDK_ROOT: "/opt/android-sdk" },
"linux",
),
"/opt/android-sdk",
);
});
it("plans only scenes supported by each selected device", () => {
const options = parseShowcaseCliArgs(["--platform", "all", "--scene", "terminal"]);
const captures = planShowcaseCaptures(config, options);
assert.deepStrictEqual(
captures.map((capture) => ({
id: capture.device.id,
appearance: capture.appearance,
scenes: capture.scenes,
})),
[{ id: "pixel", appearance: "light", scenes: ["terminal"] }],
);
});
it("expands both appearances into independent upload-ready directories", () => {
const options = parseShowcaseCliArgs(["--device", "phone", "--appearance", "both"]);
const captures = planShowcaseCaptures(config, options);
assert.deepStrictEqual(
captures.map((capture) => ({
appearance: capture.appearance,
directory: showcaseCaptureDirectory("/captures", capture),
})),
[
{ appearance: "light", directory: "/captures/apple/iphone-test/light" },
{ appearance: "dark", directory: "/captures/apple/iphone-test/dark" },
],
);
});
it("rejects unknown devices instead of silently capturing another target", () => {
const options = parseShowcaseCliArgs(["--device", "missing"]);
assert.throws(() => planShowcaseCaptures(config, options), /Unknown device 'missing'/u);
});
it("reads captured PNG dimensions from the IHDR header", () => {
const bytes = new Uint8Array(26);
bytes.set([137, 80, 78, 71, 13, 10, 26, 10]);
const view = new DataView(bytes.buffer);
view.setUint32(16, 1320);
view.setUint32(20, 2868);
view.setUint8(24, 8);
view.setUint8(25, 2);
assert.deepStrictEqual(readPngDimensions(bytes), { width: 1320, height: 2868 });
assert.deepStrictEqual(readPngMetadata(bytes), {
width: 1320,
height: 2868,
bitDepth: 8,
colorType: 2,
hasAlpha: false,
});
});
function rgbaPng(width: number, height: number): Buffer {
const png = new PNG({ width, height });
png.data.fill(255);
return PNG.sync.write(png);
}
it("converts simulator RGBA captures to upload-safe 24-bit RGB PNGs", () => {
const normalized = normalizeStorePng(rgbaPng(2, 3));
assert.deepStrictEqual(readPngMetadata(normalized), {
width: 2,
height: 3,
bitDepth: 8,
colorType: 2,
hasAlpha: false,
});
});
it("validates exact Apple and Google Play upload assets", () => {
const apple = normalizeStorePng(rgbaPng(appleSpec.width, appleSpec.height));
const google = normalizeStorePng(rgbaPng(googleSpec.width, googleSpec.height));
assert.equal(validateStoreAsset(appleSpec, apple).width, 1284);
assert.equal(validateStoreAsset(googleSpec, google).height, 1920);
});
it("rejects wrong dimensions and alpha-bearing PNGs", () => {
const wrongSize = normalizeStorePng(rgbaPng(1242, 2688));
assert.throws(() => validateStoreAsset(appleSpec, wrongSize), /requires 1284×2778/u);
assert.throws(() => validateStoreAsset(appleSpec, rgbaPng(1284, 2778)), /without alpha/u);
});
it("enforces store screenshot count limits", () => {
assert.doesNotThrow(() => validateStoreAssetCount(googleSpec, 5, true));
assert.throws(() => validateStoreAssetCount(googleSpec, 1, true), /requires at least 2/u);
assert.throws(() => validateStoreAssetCount(googleSpec, 9, false), /allows at most 8/u);
});
it("configures every default device with an exact upload-ready store target", () => {
assert.deepStrictEqual(
showcaseConfig.devices.map((device) => [
device.id,
device.storeAsset.directory,
device.storeAsset.width,
device.storeAsset.height,
]),
[
["iphone-6.9", "apple/iphone-6.9", 1320, 2868],
["iphone-6.5", "apple/iphone-6.5", 1284, 2778],
["ipad-13", "apple/ipad-13", 2064, 2752],
["pixel", "google-play/phone", 1080, 1920],
["android-tablet-7", "google-play/tablet-7", 1080, 1920],
["android-tablet-10", "google-play/tablet-10", 1440, 2560],
],
);
});
it("selects a reachable LAN IPv4 address", () => {
assert.equal(
selectLanIpv4Address([
{ address: "127.0.0.1", family: "IPv4", internal: true },
{ address: "fe80::1", family: "IPv6", internal: false },
{ address: "169.254.2.4", family: "IPv4", internal: false },
{ address: "192.168.1.80", family: "IPv4", internal: false },
]),
"192.168.1.80",
);
});
it("maps capture scenes to the real application routes", () => {
assert.equal(showcaseSceneUrl("threads", "environment-1"), "t3code-dev://");
assert.equal(
showcaseSceneUrl("environments", "environment-1"),
"t3code-dev://settings/environments",
);
assert.equal(
showcaseSceneUrl("thread", "environment-1"),
"t3code-dev://threads/environment-1/remote-command-center",
);
assert.equal(
showcaseSceneUrl("terminal", "environment-1"),
"t3code-dev://threads/environment-1/remote-command-center/terminal?terminalId=term-1",
);
assert.equal(
showcaseSceneUrl("review", "environment-1"),
"t3code-dev://threads/environment-1/remote-command-center/review",
);
});
it("seeds a playful multi-environment project spectrum", () => {
assert.deepStrictEqual(
SHOWCASE_PROJECTS.map((project) => project.title),
["T3 Code", "React", "Linux"],
);
assert.deepStrictEqual(
SHOWCASE_ENVIRONMENTS.map((environment) => environment.label),
["Moonbase Terminal", "Suspense Station", "Kernel Cabin"],
);
assert.equal(SHOWCASE_THREADS.length, 6);
assert.equal(new Set(SHOWCASE_THREADS.map((thread) => thread.projectId)).size, 3);
assert.equal(
SHOWCASE_PROJECTS.every((project) => project.favicon.includes("<svg")),
true,
);
});
it("reads multiline JSON from the pairing CLI", () => {
assert.equal(
parsePairingCredentialOutput('server log\n{\n "credential": "PAIR-ME"\n}\n'),
"PAIR-ME",
);
});
it("encodes Android pairing URLs without shell-sensitive JSON quotes", () => {
const urls = ["http://10.0.2.2:65164/#token=ONE", "http://10.0.2.2:65198/#token=TWO"];
const encoded = encodeAndroidPairingUrls(urls);
assert.equal(encoded.startsWith("json-uri:"), true);
assert.deepStrictEqual(JSON.parse(decodeURIComponent(encoded.slice("json-uri:".length))), urls);
assert.equal(encoded.includes('"'), false);
});
File diff suppressed because it is too large. Load diff
-2
View File
@@ -11,12 +11,10 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:",
"pngjs": "7.0.0",
"yaml": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/pngjs": "6.0.5",
"vite-plus": "catalog:"
}
}