@devries-cameron20 / t3code Mirror · read-only / commits / 5f1f604733
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

feat(mobile): on-demand chrome e2e runner across simulators

`vp run mobile:e2e [--device <id>] [--concurrency <n>]` boots dedicated simulators, installs the cached dev client, starts a fixture server and Metro, pairs automatically, then runs home -> open thread -> back. Each step records video and checks the settled chrome (tab bar, back button, composer) from accessibility snapshots, and compares video frames to the settled screenshots to catch chrome that lags a transition, such as the workspace tabs drawn over an entering thread (#24666). Results land in artifacts/mobile-e2e/<run>/index.html with screenshots, videos, frame sheets and the first offending frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 14:49 UTC 5f1f604733c65b50ad6d289971103b1330e943bf
65 files changed +940 -1716
.github/workflows/web-preview.yml
+1 -2
@@ -82,8 +82,7 @@ jobs:
82 --archive=tgz \
83 --yes \
84 --token "$VERCEL_TOKEN" \
85 - --scope "$vercel_scope" \
86 - --build-env "VITE_RELEASE_CHANNEL=preview"
85 + --scope "$vercel_scope"
86 )"
87 printf '%s\n' "$deployment_output"
88 # Vercel can print lockfile warnings to stdout before the deployment URL.
.gitignore
+1
@@ -36,6 +36,7 @@ apps/mobile/.generated/
36 apps/mobile/.android-cache/
37 /.generated/
38 artifacts/app-store/screenshots/
39 +artifacts/mobile-e2e/
40 .github/pr-assets/
41 native/**/target/
42 node_modules/
AGENTS.md
-1
@@ -194,7 +194,6 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/
194 options, and pass combinators as additional function-builder arguments.
195 - Inferred types over annotations. `any` is the enemy.
196 - Default to no comment. Write one only for a constraint, an external quirk, or an invariant the code can't show, in one line where you can and four at most. Don't restate names or signatures, narrate steps, record history, or explain the fix you just made; the PR carries that. `t3code/no-low-value-comments` enforces the length cap and the mechanical cases.
197 -- React effects are a last resort: derive in render, act in handlers, reset with `key`, or use a ref callback or store. The `t3code/react-effect-budget` lint rule holds each file to its entry in `scripts/effect-budget.json`; raise an entry only in the PR that needs the effect, and lower it when you remove one.
197 - Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
198 - If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
199
apps/desktop/src/app/DesktopObservability.ts
+2 -12
@@ -2,13 +2,11 @@ import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
2 import {
3 makeLocalFileTracer,
4 makeTraceSink,
5 - processServiceInstanceId,
5 type SignalExport,
6 } from "@t3tools/shared/observability";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as SharedObservability from "@t3tools/shared/observability";
9 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
11 -import { releaseChannelOf, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
10 import {
11 parsePersistedServerObservabilitySettings,
12 type PersistedServerObservabilitySettings,
@@ -597,22 +595,14 @@ const layerTelemetry = Layer.unwrap(
595 Effect.gen(function* () {
596 const environment = yield* DesktopEnvironment.DesktopEnvironment;
597 const endpoints = yield* resolveOtlpEndpoints;
600 - // Unpackaged runs launch a script, so Electron reports its own version.
601 - const serviceVersion = environment.isPackaged
602 - ? environment.appVersion
603 - : desktopPackageJson.version;
598 const resource = {
599 serviceName: "t3code-desktop",
606 - serviceVersion,
600 + // Unpackaged runs launch a script, so Electron reports its own version.
601 + serviceVersion: environment.isPackaged ? environment.appVersion : desktopPackageJson.version,
602 attributes: {
603 "service.namespace": "t3code",
604 "service.runtime": "desktop",
605 "service.mode": environment.isDevelopment ? "development" : "packaged",
611 - "service.instance.id": processServiceInstanceId(endpoints.resourceAttributes),
612 - ...releaseResourceAttributes(
613 - environment.isDevelopment ? "dev" : releaseChannelOf(serviceVersion),
614 - endpoints.resourceAttributes,
615 - ),
606 "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),
607 },
608 };
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+1 -6
@@ -678,7 +678,7 @@ describe("DesktopBackendConfiguration", () => {
678 ),
679 );
680
681 - it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () =>
681 + it.effect("resolveWsl carries the kill switch into the distro", () =>
682 Effect.gen(function* () {
683 const fileSystem = yield* FileSystem.FileSystem;
684 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -688,12 +688,10 @@ describe("DesktopBackendConfiguration", () => {
688 const previousWslEnv = process.env.WSLENV;
689 const previousDisabled = process.env.OTEL_SDK_DISABLED;
690 const previousTelemetry = process.env.T3CODE_TELEMETRY_ENABLED;
691 - const previousResourceAttributes = process.env.OTEL_RESOURCE_ATTRIBUTES;
691 try {
692 delete process.env.WSLENV;
693 process.env.OTEL_SDK_DISABLED = "true";
694 process.env.T3CODE_TELEMETRY_ENABLED = "false";
696 - process.env.OTEL_RESOURCE_ATTRIBUTES = "deployment.environment.name=staging";
695
696 yield* Effect.gen(function* () {
697 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
@@ -703,8 +701,6 @@ describe("DesktopBackendConfiguration", () => {
701 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED");
702 assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false");
703 assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED");
706 - assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging");
707 - assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES");
704 }).pipe(
705 Effect.provide(
706 layerBackendConfiguration().pipe(
@@ -726,7 +722,6 @@ describe("DesktopBackendConfiguration", () => {
722 restoreEnv("WSLENV", previousWslEnv);
723 restoreEnv("OTEL_SDK_DISABLED", previousDisabled);
724 restoreEnv("T3CODE_TELEMETRY_ENABLED", previousTelemetry);
729 - restoreEnv("OTEL_RESOURCE_ATTRIBUTES", previousResourceAttributes);
725 }
726 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
727 );
apps/desktop/src/backend/DesktopBackendConfiguration.ts
-1
@@ -110,7 +110,6 @@ const WSL_FORWARDED_ENV_NAMES = [
110 "OTEL_TRACES_EXPORTER",
111 "OTEL_METRICS_EXPORTER",
112 "OTEL_LOGS_EXPORTER",
113 - "OTEL_RESOURCE_ATTRIBUTES",
113 ] as const;
114
115 const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
apps/mobile/src/features/observability/tracing.test.ts
-1
@@ -27,7 +27,6 @@ it.effect("does not let OTLP serialization failures alter application effects",
27 },
28 {
29 appVariant: "test",
30 - serviceInstanceId: "test-instance",
30 serviceVersion: "1.2.3",
31 },
32 ).pipe(Layer.provide(layerRemoteHttpClient(fetchFn)));
apps/mobile/src/features/observability/tracing.ts
-15
@@ -1,5 +1,4 @@
1 import Constants from "expo-constants";
2 -import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
2 import * as RelayTracing from "@t3tools/shared/relayTracing";
3
4 import { hasTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
@@ -12,16 +11,9 @@ export interface TracingConfig {
11
12 export interface TracingResource {
13 readonly serviceVersion?: string;
15 - readonly serviceInstanceId: string;
14 readonly appVariant: string;
15 }
16
19 -const RELEASE_CHANNEL_BY_VARIANT: Readonly<Record<string, ReleaseChannel | undefined>> = {
20 - development: "dev",
21 - preview: "preview",
22 - production: "stable",
23 -};
24 -
17 export function resolveTracingConfig(): TracingConfig | null {
18 const config = resolveCloudPublicConfig();
19 if (!hasTracingPublicConfig(config)) {
@@ -32,23 +24,16 @@ export function resolveTracingConfig(): TracingConfig | null {
24 }
25
26 export function layerFromConfig(config: TracingConfig | null, resource: TracingResource) {
35 - const channel =
36 - typeof __DEV__ !== "undefined" && __DEV__
37 - ? "dev"
38 - : RELEASE_CHANNEL_BY_VARIANT[resource.appVariant];
27 return RelayTracing.layer(config, {
28 serviceName: "t3code-mobile",
29 serviceVersion: resource.serviceVersion,
30 runtime: "react-native",
43 - serviceInstanceId: resource.serviceInstanceId,
31 client: `mobile-${resource.appVariant}`,
45 - attributes: channel && releaseResourceAttributes(channel),
32 });
33 }
34
35 export const layer = layerFromConfig(resolveTracingConfig(), {
36 serviceVersion: Constants.expoConfig?.version,
51 - serviceInstanceId: Constants.sessionId,
37 appVariant:
38 typeof Constants.expoConfig?.extra?.appVariant === "string"
39 ? Constants.expoConfig.extra.appVariant
apps/mobile/src/features/threads/use-composer-command-menu.ts
-9
@@ -59,8 +59,6 @@ import type { ComposerCommandItem } from "./ComposerCommandPopover";
59 import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
60
61 const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
62 -// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
63 -const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
62
63 function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
64 return { start: draftMessage.length, end: draftMessage.length };
@@ -254,7 +252,6 @@ export function useComposerCommandMenu({
252 );
253 // Record client request time to enforce TTL even when the client clock runs ahead of the server.
254 const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
257 - const failedRefreshesRef = useRef<{ key: string; count: number } | null>(null);
255 const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
256 key: string;
257 notBefore: number;
@@ -310,11 +307,6 @@ export function useComposerCommandMenu({
307 workspaceRefreshKeyRef.current = request;
308 const retryLater = () => {
309 if (workspaceRefreshKeyRef.current !== request) return;
313 - const failed = failedRefreshesRef.current;
314 - const count = failed?.key === key ? failed.count + 1 : 1;
315 - failedRefreshesRef.current = { key, count };
316 - // Keeping the request marker lets the TTL hold off the next scan.
317 - if (count >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return;
310 workspaceRefreshKeyRef.current = null;
311 setWorkspaceRefreshRetry({
312 key,
@@ -334,7 +326,6 @@ export function useComposerCommandMenu({
326 projectCwd,
327 );
328 if (!refreshed) retryLater();
337 - else failedRefreshesRef.current = null;
329 }, retryLater);
330 }, [
331 draftMessage,
apps/server/scripts/acp-mock-agent.ts
+1 -2
@@ -52,7 +52,6 @@ const emitGrokMonitorPostTurnPoll = process.env.T3_ACP_EMIT_GROK_MONITOR_POST_TU
52 const emitGrokBackgroundTaskStarted = process.env.T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED === "1";
53 const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";
54 const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
55 -const omitInitializeModelState = process.env.T3_ACP_OMIT_INITIALIZE_MODEL_STATE === "1";
55 const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";
56 const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
57 const floodStderr = process.env.T3_ACP_FLOOD_STDERR === "1";
@@ -576,7 +575,7 @@ const program = Effect.gen(function* () {
575 return {
576 protocolVersion: 2,
577 info: { name: "t3-acp-mock-agent", version: "0.0.0" },
579 - ...(omitInitializeModelState ? {} : { _meta: { modelState: modelState() } }),
578 + _meta: { modelState: modelState() },
579 capabilities: {
580 session: {
581 ...(supportsSessionLifecycle ? { fork: {}, additionalDirectories: {} } : {}),
apps/server/src/cloud/pinnedRuntime.test.ts
+2 -3
@@ -487,15 +487,14 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
487 const path = yield* Path.Path;
488 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
489 const entry = path.join(versionsDir, "1.0.0", "t3");
490 - // Multicall coreutils (Ubuntu's uutils) refuse to run renamed, so copy Node instead.
491 - yield* fs.copyFile(process.execPath, entry);
490 + yield* fs.copyFile("/bin/sleep", entry);
491 yield* fs.chmod(entry, 0o755);
492 const link = path.join(baseDir, "t3");
493 yield* fs.symlink(entry, link);
494 // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
495 // spawning leaves the process's executable as the only reference.
496 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
498 - yield* spawner.spawn(ChildProcess.make(link, ["-e", "setTimeout(() => {}, 30_000)"]));
497 + yield* spawner.spawn(ChildProcess.make(link, ["30"]));
498 yield* fs.remove(link);
499
500 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
apps/server/src/cloud/relayTracing.ts
+2 -16
@@ -1,30 +1,16 @@
1 -import { processServiceInstanceId } from "@t3tools/shared/observability";
1 import * as RelayTracing from "@t3tools/shared/relayTracing";
3 -import * as Effect from "effect/Effect";
4 -import * as Layer from "effect/Layer";
2
6 -import * as ServerConfig from "../config.ts";
3 import { resolveRelayClientTracingConfig } from "./publicConfig.ts";
4
5 const relayClientTracingConfig = resolveRelayClientTracingConfig();
6
11 -const relayLayer = (resource: Omit<RelayTracing.RelayClientTracingResource, "serviceInstanceId">) =>
12 - Layer.unwrap(
13 - Effect.map(ServerConfig.ServerConfig, (config) =>
14 - RelayTracing.layer(relayClientTracingConfig, {
15 - ...resource,
16 - serviceInstanceId: processServiceInstanceId(config.otelEnvironment.resourceAttributes),
17 - }),
18 - ),
19 - );
20 -
21 -export const layerHeadlessRelayClient = relayLayer({
7 +export const layerHeadlessRelayClient = RelayTracing.layer(relayClientTracingConfig, {
8 serviceName: "t3code-server",
9 runtime: "node",
10 client: "headless-cli",
11 });
12
27 -export const layerServerRelayBroker = relayLayer({
13 +export const layerServerRelayBroker = RelayTracing.layer(relayClientTracingConfig, {
14 serviceName: "t3code-server",
15 runtime: "node",
16 client: "environment-server",
apps/server/src/config.ts
+1 -14
@@ -10,21 +10,10 @@ import * as Schema from "effect/Schema";
10
11 import type { OtlpEndpointSource } from "@t3tools/contracts";
12 import { sweepStalePendingAttachments } from "./attachmentStore.ts";
13 -import {
14 - DEFAULT_SIGNAL_EXPORT,
15 - processServiceInstanceId,
16 - type SignalExport,
17 -} from "@t3tools/shared/observability";
13 +import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";
14 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
19 -import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
15 import packageJson from "../package.json" with { type: "json" };
16
22 -// Official release workflows set this telemetry channel; other builds report dev.
23 -// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel.
24 -declare const __T3CODE_TELEMETRY_CHANNEL__: ReleaseChannel | undefined;
25 -export const telemetryChannel: ReleaseChannel =
26 - typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
27 -
17 export const DEFAULT_PORT = 3773;
18
19 export const RuntimeMode = Schema.Literals(["web", "desktop"]);
@@ -125,8 +114,6 @@ export const otlpResource = (
114 "service.namespace": "t3code",
115 "service.runtime": "t3-server",
116 "t3code.server.managed_by": config.mode === "desktop" ? "desktop" : "standalone",
128 - "service.instance.id": processServiceInstanceId(config.otelEnvironment.resourceAttributes),
129 - ...releaseResourceAttributes(telemetryChannel, config.otelEnvironment.resourceAttributes),
117 "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName,
118 },
119 });
apps/server/src/environment/ServerEnvironment.ts
-1
@@ -239,7 +239,6 @@ export const make = Effect.gen(function* () {
239 threadSnooze: true,
240 environmentThemes: true,
241 usageLimitSources: true,
242 - providerWorkspaceSnapshotsOnDemand: true,
242 usagePriceOverrides: true,
243 usageModelAliases: true,
244 threadPinning: true,
apps/server/src/observability/Metrics.ts
-19
@@ -15,14 +15,6 @@ export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
15 description: "RPC request handling duration.",
16 });
17
18 -export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
19 - description: "Total orchestration commands dispatched, by outcome.",
20 -});
21 -
22 -export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
23 - description: "Orchestration command handling duration, excluding thread dispatch lock wait.",
24 -});
25 -
18 export const orchestrationEffectClaimsTotal = Metric.counter(
19 "t3_orchestration_effect_claims_total",
20 {
@@ -194,14 +186,3 @@ export const withMetrics: {
186 ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
187 <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
188 } = dual(2, withMetricsImpl);
197 -
198 -// Shaped as an `Effect.fn` combinator: the command is the instrumented function's argument.
199 -export const withCommandMetrics = <A, E, R>(
200 - effect: Effect.Effect<A, E, R>,
201 - command: { readonly type: string },
202 -): Effect.Effect<A, E, R> =>
203 - withMetrics(effect, {
204 - counter: orchestrationCommandsTotal,
205 - timer: orchestrationCommandDuration,
206 - attributes: { commandType: command.type },
207 - });
apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
-40
@@ -21,15 +21,10 @@ import {
21 import * as DateTime from "effect/DateTime";
22 import * as Effect from "effect/Effect";
23 import * as Layer from "effect/Layer";
24 -import * as Metric from "effect/Metric";
24 import * as Result from "effect/Result";
25 import * as Stream from "effect/Stream";
26 import * as TestClock from "effect/testing/TestClock";
27 import * as SqlClient from "effect/sql/SqlClient";
29 -import {
30 - orchestrationCommandDuration,
31 - orchestrationCommandsTotal,
32 -} from "../observability/Metrics.ts";
28 import * as SqlitePersistence from "../persistence/Sqlite.ts";
29 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
30 import * as DelegatedTaskQuestionReactor from "./DelegatedTaskQuestionReactor.ts";
@@ -1373,38 +1368,3 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
1368 assert.deepInclude((yield* projections.getThreadProjection(threadId)).thread, active);
1369 }).pipe(Effect.provide(layerTest)),
1370 );
1376 -
1377 -it.effect("dispatch records the command outcome and its duration", () =>
1378 - Effect.gen(function* () {
1379 - const orchestrator = yield* Orchestrator.OrchestratorV2;
1380 - const successes = Metric.value(
1381 - Metric.withAttributes(orchestrationCommandsTotal, {
1382 - commandType: "thread.create",
1383 - outcome: "success",
1384 - }),
1385 - );
1386 - const durations = Metric.value(
1387 - Metric.withAttributes(orchestrationCommandDuration, { commandType: "thread.create" }),
1388 - );
1389 - const successesBefore = (yield* successes).count;
1390 - const durationsBefore = (yield* durations).count;
1391 -
1392 - yield* orchestrator.dispatch({
1393 - type: "thread.create",
1394 - commandId: CommandId.make("create-dispatch-metrics"),
1395 - threadId: ThreadId.make("thread:dispatch-metrics"),
1396 - projectId: ProjectId.make("project:dispatch-metrics"),
1397 - title: "Dispatch metrics",
1398 - modelSelection,
1399 - runtimeMode: "full-access",
1400 - interactionMode: "default",
1401 - branch: null,
1402 - worktreePath: null,
1403 - createdBy: "user",
1404 - creationSource: "web",
1405 - });
1406 -
1407 - assert.strictEqual((yield* successes).count - successesBefore, 1);
1408 - assert.strictEqual((yield* durations).count - durationsBefore, 1);
1409 - }).pipe(Effect.provide(layerTest)),
1410 -);
apps/server/src/orchestration-v2/Orchestrator.ts
+1 -2
@@ -118,7 +118,6 @@ import {
118 type GuestShareCommand,
119 } from "./GuestShareDecider.ts";
120 import * as EffectOutbox from "./EffectOutbox.ts";
121 -import { withCommandMetrics } from "../observability/Metrics.ts";
121 import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
122 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
123 import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
@@ -12117,7 +12116,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12116 storedEvents: committed.storedEvents,
12117 ...(committed.committed ? {} : { replayed: true as const }),
12118 } satisfies OrchestratorV2DispatchResult;
12120 - }, withCommandMetrics);
12119 + });
12120
12121 // dispatchWithReceiptEffect owns the dispatch span; this wrapper selects the thread locks.
12122 const dispatchWithReceipt = Effect.fnUntraced(function* (command: OrchestrationV2ServerCommand) {
apps/server/src/project/ProjectService.test.ts
-32
@@ -5,17 +5,12 @@ import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 -import * as Metric from "effect/Metric";
8 import * as Option from "effect/Option";
9 import * as Ref from "effect/Ref";
10 import { TestClock } from "effect/testing";
11 import * as SqlClient from "effect/sql/SqlClient";
12
13 import * as ServerConfig from "../config.ts";
15 -import {
16 - orchestrationCommandDuration,
17 - orchestrationCommandsTotal,
18 -} from "../observability/Metrics.ts";
14 import * as EventSink from "../orchestration-v2/EventSink.ts";
15 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
16 import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
@@ -208,33 +203,6 @@ it.layer(layerTest)("ProjectService", (it) => {
203 }),
204 );
205
211 - it.effect("records the outcome and duration of a committed project command", () =>
212 - Effect.gen(function* () {
213 - const service = yield* ProjectService.ProjectService;
214 - const successes = Metric.value(
215 - Metric.withAttributes(orchestrationCommandsTotal, {
216 - commandType: "project.create",
217 - outcome: "success",
218 - }),
219 - );
220 - const durations = Metric.value(
221 - Metric.withAttributes(orchestrationCommandDuration, { commandType: "project.create" }),
222 - );
223 - const successesBefore = (yield* successes).count;
224 - const durationsBefore = (yield* durations).count;
225 -
226 - yield* service.create({
227 - commandId: CommandId.make("command:metrics:create"),
228 - projectId: ProjectId.make("project:metrics"),
229 - title: "Metrics",
230 - workspaceRoot: "/work/metrics",
231 - });
232 -
233 - assert.strictEqual((yield* successes).count - successesBefore, 1);
234 - assert.strictEqual((yield* durations).count - durationsBefore, 1);
235 - }),
236 - );
237 -
206 it.effect("auto-bootstraps a workspace exactly once", () =>
207 Effect.gen(function* () {
208 const service = yield* ProjectService.ProjectService;
apps/server/src/project/ProjectService.ts
+1 -2
@@ -17,7 +17,6 @@ import * as Option from "effect/Option";
17 import * as Result from "effect/Result";
18 import * as Schema from "effect/Schema";
19
20 -import { withCommandMetrics } from "../observability/Metrics.ts";
20 import * as EventSink from "../orchestration-v2/EventSink.ts";
21 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
22 import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
@@ -284,7 +283,7 @@ export const make = Effect.gen(function* () {
283 rejection ?? receipt.error ?? "The command was previously rejected.",
284 );
285 }
287 - }, withCommandMetrics);
286 + });
287
288 const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
289 const row = yield* readRow(projectId, { includeDeleted: true });
apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts
+1 -20
@@ -1,15 +1,8 @@
1 // @effect-diagnostics nodeBuiltinImport:off - cleanup uses Node's retrying rm, which the FileSystem service does not expose.
2 -import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { ClaudeSettings, type ServerProvider } from "@t3tools/contracts";
2 import { vi } from "vite-plus/test";
3 import { assert, it } from "@effect/vitest";
6 -import * as Effect from "effect/Effect";
7 -import * as Schema from "effect/Schema";
4
9 -import {
10 - buildClaudeCapabilitiesProbeQueryOptions,
11 - probeClaudeWorkspaceSnapshot,
12 -} from "./ClaudeProvider.ts";
5 +import { buildClaudeCapabilitiesProbeQueryOptions } from "./ClaudeProvider.ts";
6
7 vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
8
@@ -27,15 +20,3 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp
20 assert.deepEqual(options.mcpServers, {});
21 assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
22 });
30 -
31 -it.effect("reports a deleted worktree's scan as finished, not pending", () =>
32 - Effect.gen(function* () {
33 - const snapshot = yield* probeClaudeWorkspaceSnapshot(
34 - yield* Schema.decodeEffect(ClaudeSettings)({}),
35 - { skills: [], slashCommands: [] } as unknown as ServerProvider,
36 - "/nonexistent/t3-deleted-worktree",
37 - { HOME: "/nonexistent/t3-home" },
38 - );
39 - assert.strictEqual(snapshot.slashCommandsPending, false);
40 - }).pipe(Effect.provide(NodeServices.layer)),
41 -);
apps/server/src/provider/ClaudeProvider.ts
+5 -9
@@ -431,14 +431,10 @@ export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnaps
431 ): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
432 if (!claudeSettings.enabled) return machineSnapshot;
433 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
434 - const fileSystem = yield* FileSystem.FileSystem;
435 - // A deleted worktree can never answer the probe. Pending would make clients rescan it forever.
436 - const cwdExists = yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true));
437 - const probeResult = cwdExists
438 - ? yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(Effect.result)
439 - : undefined;
440 - const capabilities =
441 - probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
434 + const probeResult = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(
435 + Effect.result,
436 + );
437 + const capabilities = Result.isSuccess(probeResult) ? probeResult.success : undefined;
438 return {
439 ...machineSnapshot,
440 skills,
@@ -446,7 +442,7 @@ export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnaps
442 COMPACT_SLASH_COMMAND,
443 ...(capabilities?.slashCommands ?? []),
444 ]),
449 - slashCommandsPending: cwdExists && !capabilities,
445 + slashCommandsPending: !capabilities,
446 };
447 });
448
apps/server/src/provider/GrokProvider.test.ts
-21
@@ -352,27 +352,6 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
352 }),
353 );
354
355 - it.effect("warns instead of reporting ready when no models are discovered", () =>
356 - Effect.gen(function* () {
357 - const snapshot = yield* Effect.scoped(
358 - Effect.gen(function* () {
359 - const grokPath = yield* writeFakeGrokCli({
360 - modelsOutput: "You are logged in with grok.com.\n",
361 - acp: true,
362 - });
363 - return yield* checkGrokProviderStatus(
364 - decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
365 - { ...process.env, XAI_API_KEY: "", T3_ACP_OMIT_INITIALIZE_MODEL_STATE: "1" },
366 - );
367 - }),
368 - );
369 -
370 - expect(snapshot.status).toBe("warning");
371 - expect(snapshot.message).toContain("did not list any models");
372 - expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
373 - }),
374 - );
375 -
355 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
356 Effect.gen(function* () {
357 const snapshot = yield* Effect.scoped(
apps/server/src/provider/ProviderRegistry.test.ts
-130
@@ -693,44 +693,6 @@ it.layer(
693 );
694 });
695
696 - it("drops Grok models a completed probe no longer advertises", () => {
697 - const previousProvider = {
698 - instanceId: ProviderInstanceId.make("grok"),
699 - driver: ProviderDriverKind.make("grok"),
700 - status: "ready",
701 - enabled: true,
702 - installed: true,
703 - auth: { status: "authenticated" },
704 - checkedAt: "2026-09-30T00:00:00.000Z",
705 - version: "1.0.44",
706 - models: [
707 - { slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null },
708 - { slug: "codexhub-removed", name: "Removed", isCustom: false, capabilities: null },
709 - ],
710 - slashCommands: [],
711 - skills: [],
712 - } as const satisfies ServerProvider;
713 - const refreshedProvider = {
714 - ...previousProvider,
715 - checkedAt: "2026-09-30T00:01:00.000Z",
716 - models: [previousProvider.models[0]],
717 - } satisfies ServerProvider;
718 - const acpFailedProvider = {
719 - ...refreshedProvider,
720 - status: "warning",
721 - message: "Grok CLI is installed but ACP initialize failed.",
722 - } satisfies ServerProvider;
723 -
724 - assert.deepStrictEqual(
725 - ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
726 - [previousProvider.models[0]],
727 - );
728 - assert.deepStrictEqual(
729 - ProviderRegistry.mergeProviderSnapshot(previousProvider, acpFailedProvider).models,
730 - [...previousProvider.models],
731 - );
732 - });
733 -
696 it("retains stale OpenCode models when a refresh fails", () => {
697 const previousProvider = {
698 instanceId: ProviderInstanceId.make("opencode"),
@@ -1284,98 +1246,6 @@ it.layer(
1246 );
1247 });
1248
1287 - it.effect(
1288 - "a second request for a cwd being scanned gets its result, even if the first leaves",
1289 - () =>
1290 - Effect.gen(function* () {
1291 - const driver = ProviderDriverKind.make("codex");
1292 - const instanceId = ProviderInstanceId.make("codex");
1293 - const provider = {
1294 - instanceId,
1295 - driver,
1296 - status: "ready",
1297 - enabled: true,
1298 - installed: true,
1299 - auth: { status: "authenticated" },
1300 - checkedAt: "2026-06-10T00:00:00.000Z",
1301 - version: "1.0.0",
1302 - models: [],
1303 - slashCommands: [],
1304 - skills: [],
1305 - } as const satisfies ServerProvider;
1306 - const scanStarted = yield* Deferred.make<void>();
1307 - const releaseScan = yield* Deferred.make<void>();
1308 - const scans = yield* Ref.make(0);
1309 - const instance: ProviderInstance = {
1310 - instanceId,
1311 - driverKind: driver,
1312 - continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
1313 - displayName: undefined,
1314 - enabled: true,
1315 - snapshot: {
1316 - resolveMaintenance: () =>
1317 - Effect.succeed(
1318 - makeManualOnlyProviderMaintenanceCapabilities({
1319 - provider: driver,
1320 - packageName: null,
1321 - }),
1322 - ),
1323 - getSnapshot: Effect.succeed(provider),
1324 - refresh: Effect.succeed(provider),
1325 - streamChanges: Stream.empty,
1326 - applyUsageLimits: () => Effect.void,
1327 - },
1328 - snapshotForCwd: () =>
1329 - Ref.update(scans, (count) => count + 1).pipe(
1330 - Effect.andThen(Deferred.succeed(scanStarted, undefined)),
1331 - Effect.andThen(Deferred.await(releaseScan)),
1332 - Effect.as(provider),
1333 - ),
1334 - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
1335 - textGeneration: {} as ProviderInstance["textGeneration"],
1336 - };
1337 - const layerInstanceRegistry = Layer.succeed(
1338 - ProviderInstanceRegistry.ProviderInstanceRegistry,
1339 - {
1340 - getInstance: (requestedId) =>
1341 - Effect.succeed(requestedId === instanceId ? instance : undefined),
1342 - listInstances: Effect.succeed([instance]),
1343 - listUnavailable: Effect.succeed([]),
1344 - streamChanges: Stream.empty,
1345 - subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
1346 - },
1347 - );
1348 - const scope = yield* Scope.make();
1349 - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
1350 - const runtimeServices = yield* Layer.build(
1351 - ProviderRegistry.layer.pipe(
1352 - Layer.provideMerge(layerInstanceRegistry),
1353 - Layer.provideMerge(
1354 - ServerConfig.layerTest(process.cwd(), {
1355 - prefix: "t3-provider-registry-shared-workspace-scan-",
1356 - }),
1357 - ),
1358 - Layer.provideMerge(NodeServices.layer),
1359 - ),
1360 - ).pipe(Scope.provide(scope));
1361 -
1362 - yield* Effect.gen(function* () {
1363 - const registry = yield* ProviderRegistry.ProviderRegistry;
1364 - const refresh = registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
1365 - const first = yield* Effect.forkChild(refresh);
1366 - yield* Deferred.await(scanStarted);
1367 - const second = yield* Effect.forkChild(refresh, { startImmediately: true });
1368 - yield* Fiber.interrupt(first);
1369 - yield* Deferred.succeed(releaseScan, undefined);
1370 - assert.deepStrictEqual(
1371 - (yield* Fiber.join(second))[0]?.workspaceSnapshots?.map((snapshot) => snapshot.cwd),
1372 - ["/workspace"],
1373 - );
1374 - assert.strictEqual(yield* Ref.get(scans), 1);
1375 - }).pipe(Effect.provide(runtimeServices));
1376 - }),
1377 - );
1378 -
1249 it.effect("publishes workspace skills while machine health is in error", () =>
1250 Effect.gen(function* () {
1251 const driver = ProviderDriverKind.make("codex");
apps/server/src/provider/ProviderRegistry.ts
+12 -35
@@ -12,7 +12,6 @@ import * as DateTime from "effect/DateTime";
12 import * as Deferred from "effect/Deferred";
13 import * as Effect from "effect/Effect";
14 import * as Equal from "effect/Equal";
15 -import * as Fiber from "effect/Fiber";
15 import * as FileSystem from "effect/FileSystem";
16 import * as Layer from "effect/Layer";
17 import * as Option from "effect/Option";
@@ -168,12 +167,6 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean =>
167 );
168 }
169
171 - if (provider.driver === ProviderDriverKind.make("grok")) {
172 - // Grok reports ready only after it discovers a model list; the pending,
173 - // ACP-failed, empty-inventory, and logged-out probes are warning/error.
174 - return !(provider.installed && provider.status === "ready");
175 - }
176 -
170 const isAntigravity = provider.driver === ProviderDriverKind.make("antigravity");
171 const isCodex = provider.driver === ProviderDriverKind.make("codex");
172 if (!isAntigravity && !isCodex && provider.driver !== ProviderDriverKind.make("opencode")) {
@@ -412,7 +405,7 @@ export const layer = Layer.effect(
405 cachedProviders.map((provider) => classifyCompatibility(provider, initialManifest)),
406 );
407 const workspaceRefreshesRef = yield* Ref.make<
415 - ReadonlyMap<ProviderInstance, ReadonlyMap<string, Deferred.Deferred<void>>>
408 + ReadonlyMap<ProviderInstance, ReadonlyMap<string, symbol>>
409 >(new Map());
410 const maintenanceActionStatesRef = yield* Ref.make<
411 ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
@@ -929,13 +922,21 @@ export const layer = Layer.effect(
922 const scannedAt = DateTime.formatIso(now);
923 const instance = yield* instanceRegistry.getInstance(input.instanceId);
924 if (!instance?.snapshotForCwd) return providers;
932 - const token = yield* Deferred.make<void>();
925 + const token = Symbol();
926 + const claimed = yield* Ref.modify(workspaceRefreshesRef, (refreshes) => {
927 + const current = refreshes.get(instance);
928 + if (!input.fresh && current?.has(input.cwd)) return [false, refreshes] as const;
929 + const next = new Map(refreshes);
930 + next.set(instance, new Map(current).set(input.cwd, token));
931 + return [true, next] as const;
932 + });
933 + if (!claimed) return yield* Ref.get(providersRef);
934 const refreshMachineSnapshot = input.fresh
935 ? (instance.invalidateCaches ?? Effect.void).pipe(
936 Effect.andThen(refreshInstance(input.instanceId)),
937 )
938 : Effect.void;
938 - const runScan = refreshMachineSnapshot.pipe(
939 + return yield* refreshMachineSnapshot.pipe(
940 Effect.andThen(instance.snapshotForCwd(input.cwd)),
941 // Scans fail on error; returned inventory remains valid even when provider health reports an error.
942 Effect.flatMap((scopedSnapshot) =>
@@ -973,33 +974,9 @@ export const layer = Layer.effect(
974 if (nextCwds.size) next.set(instance, nextCwds);
975 else next.delete(instance);
976 return next;
976 - }).pipe(Effect.andThen(Deferred.succeed(token, undefined))),
977 + }),
978 ),
979 );
979 - // The claim and the fork happen together, so the token is always completed. The scan is
980 - // detached so a disconnecting owner cannot cancel the result its waiters depend on.
981 - const claim = yield* Effect.uninterruptible(
982 - Effect.gen(function* () {
983 - const inFlight = yield* Ref.modify(workspaceRefreshesRef, (refreshes) => {
984 - const current = refreshes.get(instance);
985 - const running = current?.get(input.cwd);
986 - if (!input.fresh && running) return [running, refreshes] as const;
987 - const next = new Map(refreshes);
988 - next.set(instance, new Map(current).set(input.cwd, token));
989 - return [undefined, next] as const;
990 - });
991 - if (inFlight) return { inFlight } as const;
992 - return {
993 - // Starting now attaches the scan's `ensuring` before anything can close the scope.
994 - scan: yield* Effect.forkIn(runScan, serviceScope, { startImmediately: true }),
995 - } as const;
996 - }),
997 - );
998 - // Wait for the running scan: on-demand clients get its result only in this reply.
999 - if ("inFlight" in claim) {
1000 - return yield* Deferred.await(claim.inFlight).pipe(Effect.andThen(Ref.get(providersRef)));
1001 - }
1002 - return yield* Fiber.join(claim.scan);
980 });
981
982 return {
apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts
+1 -1
@@ -165,7 +165,7 @@ describe("terminatePosixOwnedProcessTree", () => {
165 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined }),
166 ).toBeUndefined();
167 expect(
168 - AcpSessionRuntime.resolveLinuxCgroupTargetCommand("sh", scratch, { PATH: undefined }),
168 + AcpSessionRuntime.resolveLinuxCgroupTargetCommand("node", scratch, { PATH: undefined }),
169 ).toBeDefined();
170 expect(
171 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, {
apps/server/src/serverLogger.test.ts
-15
@@ -151,21 +151,6 @@ const printThroughConsole = (fields: object) =>
151 });
152
153 describe("ServerLoggerLive", () => {
154 - it.effect("exports the operator's service instance id instead of a generated one", () =>
155 - Effect.gen(function* () {
156 - const { requests } = yield* logInSpanThrough({
157 - otlpLogsUrl: "https://collector.example.com/v1/logs",
158 - otelEnvironment: {
159 - ...OtelEnvironment.none,
160 - resourceAttributes: { "service.instance.id": "pod-7" },
161 - },
162 - });
163 -
164 - const body = requests.map((request) => request.body).join("\n");
165 - assert.include(body, '"key":"service.instance.id","value":{"stringValue":"pod-7"}');
166 - }),
167 - );
168 -
154 it.effect("exports a resource that names whether the desktop app launched the server", () =>
155 Effect.gen(function* () {
156 const { requests } = yield* logInSpanThrough({
apps/server/src/telemetry/AnalyticsService.ts
+7 -1
@@ -50,6 +50,10 @@ const RETRY_MAX_DELAY_MS = 300_000;
50 // These statuses reject the batch itself; unlike 408/429, retrying cannot help.
51 const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
52
53 +// Official release workflows set this telemetry channel; other builds report dev.
54 +// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel.
55 +declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined;
56 +
57 /** `random` is in [0, 1). */
58 function retryDelayMs(failures: number, random: number): number {
59 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
@@ -138,6 +142,8 @@ export const make = Effect.gen(function* () {
142 // The background flush and the shutdown flush must not send the same batch at once.
143 const flushLock = yield* Semaphore.make(1);
144 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
145 + const telemetryChannel =
146 + typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
147 const hostPlatform = yield* HostProcess.Platform;
148 const hostArchitecture = yield* HostProcess.Architecture;
149
@@ -192,7 +198,7 @@ export const make = Effect.gen(function* () {
198 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
199 arch: hostArchitecture,
200 t3CodeVersion: packageJson.version,
195 - telemetryChannel: ServerConfig.telemetryChannel,
201 + telemetryChannel,
202 clientType,
203 serverOs: serverOsFromNodePlatform(hostPlatform),
204 serverArch: hostArchitecture,
apps/server/src/testUtils/managedServiceEnv.setup.ts deleted
-6
@@ -1,6 +0,0 @@
1 -import { SERVICE_LAUNCHER_CONTEXT_ENV } from "../cloud/serviceProtocol.ts";
2 -
3 -// Agents inside a managed T3 service inherit its home and launcher context; CI has neither.
4 -for (const name of ["T3CODE_HOME", "T3_BOOT_SERVICE_UNIT", SERVICE_LAUNCHER_CONTEXT_ENV]) {
5 - delete process.env[name];
6 -}
apps/server/src/ws.test.ts
-161
@@ -5,17 +5,13 @@ import {
5 EnvironmentId,
6 ProjectId,
7 ThreadId,
8 - ProviderDriverKind,
9 - ProviderInstanceId,
8 WS_METHODS,
11 - WsServerRefreshProvidersRpc,
9 WsSubscribeServerConfigRpc,
10 type OrchestrationV2StoredEvent,
11 type OrchestrationV2ThreadShell,
12 type OrchestrationProjectShell,
13 type ServerConfig,
14 type ServerConfigStreamEvent,
18 - type ServerProvider,
15 } from "@t3tools/contracts";
16 import * as Deferred from "effect/Deferred";
17 import * as DateTime from "effect/DateTime";
@@ -24,7 +20,6 @@ import * as Layer from "effect/Layer";
20 import * as PubSub from "effect/PubSub";
21 import * as Queue from "effect/Queue";
22 import * as Stream from "effect/Stream";
27 -import * as TestClock from "effect/testing/TestClock";
23 import { Headers } from "effect/http";
24 import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc";
25 import * as SqlClient from "effect/sql/SqlClient";
@@ -637,162 +632,6 @@ it.effect(
632 ),
633 );
634
640 -it.effect("on-demand clients get provider config without workspace snapshots", () =>
641 - Effect.gen(function* () {
642 - const instanceId = ProviderInstanceId.make("claudeAgent");
643 - const snapshotFor = (cwd: string, checkedAt: string) => ({
644 - cwd,
645 - checkedAt,
646 - slashCommands: [{ name: `${cwd.slice(1)}-command` }],
647 - skills: [],
648 - });
649 - const provider: ServerProvider = {
650 - instanceId,
651 - driver: ProviderDriverKind.make("claudeAgent"),
652 - enabled: true,
653 - installed: true,
654 - version: "1.0.0",
655 - status: "ready",
656 - auth: { status: "authenticated" },
657 - checkedAt: "2026-10-25T00:00:00.000Z",
658 - models: [],
659 - slashCommands: [{ name: "machine-command" }],
660 - skills: [],
661 - workspaceSnapshots: [
662 - snapshotFor("/a", "2026-10-25T00:00:00.000Z"),
663 - snapshotFor("/b", "2026-10-25T00:00:00.000Z"),
664 - ],
665 - };
666 - const providerChanges = yield* Queue.unbounded<ReadonlyArray<ServerProvider>>();
667 - const pulled = yield* Queue.unbounded<void>();
668 - const responses = yield* Queue.unbounded<unknown>();
669 - const configRpcServices = Layer.mergeAll(
670 - layerUnusedConfigRpcServices,
671 - Layer.mock(ExternalLauncher.ExternalLauncher)({
672 - resolveAvailableEditors: () => Effect.succeed([]),
673 - resolveFileManagerRevealKind: () => Effect.succeed(undefined),
674 - }),
675 - Layer.mock(ProviderRegistry.ProviderRegistry)({
676 - getProviders: Effect.succeed([provider]),
677 - streamChanges: Stream.fromQueue(providerChanges).pipe(
678 - Stream.tap(() => Queue.offer(pulled, undefined)),
679 - ),
680 - refreshWorkspaceSnapshot: () => Effect.succeed([provider]),
681 - }),
682 - Layer.mock(UsageLimitSources.UsageLimitSources)({
683 - current: Effect.succeed([]),
684 - streamChanges: Stream.make([]),
685 - }),
686 - Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
687 - resolveTargets: () => Effect.succeed([]),
688 - }),
689 - Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }),
690 - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
691 - scratchRoot: Effect.succeedNone,
692 - namedProjectsRoot: process.cwd(),
693 - }),
694 - Layer.mock(ServerEnvironment.ServerEnvironment)({
695 - getDescriptor: Effect.succeed({
696 - environmentId: EnvironmentId.make("config-test"),
697 - label: "Config test",
698 - platform: { os: "linux", arch: "x64" },
699 - serverVersion: "0.0.0",
700 - capabilities: { repositoryIdentity: false },
701 - }),
702 - }),
703 - Layer.mock(EnvironmentAuth.EnvironmentAuth)({
704 - getDescriptor: () =>
705 - Effect.succeed({
706 - policy: "loopback-browser",
707 - bootstrapMethods: [],
708 - sessionMethods: ["browser-session-cookie"],
709 - sessionCookieName: "config-test-session",
710 - }),
711 - }),
712 - );
713 - const server = yield* RpcServer.makeNoSerialization(
714 - RpcGroup.make(WsSubscribeServerConfigRpc, WsServerRefreshProvidersRpc),
715 - {
716 - ...WS_RPC_SERVER_OPTIONS,
717 - onFromServer: (response) =>
718 - response._tag === "Chunk"
719 - ? Effect.forEach(response.values, (value) => Queue.offer(responses, value), {
720 - discard: true,
721 - })
722 - : response._tag === "Exit" && response.exit._tag === "Success"
723 - ? Queue.offer(responses, response.exit.value)
724 - : Effect.void,
725 - },
726 - ).pipe(
727 - Effect.provide(
728 - layerWsRpc(
729 - {
730 - sessionId: AuthSessionId.make("config-test"),
731 - subject: "config-test",
732 - method: "browser-session-cookie",
733 - scopes: [],
734 - },
735 - {},
736 - {},
737 - yield* PreviewAutomationBroker.PreviewAutomationBroker,
738 - yield* ServerBrowser.ServerBrowser,
739 - ).pipe(Layer.provide(configRpcServices)),
740 - ),
741 - );
742 - const configRequest = RpcMessage.RequestId("config");
743 - yield* server.write(0, {
744 - _tag: "Request",
745 - id: configRequest,
746 - tag: WS_METHODS.subscribeServerConfig,
747 - payload: { workspaceSnapshotsOnDemand: true },
748 - headers: Headers.empty,
749 - });
750 - const snapshot = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
751 - if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot");
752 - assert.isUndefined(snapshot.config.providers[0]?.workspaceSnapshots);
753 - yield* server.write(0, { _tag: "Ack", requestId: configRequest });
754 -
755 - // A rescan that only touches a snapshot sends nothing; the next real change does.
756 - yield* Queue.offer(providerChanges, [
757 - { ...provider, workspaceSnapshots: [snapshotFor("/a", "2026-10-25T00:05:00.000Z")] },
758 - ]);
759 - yield* Queue.take(pulled);
760 - yield* TestClock.adjust("1 second");
761 - yield* Queue.offer(providerChanges, [{ ...provider, status: "warning" }]);
762 - yield* Queue.take(pulled);
763 - yield* TestClock.adjust("1 second");
764 - const update = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
765 - if (update.type !== "providerStatuses") return yield* Effect.die("Expected provider update");
766 - assert.equal(update.payload.providers[0]?.status, "warning");
767 - assert.isUndefined(update.payload.providers[0]?.workspaceSnapshots);
768 -
769 - yield* server.write(0, {
770 - _tag: "Request",
771 - id: RpcMessage.RequestId("refresh"),
772 - tag: WS_METHODS.serverRefreshProviders,
773 - payload: { instanceId, cwd: "/b", workspaceSnapshotsOnDemand: true },
774 - headers: Headers.empty,
775 - });
776 - const refreshed = (yield* Queue.take(responses)) as {
777 - readonly providers: ReadonlyArray<ServerProvider>;
778 - };
779 - assert.deepEqual(
780 - refreshed.providers.map((entry) => [entry.workspaceSnapshots, entry.slashCommands]),
781 - [[[snapshotFor("/b", "2026-10-25T00:00:00.000Z")], []]],
782 - );
783 - yield* server.write(0, { _tag: "Interrupt", requestId: configRequest, interruptors: [] });
784 - }).pipe(
785 - Effect.provide(
786 - Layer.mergeAll(
787 - Layer.fresh(layerConfigSources),
788 - Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
789 - Layer.mock(ServerBrowser.ServerBrowser)({}),
790 - ),
791 - ),
792 - Effect.scoped,
793 - ),
794 -);
795 -
635 // Compaction keeps the oldest and newest event per message, so a cursor older
636 // than the deleted rows still replays each message where the client would
637 // first have seen it (reducers append on first sight) and reaches the same
apps/server/src/ws.ts
+6 -49
@@ -82,7 +82,6 @@ import {
82 type ServerConfig as ClientServerConfig,
83 type ServerConfigStreamEvent,
84 type ServerLifecycleStreamEvent,
85 - type ServerProvider,
85 type FilesystemBrowseFailure,
86 FilesystemBrowseError,
87 AssetWorkspaceContextNotFoundError,
@@ -364,10 +363,6 @@ export const withLateEditorConfig = <E, R>(
363 );
364 };
365
367 -function withoutWorkspaceSnapshots(providers: ReadonlyArray<ServerProvider>): ServerProvider[] {
368 - return providers.map(({ workspaceSnapshots: _workspaceSnapshots, ...provider }) => provider);
369 -}
370 -
366 function unexpectedCompatibilityError(error: never): never {
367 throw new Error(`Unhandled compatibility error: ${String(error)}`);
368 }
@@ -1726,16 +1721,12 @@ export const layerWsRpc = (
1721
1722 const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: {
1723 readonly usageLimitsCommand: boolean;
1729 - readonly workspaceSnapshotsOnDemand: boolean;
1724 }) {
1725 const keybindingsConfig = yield* keybindings.loadConfigState;
1726 const currentProviders = yield* providerRegistry.getProviders;
1733 - const commandProviders = options.usageLimitsCommand
1727 + const providers = options.usageLimitsCommand
1728 ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)
1729 : currentProviders;
1736 - const providers = options.workspaceSnapshotsOnDemand
1737 - ? withoutWorkspaceSnapshots(commandProviders)
1738 - : commandProviders;
1730 const settings = ServerSettings.redactServerSettingsForClient(
1731 yield* serverSettings.getSettings,
1732 );
@@ -2216,8 +2207,7 @@ export const layerWsRpc = (
2207 Effect.andThen(scheduledTasks.getWebhookDelivery(input)),
2208 ),
2209 [WS_METHODS.serverProbe]: (_input) => Effect.succeed({}),
2219 - [WS_METHODS.serverGetConfig]: (_input) =>
2220 - loadServerConfig({ usageLimitsCommand: false, workspaceSnapshotsOnDemand: false }),
2210 + [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig({ usageLimitsCommand: false }),
2211 [WS_METHODS.serverSearchAcpRegistry]: (input) =>
2212 acpRegistryCatalog
2213 .search(input)
@@ -2386,29 +2376,7 @@ export const layerWsRpc = (
2376 providers = yield* providerRegistry.refreshInstance(instance.instanceId);
2377 }
2378 }
2389 - if (input.workspaceSnapshotsOnDemand !== true) return { providers };
2390 - const commandProviders =
2391 - input.usageLimitsCommand === true
2392 - ? withUsageLimitsCommands(providers, yield* usageLimitSources.current)
2393 - : providers;
2394 - const { instanceId, cwd } = input;
2395 - if (instanceId === undefined || cwd === undefined) {
2396 - return { providers: withoutWorkspaceSnapshots(commandProviders) };
2397 - }
2398 - return {
2399 - providers: commandProviders
2400 - .filter((provider) => provider.instanceId === instanceId)
2401 - .map((provider) => ({
2402 - ...provider,
2403 - // Callers read only the cwd snapshot; the config stream carries the rest.
2404 - models: [],
2405 - slashCommands: [],
2406 - skills: [],
2407 - workspaceSnapshots: (provider.workspaceSnapshots ?? []).filter(
2408 - (snapshot) => snapshot.cwd === cwd,
2409 - ),
2410 - })),
2411 - };
2379 + return { providers };
2380 }),
2381 [WS_METHODS.mcpAppsCallTool]: (input) => mcpAppRequests.callTool(input),
2382 [WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input),
@@ -3125,14 +3093,10 @@ export const layerWsRpc = (
3093 Stream.unwrap(
3094 Effect.gen(function* () {
3095 const usageLimitsCommand = input.usageLimitsCommand === true;
3128 - const workspaceSnapshotsOnDemand = input.workspaceSnapshotsOnDemand === true;
3096 // Buffer changes through discovery and the initial snapshot's RPC ACK wait.
3097 const keybindingsChanges = yield* keybindings.subscribeChanges;
3098 const settingsChanges = yield* serverSettings.subscribeChanges;
3132 - const config = yield* loadServerConfig({
3133 - usageLimitsCommand,
3134 - workspaceSnapshotsOnDemand,
3135 - });
3099 + const config = yield* loadServerConfig({ usageLimitsCommand });
3100 const keybindingsUpdates = keybindingsChanges.pipe(
3101 Stream.map((event) => ({
3102 version: 1 as const,
@@ -3154,15 +3118,8 @@ export const layerWsRpc = (
3118 usageLimitsCommand ? sameUsageLimitCommandCoverage : () => true,
3119 ),
3120 ),
3157 - (providers, sources) => {
3158 - const commandProviders = usageLimitsCommand
3159 - ? withUsageLimitsCommands(providers, sources)
3160 - : providers;
3161 - // Stripped before the de-dupe below, so snapshot-only changes send nothing.
3162 - return workspaceSnapshotsOnDemand
3163 - ? withoutWorkspaceSnapshots(commandProviders)
3164 - : commandProviders;
3165 - },
3121 + (providers, sources) =>
3122 + usageLimitsCommand ? withUsageLimitsCommands(providers, sources) : providers,
3123 ).pipe(
3124 // Compare initial paired values with the snapshot; blindly dropping them loses changes between snapshot and subscription.
3125 (updates) => Stream.concat(rpcInitialItems([config.providers]), updates),
apps/server/vite.config.ts
+1 -4
@@ -128,10 +128,7 @@ export default mergeConfig(
128 // Parallel sqlite/git/worktree/orchestration tests introduce load-sensitive flakes.
129 fileParallelism: false,
130 sequence: { sequencer: WeightedShardSequencer },
131 - setupFiles: [
132 - "./src/testUtils/gitConfig.setup.ts",
133 - "./src/testUtils/managedServiceEnv.setup.ts",
134 - ],
131 + setupFiles: ["./src/testUtils/gitConfig.setup.ts"],
132 hookTimeout: 120_000,
133 testTimeout: 120_000,
134 },
apps/web/src/components/chat/ChatMarkdownMedia.tsx
-2
@@ -207,7 +207,6 @@ export function ChatMarkdownImage(props: {
207 alt={props.alt}
208 data-markdown-copy={props.copyMarkdown}
209 decoding="async"
210 - loading="lazy"
210 draggable={false}
211 className={cn(
212 CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
@@ -264,7 +263,6 @@ export function ChatMarkdownImage(props: {
263 src={src}
264 alt={props.alt}
265 decoding="async"
267 - loading="lazy"
266 draggable={false}
267 className="invisible absolute inset-0 size-full"
268 {...imageEvents(src)}
apps/web/src/components/chat/TimelineUserMessageRow.tsx
-1
@@ -508,7 +508,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
508 src={image.previewUrl}
509 alt={image.name}
510 decoding="async"
511 - loading="lazy"
511 className="block size-full object-cover"
512 />
513 </button>
apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts
-9
@@ -14,8 +14,6 @@ import { useEffect, useEffectEvent, useRef, useState } from "react";
14 import { useStableCallback } from "../../hooks/useStableCallback";
15
16 const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
17 -// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
18 -const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
17
18 /**
19 * Keeps the selected provider's workspace snapshot fresh for the composer's
@@ -34,7 +32,6 @@ export function useProviderWorkspaceSnapshotRefresh(input: {
32 // The last scan this composer asked for. A request inside the TTL is not
33 // repeated, so a client clock ahead of the server's cannot loop rescans.
34 const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
37 - const failedRefreshesRef = useRef<{ key: string; count: number } | null>(null);
35 const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
36 key: string;
37 notBefore: number;
@@ -99,11 +96,6 @@ export function useProviderWorkspaceSnapshotRefresh(input: {
96 workspaceRefreshKeyRef.current = request;
97 const retryLater = () => {
98 if (workspaceRefreshKeyRef.current !== request) return;
102 - const failed = failedRefreshesRef.current;
103 - const count = failed?.key === key ? failed.count + 1 : 1;
104 - failedRefreshesRef.current = { key, count };
105 - // Keeping the request marker lets the TTL hold off the next scan.
106 - if (count >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return;
99 workspaceRefreshKeyRef.current = null;
100 setWorkspaceRefreshRetry({
101 key,
@@ -123,7 +115,6 @@ export function useProviderWorkspaceSnapshotRefresh(input: {
115 gitCwd,
116 );
117 if (!refreshedSnapshot) retryLater();
126 - else failedRefreshesRef.current = null;
118 }, retryLater);
119 };
120 const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
apps/web/src/lib/runtime.ts
-1
@@ -22,7 +22,6 @@ const layerRelayTracing = RelayTracing.layer(resolveRelayTracingConfig(), {
22 serviceName: "t3code-web",
23 serviceVersion: import.meta.env.APP_VERSION,
24 runtime: "browser",
25 - serviceInstanceId: ClientTracer.serviceInstanceId,
25 client: typeof window !== "undefined" && window.desktopBridge ? "desktop" : "web",
26 }).pipe(Layer.provide(layerHttpClient));
27
apps/web/src/observability/clientTracer.ts
-5
@@ -1,11 +1,6 @@
1 import * as Layer from "effect/Layer";
2 import * as Tracer from "effect/Tracer";
3
4 -import { randomUUID } from "../lib/utils";
5 -
6 -/** `service.instance.id` for this page load, shared by every resource the UI exports. */
7 -export const serviceInstanceId = randomUUID();
8 -
4 let delegate: Tracer.Tracer | null = null;
5
6 export function setDelegate(next: Tracer.Tracer | null): void {
apps/web/src/observability/clientTracing.ts
+1 -10
@@ -8,26 +8,17 @@ import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observabilit
8 import { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9 import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
10 import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
11 -import { releaseChannelOf, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
11 import * as ClientTracer from "./clientTracer";
12 import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
13 import { isElectron } from "../env";
14 import { APP_VERSION } from "~/branding";
15
16 const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
18 -// PR previews can't mark themselves in APP_VERSION without breaking the version-skew check against the server.
19 -const RELEASE_CHANNEL =
20 - import.meta.env.DEV || import.meta.env.VITE_RELEASE_CHANNEL === "dev"
21 - ? "dev"
22 - : import.meta.env.VITE_RELEASE_CHANNEL === "preview"
23 - ? "preview"
24 - : releaseChannelOf(APP_VERSION);
17 const CLIENT_TRACING_RESOURCE = {
18 serviceName: "t3code-web",
19 attributes: {
20 "service.namespace": "t3code",
29 - "service.instance.id": ClientTracer.serviceInstanceId,
30 - ...releaseResourceAttributes(RELEASE_CHANNEL),
21 + "deployment.environment.name": import.meta.env.DEV ? "development" : "production",
22 "service.runtime": "t3-web",
23 "t3code.client.surface": isElectron ? "desktop" : "web",
24 "service.version": APP_VERSION,
apps/web/src/vite-env.d.ts
-1
@@ -7,7 +7,6 @@ interface ImportMetaEnv {
7 readonly VITE_WS_URL: string;
8 readonly VITE_HOSTED_APP_URL: string;
9 readonly VITE_HOSTED_APP_CHANNEL: string;
10 - readonly VITE_RELEASE_CHANNEL: string;
10 readonly VITE_CLERK_PUBLISHABLE_KEY: string;
11 readonly VITE_CLERK_JWT_TEMPLATE: string;
12 readonly VITE_CLERK_CLI_OAUTH_CLIENT_ID: string;
apps/web/vite.config.ts
-3
@@ -39,8 +39,6 @@ const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() ||
39 const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
40 const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
41 const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
42 -const configuredReleaseChannel =
43 - process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || "";
42 const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
43 const configuredDesktopUpdateRepository =
44 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
@@ -239,7 +237,6 @@ export default defineConfig(() => {
237 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
238 configuredDesktopUpdateRepository,
239 ),
242 - "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel),
240 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
241 },
242 resolve: {
docs/operations/observability.md
+3 -17
@@ -393,14 +393,12 @@ Traces are best for one request. Metrics are best for trends.
393 Good metric families to watch:
394
395 - `t3_rpc_request_duration`
396 -- `t3_orchestration_command_duration`
396 - `t3_provider_turn_duration` (how long the provider adapter takes to start a turn, not the turn's run time)
397 - `t3_git_command_duration`
398
399 Counters tell you volume and failure rate:
400
401 - `t3_rpc_requests_total`
403 -- `t3_orchestration_commands_total`
402 - `t3_provider_turns_total`
403 - `t3_git_commands_total`
404
@@ -627,27 +625,15 @@ with a startup warning, rather than sending it to the Settings endpoint.
625 Service names are fixed: `t3code-server` for the backend and `t3code-desktop` for the desktop main
626 process, both in `service.namespace` `t3code`. `OTEL_SERVICE_NAME` and a `service.name` or
627 `service.namespace` in `OTEL_RESOURCE_ATTRIBUTES` are ignored. Tell installations apart with other
630 -resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=staging`.
631 -
632 -Each process reports its own build, not the one it talks to: the server, the desktop main process,
633 -the UI, and the mobile app each carry `t3code.release.channel` (`dev`, `stable`, `nightly`, or
634 -`preview`, from their own version; desktop PR builds count as `preview`, and a server not built by a
635 -release workflow reports `dev`) and `deployment.environment.name` (`development`, `production`, or
636 -`staging` for `preview`). On the server and the desktop main process either key in
637 -`OTEL_RESOURCE_ATTRIBUTES` wins. The UI and mobile app never read that variable: Vercel PR previews
638 -set `VITE_RELEASE_CHANNEL=preview` because their `APP_VERSION` must stay comparable with the
639 -server's, and the mobile app maps its build variant (`development`, `preview`, `production`), or
640 -reports `dev` from a development bundle.
628 +resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development`.
629 +The UI reports `deployment.environment.name` from its build: `development` under the Vite dev server
630 +and `production` otherwise.
631
632 Attributes specific to T3 Code use the `t3code.` prefix. The UI runs as `t3code-web` in both a
633 browser and the desktop window, since it is the same code, and `t3code.client.surface` is `desktop`
634 or `web`. The server's `t3code.server.managed_by` is `desktop` when the desktop app launched it and
635 `standalone` otherwise.
636
647 -Every resource also carries a `service.instance.id`: random per process for the server and desktop,
648 -per page load for the UI, and the Expo session on mobile. A `service.instance.id` in
649 -`OTEL_RESOURCE_ATTRIBUTES` replaces the generated one on the server and desktop.
650 -
637 If the OTLP URLs are unset, local tracing still works, metrics stay in-process only, and logs stay
638 on stdout only.
639
oxlint-plugin-t3code/index.ts
-2
@@ -15,7 +15,6 @@ import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-e
15 import noAmbiguousDetailNavigation from "./rules/no-ambiguous-detail-navigation.ts";
16 import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts";
17 import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
18 -import reactEffectBudget from "./rules/react-effect-budget.ts";
18 import requireRegisteredListScroll from "./rules/require-registered-list-scroll.ts";
19 import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";
20 import noPollingLoopInTests from "./rules/no-polling-loop-in-tests.ts";
@@ -53,7 +52,6 @@ export default definePlugin({
52 "no-ambiguous-detail-navigation": noAmbiguousDetailNavigation,
53 "no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals,
54 "no-native-title-tooltip": noNativeTitleTooltip,
56 - "react-effect-budget": reactEffectBudget,
55 "require-registered-list-scroll": requireRegisteredListScroll,
56 "no-outset-state-indicators": noOutsetStateIndicators,
57 "no-polling-loop-in-tests": noPollingLoopInTests,
oxlint-plugin-t3code/rules/react-effect-budget.test.ts deleted
-50
@@ -1,50 +0,0 @@
1 -import { assert, describe } from "@effect/vitest";
2 -
3 -import budget from "../../scripts/effect-budget.json" with { type: "json" };
4 -import { createOxlintRuleHarness } from "../test/utils.ts";
5 -
6 -const [budgetedFile, allowed] = Object.entries(budget)[0]!;
7 -
8 -const component = (effects: number) => `import React, { useEffect } from "react";
9 -export function Panel() {
10 -${Array.from({ length: effects }, (_, index) => (index % 2 === 0 ? " useEffect(() => {}, []);" : " React.useLayoutEffect(() => {});")).join("\n")}
11 - return null;
12 -}
13 -`;
14 -
15 -const reports = (output: string) => output.match(/t3code\(react-effect-budget\)/g)?.length ?? 0;
16 -const lint = (filename: string) =>
17 - createOxlintRuleHarness("t3code/react-effect-budget", { filename });
18 -
19 -const budgeted = lint(budgetedFile);
20 -const unbudgeted = lint("apps/web/src/NotInTheBudget.tsx");
21 -
22 -describe("t3code/react-effect-budget", () => {
23 - budgeted.valid("passes a file at its budget", component(allowed));
24 -
25 - budgeted.invalid("reports only the calls past the budget", component(allowed + 2), (output) => {
26 - assert.strictEqual(reports(output), 2);
27 - assert.include(output, `has ${allowed + 2} React effects against a budget of ${allowed}`);
28 - });
29 -
30 - unbudgeted.invalid(
31 - "gives a file without an entry a budget of 0, counting member calls",
32 - `export function New() { React.useEffect(() => {}); return null; }`,
33 - (output) => {
34 - assert.strictEqual(reports(output), 1);
35 - assert.include(output, "has 1 React effect against a budget of 0");
36 - },
37 - );
38 -
39 - unbudgeted.valid(
40 - "ignores comments, strings and lookalike names",
41 - `// useEffect(() => {}) in a comment
42 -/* React.useLayoutEffect(() => {}) */
43 -const label = "useEffect(() => {})";
44 -const pipeline = Effect.matchCauseEffect(effect, {});
45 -const alias = useEffect;
46 -`,
47 - );
48 -
49 - lint("apps/web/src/Panel.test.tsx").valid("skips test files", component(3));
50 -});
oxlint-plugin-t3code/rules/react-effect-budget.ts deleted
-58
@@ -1,58 +0,0 @@
1 -import { defineRule, type ESTree } from "@oxlint/plugins";
2 -import * as Option from "effect/Option";
3 -
4 -import budget from "../../scripts/effect-budget.json" with { type: "json" };
5 -import { getPropertyName, unwrapExpression } from "../utils.ts";
6 -
7 -const BUDGET_FILE = "scripts/effect-budget.json";
8 -const EFFECT_HOOKS = new Set(["useEffect", "useLayoutEffect", "useInsertionEffect"]);
9 -const EFFECT_HOOK_TEXT = /use(?:Layout|Insertion)?Effect/;
10 -const UNBUDGETED_FILE = /\.test\.[cm]?[jt]sx?$|[\\/](?:test|__tests__)[\\/]/;
11 -const budgets: Readonly<Record<string, number>> = budget;
12 -
13 -const isEffectHookCall = (node: ESTree.CallExpression): boolean => {
14 - const callee = unwrapExpression(node.callee);
15 - if (Option.isNone(callee)) return false;
16 - const expression = callee.value;
17 - if (expression.type === "Identifier") return EFFECT_HOOKS.has(expression.name);
18 - if (expression.type === "MemberExpression" && !expression.computed) {
19 - return Option.exists(getPropertyName(expression.property), (name) => EFFECT_HOOKS.has(name));
20 - }
21 - return false;
22 -};
23 -
24 -// Budget keys are repo-relative; matching on the path's end also works for files linted elsewhere.
25 -const budgetFor = (filename: string): number => {
26 - const normalized = filename.replaceAll("\\", "/");
27 - const key = Object.keys(budgets).find((file) => normalized.endsWith(`/${file}`));
28 - return key === undefined ? 0 : budgets[key]!;
29 -};
30 -
31 -export default defineRule({
32 - meta: {
33 - type: "suggestion",
34 - docs: {
35 - description: `Hold each file to the React effect hooks it is allowed in ${BUDGET_FILE}; a missing entry allows none.`,
36 - },
37 - },
38 - create(context) {
39 - if (UNBUDGETED_FILE.test(context.filename) || !EFFECT_HOOK_TEXT.test(context.sourceCode.text)) {
40 - return {};
41 - }
42 - const calls: Array<ESTree.CallExpression> = [];
43 - return {
44 - CallExpression(node) {
45 - if (isEffectHookCall(node)) calls.push(node);
46 - },
47 - "Program:exit"() {
48 - const allowed = budgetFor(context.filename);
49 - if (calls.length <= allowed) return;
50 - const message =
51 - `This file has ${calls.length} React ${calls.length === 1 ? "effect" : "effects"} against a budget of ${allowed}. ` +
52 - "Prefer deriving in render, event handlers, a `key` reset, an element-owned ref callback, or a store. " +
53 - `If an effect is genuinely right, raise this file's entry in ${BUDGET_FILE} in the same PR.`;
54 - for (const node of calls.slice(allowed)) context.report({ node, message });
55 - },
56 - };
57 - },
58 -});
package.json
+1
@@ -33,6 +33,7 @@
33 "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts",
34 "lint:mobile": "node scripts/mobile-native-static-check.ts",
35 "mobile:install": "node scripts/mobile-native-client.ts ensure",
36 + "mobile:e2e": "node scripts/mobile-e2e.ts",
37 "test": "vp run -r test",
38 "test:cached": "node scripts/test-cached.ts",
39 "test:perf:v2-wire": "vp test run apps/server/src/orchestration-v2/WireProjection.test.ts apps/server/src/orchestration-v2/threadHistoryPaging.test.ts apps/server/src/orchestration-v2/ThreadStream.test.ts apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts apps/server/src/orchestration-v2/ShellStream.test.ts apps/server/src/orchestration-v2/CommandPolicy.test.ts apps/server/src/orchestration-v2/runtimeLayer.test.ts apps/server/src/ws.test.ts packages/contracts/src/orchestrationV2.test.ts packages/client-runtime/src/operations/commands.test.ts packages/client-runtime/src/operations/commands.performance.test.ts packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts packages/client-runtime/src/state/threadHistoryController.test.ts packages/client-runtime/src/state/threadHistoryMerge.test.ts packages/client-runtime/src/state/threads-sync.test.ts packages/client-runtime/src/state/shellReducer.test.ts",
packages/client-runtime/src/rpc/session.ts
+2 -7
@@ -170,11 +170,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
170 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
171 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
172 };
173 - // Config state merges the snapshots it fetches back in, so no subscriber needs them broadcast.
174 - const onDemandSnapshots = (input: ServerConfigSubscriptionInput) => ({
175 - ...input,
176 - workspaceSnapshotsOnDemand: true,
177 - });
173
174 const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
175 const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct";
@@ -253,7 +248,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
248 detail: `${connection.label} config subscription ended.`,
249 });
250 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
256 - onDemandSnapshots(serverConfigInput),
251 + serverConfigInput,
252 ).pipe(
253 Stream.runForEach((event) =>
254 Effect.gen(function* () {
@@ -392,7 +387,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
387 Effect.as(
388 Equal.equals(input, serverConfigInput)
389 ? serverConfigEvents
395 - : protocolClient[WS_METHODS.subscribeServerConfig](onDemandSnapshots(input)),
390 + : protocolClient[WS_METHODS.subscribeServerConfig](input),
391 ),
392 ),
393 );
packages/client-runtime/src/state/server.test.ts
-84
@@ -1,6 +1,5 @@
1 import {
2 EnvironmentId,
3 - ProviderInstanceId,
3 ServerObservability,
4 EnvironmentThemeId,
5 UsageLimitSourceId,
@@ -40,8 +39,6 @@ import {
39 makeEnvironmentServerWelcomeState,
40 makeEnvironmentServerConfigState,
41 isLegacyUpdateHandoffLoss,
43 - recordFetchedWorkspaceSnapshot,
44 - withFetchedWorkspaceSnapshots,
42 matchesServerUpdateReadyEvent,
43 matchesServerUpdateResumeEvent,
44 nudgeReconnectDuringUpdateRestart,
@@ -940,87 +937,6 @@ describe("server state projection", () => {
937 ).toBe(live);
938 });
939
943 - it("merges fetched workspace snapshots only from servers that omit them", () => {
944 - const claude = ProviderInstanceId.make("claudeAgent");
945 - const codex = ProviderInstanceId.make("codex");
946 - const snapshot = (cwd: string, command: string) => ({
947 - cwd,
948 - checkedAt: "2026-10-25T00:00:00.000Z",
949 - slashCommands: [{ name: command }],
950 - skills: [],
951 - });
952 - const provider = (
953 - instanceId: ProviderInstanceId,
954 - workspaceSnapshots?: ReadonlyArray<ReturnType<typeof snapshot>>,
955 - slashCommands: ReadonlyArray<{ readonly name: string }> = [],
956 - ) =>
957 - ({
958 - instanceId,
959 - enabled: true,
960 - slashCommands,
961 - skills: [],
962 - ...(workspaceSnapshots ? { workspaceSnapshots } : {}),
963 - }) as unknown as ServerConfig["providers"][number];
964 - const configWith = (onDemand: boolean, providers: ServerConfig["providers"]) =>
965 - ({
966 - ...CONFIG,
967 - environment: { capabilities: { providerWorkspaceSnapshotsOnDemand: onDemand } },
968 - providers,
969 - }) as unknown as ServerConfig;
970 - const claudeA = snapshot("/a", "claude");
971 - const record = (
972 - current: Parameters<typeof recordFetchedWorkspaceSnapshot>[0],
973 - instanceId: ProviderInstanceId,
974 - fresh: boolean,
975 - reply: ServerConfig["providers"],
976 - ) =>
977 - recordFetchedWorkspaceSnapshot(
978 - current,
979 - { instanceId, cwd: "/a", fresh },
980 - reply,
981 - provider(instanceId),
982 - );
983 -
984 - let fetched = record([], claude, false, [provider(claude, [claudeA])]);
985 - fetched = record(fetched, codex, false, [provider(codex, [snapshot("/a", "codex")])]);
986 - const merged = withFetchedWorkspaceSnapshots(
987 - configWith(true, [provider(claude), provider(codex)]),
988 - fetched,
989 - );
990 - expect(merged.providers[0]?.workspaceSnapshots).toEqual([claudeA]);
991 - // An unchanged answer keeps the cache, so config readers do not re-render.
992 - expect(
993 - record(fetched, claude, false, [
994 - provider(claude, [JSON.parse(JSON.stringify(claudeA)) as typeof claudeA]),
995 - ]),
996 - ).toBe(fetched);
997 -
998 - // Health checks and usage updates leave the snapshot in place.
999 - expect(
1000 - withFetchedWorkspaceSnapshots(
1001 - configWith(true, [
1002 - { ...provider(claude), checkedAt: "2026-10-25T00:09:00.000Z", usageLimits: {} },
1003 - ] as unknown as ServerConfig["providers"]),
1004 - fetched,
1005 - ).providers[0]?.workspaceSnapshots,
1006 - ).toEqual([claudeA]);
1007 -
1008 - // New provider-wide commands, such as a live session's, retire the old snapshot.
1009 - expect(
1010 - withFetchedWorkspaceSnapshots(
1011 - configWith(true, [provider(claude, undefined, [{ name: "live" }])]),
1012 - fetched,
1013 - ).providers[0]?.workspaceSnapshots,
1014 - ).toBeUndefined();
1015 -
1016 - // Older servers send every snapshot and every drop; their config stands.
1017 - const legacy = configWith(false, [provider(claude)]);
1018 - expect(withFetchedWorkspaceSnapshots(legacy, fetched)).toBe(legacy);
1019 -
1020 - // A fresh scan drops the cwd's other provider snapshots, as the server does.
1021 - expect(record(fetched, claude, true, [])).toEqual([]);
1022 - });
1023 -
940 it.effect("starts from cached configuration and persists the live projection", () =>
941 Effect.gen(function* () {
942 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
packages/client-runtime/src/state/server.ts
+1 -129
@@ -1,11 +1,9 @@
1 import {
2 type EnvironmentId,
3 - type ProviderInstanceId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 type ServerLifecycleStreamReadyEvent,
8 - type ServerProviderWorkspaceSnapshot,
7 type ServerSelfUpdateProgressEvent,
8 type ServerSelfUpdateResult,
9 shouldRecommendDatabaseCompaction,
@@ -13,7 +11,6 @@ import {
11 } from "@t3tools/contracts";
12 import * as Cause from "effect/Cause";
13 import * as Duration from "effect/Duration";
16 -import * as Equal from "effect/Equal";
14 import * as Deferred from "effect/Deferred";
15 import * as Effect from "effect/Effect";
16 import * as Exit from "effect/Exit";
@@ -45,7 +42,6 @@ import { runCachePersistence } from "./cachePersistence.ts";
42 import {
43 isRpcClientError,
44 request,
48 - requestGuarded,
45 runStream,
46 subscribe,
47 subscribeDynamicWithSession,
@@ -55,7 +51,6 @@ import type { RpcSession } from "../rpc/session.ts";
51 import { followStreamInEnvironment } from "./runtime.ts";
52 import {
53 applyServerConfigProjection,
58 - reuseUnchanged,
54 type ServerConfigProjection,
55 withoutEnvironmentThemes,
56 } from "./serverConfigProjection.ts";
@@ -653,92 +648,6 @@ export function resolveServerConfigValue(
648 return initialConfig ?? projection?.config ?? null;
649 }
650
656 -type ServerProviderEntry = ServerConfig["providers"][number];
657 -
658 -/**
659 - * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, or a
660 - * /usage-limits change shows up here, so a snapshot fetched before it no longer applies.
661 - */
662 -const snapshotBasis = (provider: ServerProviderEntry | undefined) =>
663 - provider && {
664 - enabled: provider.enabled,
665 - slashCommands: provider.slashCommands,
666 - skills: provider.skills,
667 - };
668 -
669 -interface FetchedWorkspaceSnapshot {
670 - readonly instanceId: ProviderInstanceId;
671 - readonly snapshot: ServerProviderWorkspaceSnapshot;
672 - readonly basis: ReturnType<typeof snapshotBasis>;
673 -}
674 -
675 -const MAX_FETCHED_WORKSPACE_SNAPSHOTS = 32;
676 -
677 -/**
678 - * Servers with `providerWorkspaceSnapshotsOnDemand` leave per-cwd snapshots out of the config,
679 - * so the ones this client fetched are merged back in. Older servers send every snapshot and
680 - * their drops, so their config is used as is.
681 - */
682 -export function withFetchedWorkspaceSnapshots(
683 - config: ServerConfig,
684 - fetched: ReadonlyArray<FetchedWorkspaceSnapshot>,
685 -): ServerConfig {
686 - if (
687 - fetched.length === 0 ||
688 - config.environment.capabilities.providerWorkspaceSnapshotsOnDemand !== true
689 - ) {
690 - return config;
691 - }
692 - return {
693 - ...config,
694 - providers: config.providers.map((provider) => {
695 - // A dropped snapshot reads as lost, and the composer fetches it again.
696 - const own = fetched.filter(
697 - (entry) =>
698 - entry.instanceId === provider.instanceId &&
699 - Equal.equals(entry.basis, snapshotBasis(provider)),
700 - );
701 - return own.length === 0
702 - ? provider
703 - : { ...provider, workspaceSnapshots: own.map((entry) => entry.snapshot) };
704 - }),
705 - };
706 -}
707 -
708 -export function recordFetchedWorkspaceSnapshot(
709 - current: ReadonlyArray<FetchedWorkspaceSnapshot>,
710 - input: { readonly instanceId: ProviderInstanceId; readonly cwd: string; readonly fresh: boolean },
711 - providers: ServerConfig["providers"],
712 - configProvider: ServerProviderEntry | undefined,
713 -): ReadonlyArray<FetchedWorkspaceSnapshot> {
714 - const basis = snapshotBasis(configProvider);
715 - const snapshot = providers
716 - .find((provider) => provider.instanceId === input.instanceId)
717 - ?.workspaceSnapshots?.find((candidate) => candidate.cwd === input.cwd);
718 - const stored = current.find(
719 - (entry) => entry.instanceId === input.instanceId && entry.snapshot.cwd === input.cwd,
720 - );
721 - // A cached answer from the server would otherwise re-render every config reader.
722 - if (
723 - !input.fresh &&
724 - snapshot &&
725 - stored &&
726 - Equal.equals(stored.snapshot, snapshot) &&
727 - Equal.equals(stored.basis, basis)
728 - ) {
729 - return current;
730 - }
731 - // A fresh scan drops the cwd's snapshots for every provider, as the server does.
732 - const kept = current.filter(
733 - (entry) =>
734 - entry.snapshot.cwd !== input.cwd || (!input.fresh && entry.instanceId !== input.instanceId),
735 - );
736 - if (!snapshot) return kept.length === current.length ? current : kept;
737 - return [...kept, { instanceId: input.instanceId, snapshot, basis }].slice(
738 - -MAX_FETCHED_WORKSPACE_SNAPSHOTS,
739 - );
740 -}
741 -
651 export function createServerEnvironmentAtoms<R, E>(
652 runtime: Atom.AtomRuntime<
653 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
@@ -777,12 +686,6 @@ export function createServerEnvironmentAtoms<R, E>(
686 readonly environmentId: EnvironmentId;
687 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
688 }) => configProjectionFamily(target.environmentId);
780 - const fetchedWorkspaceSnapshotsAtom = Atom.family((environmentId: EnvironmentId) =>
781 - Atom.make<ReadonlyArray<FetchedWorkspaceSnapshot>>([]).pipe(
782 - Atom.keepAlive,
783 - Atom.withLabel(`environment-data:server:fetched-workspace-snapshots:${environmentId}`),
784 - ),
785 - );
689 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
690 Atom.withLabel("environment-data:server:config:empty"),
691 );
@@ -790,24 +693,14 @@ export function createServerEnvironmentAtoms<R, E>(
693 if (environmentId === null) {
694 return emptyConfigAtom;
695 }
793 - let previousProviders: ServerConfig["providers"] | undefined;
696 return Atom.make((get): ServerConfig | null => {
697 const projection = Option.getOrNull(
698 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
699 );
798 - const config = resolveServerConfigValue(
700 + return resolveServerConfigValue(
701 projection,
702 get(options.initialConfigValueAtom(environmentId)),
703 );
802 - if (config === null) return null;
803 - const merged = withFetchedWorkspaceSnapshots(
804 - config,
805 - get(fetchedWorkspaceSnapshotsAtom(environmentId)),
806 - );
807 - if (merged === config) return config;
808 - // Keep provider identities stable across config events; the projection already reuses the rest.
809 - previousProviders = reuseUnchanged(previousProviders, merged.providers);
810 - return { ...merged, providers: previousProviders };
704 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
705 });
706 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
@@ -1334,27 +1227,6 @@ export function createServerEnvironmentAtoms<R, E>(
1227 refreshProviders: createEnvironmentRpcCommand(runtime, {
1228 label: "environment-data:server:refresh-providers",
1229 tag: WS_METHODS.serverRefreshProviders,
1337 - execute: (input) =>
1338 - requestGuarded(WS_METHODS.serverRefreshProviders, {
1339 - ...input,
1340 - workspaceSnapshotsOnDemand: true,
1341 - ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
1342 - }),
1343 - onSuccess: ({ environmentId, input }, registry, result) =>
1344 - Effect.sync(() => {
1345 - const { instanceId, cwd } = input;
1346 - if (instanceId === undefined || cwd === undefined) return;
1347 - registry.update(fetchedWorkspaceSnapshotsAtom(environmentId), (current) =>
1348 - recordFetchedWorkspaceSnapshot(
1349 - current,
1350 - { instanceId, cwd, fresh: input.fresh === true },
1351 - result.providers,
1352 - registry
1353 - .get(configValueAtom(environmentId))
1354 - ?.providers.find((provider) => provider.instanceId === instanceId),
1355 - ),
1356 - );
1357 - }),
1230 concurrency: {
1231 mode: "singleFlight",
1232 key: ({ environmentId, input }) =>
packages/contracts/src/environment.ts
-2
@@ -102,8 +102,6 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
102 /** Clear published themes when absent; older servers never send updates. */
103 environmentThemes: Schema.optionalKey(Schema.Boolean),
104 usageLimitSources: Schema.optionalKey(Schema.Boolean),
105 - /** Honors `workspaceSnapshotsOnDemand`; older servers send every snapshot and drop them in the stream. */
106 - providerWorkspaceSnapshotsOnDemand: Schema.optionalKey(Schema.Boolean),
105 usagePriceOverrides: Schema.optionalKey(Schema.Boolean),
106 usageModelAliases: Schema.optionalKey(Schema.Boolean),
107 threadPinning: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/rpc.ts
+1 -11
@@ -612,21 +612,13 @@ const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {
612 error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),
613 });
614
615 -export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {
615 +const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {
616 payload: Schema.Struct({
617 instanceId: Schema.optional(ProviderInstanceId),
618 cwd: Schema.optional(TrimmedNonEmptyString),
619 fresh: Schema.optional(Schema.Boolean),
620 /** Bypass model caches; explicit rediscovery may open sessions, background refreshes must not. */
621 refreshModels: Schema.optional(Schema.Boolean),
622 - /**
623 - * Reply without snapshots, or with only the requested instance's cwd snapshot. Snapshots then
624 - * reach the client only through these replies, so another client's scan shows on its next
625 - * refresh, at most one TTL later.
626 - */
627 - workspaceSnapshotsOnDemand: Schema.optional(Schema.Boolean),
628 - /** As on `subscribeServerConfig`: add /usage-limits to the replied snapshot. */
629 - usageLimitsCommand: Schema.optional(Schema.Boolean),
622 }),
623 success: ServerProviderUpdatedPayload,
624 error: Schema.Union([EnvironmentAuthorizationError, ProviderSetupError]),
@@ -1799,8 +1791,6 @@ export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerCon
1791 usageLimitSources: Schema.optional(Schema.Boolean),
1792 /** Advertise client handling before the server offers /usage-limits, or older clients send it as a prompt. */
1793 usageLimitsCommand: Schema.optional(Schema.Boolean),
1802 - /** Omit per-cwd provider snapshots; the client fetches its cwd through `server.refreshProviders`. */
1803 - workspaceSnapshotsOnDemand: Schema.optional(Schema.Boolean),
1794 }),
1795 success: ServerConfigStreamEvent,
1796 error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),
packages/provider-grok/src/server/status.ts
+7 -8
@@ -527,12 +527,6 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
527 discoveredModels.length > 0
528 ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
529 : fallbackModels;
530 - // The registry replaces cached models on a ready probe, so a fallback-only list must not be ready.
531 - const incompleteMessage = acpFailed
532 - ? "Grok CLI is installed but ACP initialize failed. Model options may be incomplete."
533 - : discoveredModels.length === 0
534 - ? "Grok CLI did not list any models. Model options may be incomplete."
535 - : undefined;
530
531 if (auth.status === "unauthenticated") {
532 return buildServerProvider({
@@ -561,9 +555,14 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
555 probe: {
556 installed: true,
557 version,
564 - status: incompleteMessage ? "warning" : "ready",
558 + status: acpFailed ? "warning" : "ready",
559 auth,
566 - ...(incompleteMessage ? { message: incompleteMessage } : {}),
560 + ...(acpFailed
561 + ? {
562 + message:
563 + "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",
564 + }
565 + : {}),
566 },
567 });
568 });
packages/shared/package.json
-4
@@ -59,10 +59,6 @@
59 "types": "./src/logging.ts",
60 "import": "./src/logging.ts"
61 },
62 - "./releaseResource": {
63 - "types": "./src/releaseResource.ts",
64 - "import": "./src/releaseResource.ts"
65 - },
62 "./observability": {
63 "types": "./src/observability.ts",
64 "import": "./src/observability.ts"
packages/shared/src/observability.test.ts
-8
@@ -24,16 +24,8 @@ import {
24 type TraceRecord,
25 OtlpHeadersFromString,
26 truncateTraceAttributes,
27 - processServiceInstanceId,
27 } from "./observability.ts";
28
30 -describe("processServiceInstanceId", () => {
31 - it("stays the same for the process unless the operator set one", () => {
32 - expect(processServiceInstanceId()).toBe(processServiceInstanceId({}));
33 - expect(processServiceInstanceId({ "service.instance.id": "pod-7" })).toBe("pod-7");
34 - });
35 -});
36 -
29 describe("errorTag", () => {
30 it("reports structural tags without retaining arbitrary values", () => {
31 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
packages/shared/src/observability.ts
-15
@@ -26,21 +26,6 @@ export interface SignalExport {
26 readonly exportIntervalMs: number;
27 }
28
29 -let generatedServiceInstanceId: string | undefined;
30 -
31 -/**
32 - * `service.instance.id` shared by every resource this process exports. Effect lets code
33 - * attributes beat `OTEL_RESOURCE_ATTRIBUTES`, so callers pass the operator's in to keep it winning.
34 - */
35 -export const processServiceInstanceId = (
36 - operatorAttributes: Readonly<Record<string, string>> = {},
37 -): string => {
38 - if (operatorAttributes["service.instance.id"]) return operatorAttributes["service.instance.id"];
39 - // @effect-diagnostics-next-line cryptoRandomUUID:off -- Resources are built synchronously, outside any Effect.
40 - generatedServiceInstanceId ??= crypto.randomUUID();
41 - return generatedServiceInstanceId;
42 -};
43 -
29 export const DEFAULT_SIGNAL_EXPORT: SignalExport = {
30 protocol: "http/json",
31 headers: undefined,
packages/shared/src/relayTracing.ts
-4
@@ -18,10 +18,8 @@ export interface RelayClientTracingResource {
18 readonly serviceName: string;
19 readonly serviceVersion?: string;
20 readonly runtime: string;
21 - readonly serviceInstanceId: string;
21 readonly client: string;
22 readonly component?: string;
24 - readonly attributes?: Readonly<Record<string, string>> | undefined;
23 }
24
25 export class RelayClientTracer extends Context.Reference(
@@ -167,11 +165,9 @@ export function layer(
165 serviceVersion: resource.serviceVersion,
166 attributes: {
167 "service.namespace": "t3code",
170 - "service.instance.id": resource.serviceInstanceId,
168 "service.runtime": resource.runtime,
169 "t3code.component": resource.component ?? "relay-client",
170 "t3code.client.surface": resource.client,
174 - ...resource.attributes,
171 },
172 },
173 }).pipe(Layer.provide(OtlpSerialization.layerJson));
packages/shared/src/releaseResource.test.ts deleted
-35
@@ -1,35 +0,0 @@
1 -import { describe, expect, it } from "@effect/vitest";
2 -
3 -import { releaseChannelOf, releaseResourceAttributes } from "./releaseResource.ts";
4 -
5 -describe("releaseResourceAttributes", () => {
6 - it.each([
7 - ["dev", {}, "dev", "development"],
8 - ["stable", {}, "stable", "production"],
9 - ["nightly", {}, "nightly", "production"],
10 - ["preview", {}, "preview", "staging"],
11 - [
12 - "stable",
13 - { "deployment.environment.name": "staging", "t3code.release.channel": "" },
14 - "stable",
15 - "staging",
16 - ],
17 - ] as const)(
18 - "%s (operator: %o) reports %s in %s",
19 - (channel, operatorAttributes, expectedChannel, environment) => {
20 - expect(releaseResourceAttributes(channel, operatorAttributes)).toEqual({
21 - "t3code.release.channel": expectedChannel,
22 - "deployment.environment.name": environment,
23 - });
24 - },
25 - );
26 -
27 - it.each([
28 - ["0.1.2", "stable"],
29 - ["0.1.2-nightly.20261025.1", "nightly"],
30 - ["0.1.2-preview.20261025.1", "preview"],
31 - ["0.1.2-pr.24340.123", "preview"],
32 - ] as const)("classifies %s as %s", (version, channel) => {
33 - expect(releaseChannelOf(version)).toBe(channel);
34 - });
35 -});
packages/shared/src/releaseResource.ts deleted
-24
@@ -1,24 +0,0 @@
1 -import { type CliReleaseChannel, cliReleaseChannelOf } from "./cliRelease.ts";
2 -
3 -export type ReleaseChannel = "dev" | CliReleaseChannel;
4 -
5 -// Desktop PR preview builds are stamped `X.Y.Z-pr.<number>.<run>`; the CLI updater must not see them as preview.
6 -export const releaseChannelOf = (version: string): ReleaseChannel =>
7 - /-pr\.\d+\.\d+$/.test(version) ? "preview" : cliReleaseChannelOf(version);
8 -
9 -// Effect lets code attributes beat OTEL_RESOURCE_ATTRIBUTES, so the operator value is applied here.
10 -export const releaseResourceAttributes = (
11 - channel: ReleaseChannel,
12 - operatorAttributes: Readonly<Record<string, unknown>> = {},
13 -) => {
14 - const operatorValue = (key: string) => {
15 - const value = operatorAttributes[key];
16 - return typeof value === "string" && value !== "" ? value : undefined;
17 - };
18 - return {
19 - "t3code.release.channel": operatorValue("t3code.release.channel") ?? channel,
20 - "deployment.environment.name":
21 - operatorValue("deployment.environment.name") ??
22 - (channel === "dev" ? "development" : channel === "preview" ? "staging" : "production"),
23 - };
24 -};
pnpm-lock.yaml
+15
@@ -2157,6 +2157,9 @@ importers:
2157 '@t3tools/tailscale':
2158 specifier: workspace:*
2159 version: link:../packages/tailscale
2160 + agent-device:
2161 + specifier: 0.21.25
2162 + version: 0.21.25
2163 effect:
2164 specifier: 4.0.5
2165 version: 4.0.5
@@ -7150,6 +7153,16 @@ packages:
7153 engines: {node: '>=18.18'}
7154 hasBin: true
7155
7156 + agent-device@0.21.25:
7157 + resolution: {integrity: sha512-JFmAD5AqM03dVU6BVQW1DQ2Kz+MThmbCYBbDxpGw2lka91LcoXHdrb4IjF9NNg4DEQUu41Pg8WnB/7crM3ig2w==}
7158 + engines: {node: '>=22.12'}
7159 + hasBin: true
7160 + peerDependencies:
7161 + ai: ^6.0.0 || ^7.0.0
7162 + peerDependenciesMeta:
7163 + ai:
7164 + optional: true
7165 +
7166 agent-install@0.0.5:
7167 resolution: {integrity: sha512-nHlms9BkP8ZiY79HrwCGiA2DcNaXrAaJrCM/BEqQ7MEsSKyCk+2A76xPGylIfASZSZE0SaU3T0bNSg4rBPIJAQ==}
7168 hasBin: true
@@ -16988,6 +17001,8 @@ snapshots:
17001
17002 agent-cli-detector@0.1.7: {}
17003
17004 + agent-device@0.21.25: {}
17005 +
17006 agent-install@0.0.5:
17007 dependencies:
17008 '@iarna/toml': 2.2.5
scripts/effect-budget.json deleted
-433
@@ -1,433 +0,0 @@
1 -{
2 - "apps/mobile/src/App.tsx": 2,
3 - "apps/mobile/src/Stack.tsx": 1,
4 - "apps/mobile/src/components/ComposerAttachmentStrip.tsx": 2,
5 - "apps/mobile/src/components/ComposerContextAttachment.tsx": 1,
6 - "apps/mobile/src/components/ComposerEditor.tsx": 2,
7 - "apps/mobile/src/components/FilePreview.ios.tsx": 1,
8 - "apps/mobile/src/components/FilePreview.tsx": 1,
9 - "apps/mobile/src/components/FilePreviewModal.tsx": 5,
10 - "apps/mobile/src/components/MediaVideoPlayer.tsx": 3,
11 - "apps/mobile/src/components/PdfPreview.android.tsx": 1,
12 - "apps/mobile/src/components/ProjectFavicon.tsx": 1,
13 - "apps/mobile/src/components/VideoPreviewModal.ios.tsx": 6,
14 - "apps/mobile/src/components/VideoPreviewModal.tsx": 3,
15 - "apps/mobile/src/components/VideoThumbnailImage.tsx": 1,
16 - "apps/mobile/src/components/ui/AndroidAnchoredMenu.tsx": 1,
17 - "apps/mobile/src/components/ui/AppBar.android.tsx": 1,
18 - "apps/mobile/src/components/ui/Dialog.android.tsx": 1,
19 - "apps/mobile/src/components/ui/Notice.tsx": 1,
20 - "apps/mobile/src/components/ui/OverlayPortal.tsx": 3,
21 - "apps/mobile/src/components/ui/SliderRow.android.tsx": 1,
22 - "apps/mobile/src/components/ui/SliderRow.tsx": 1,
23 - "apps/mobile/src/components/ui/Toast.tsx": 2,
24 - "apps/mobile/src/features/agent-awareness/notificationNavigation.ts": 3,
25 - "apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx": 2,
26 - "apps/mobile/src/features/browser/PreviewStreamWebView.tsx": 5,
27 - "apps/mobile/src/features/browser/ThreadBrowserFloat.tsx": 2,
28 - "apps/mobile/src/features/cloud/CloudAuthProvider.tsx": 3,
29 - "apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx": 1,
30 - "apps/mobile/src/features/cloud/connectOnboardingNavigation.ts": 1,
31 - "apps/mobile/src/features/cloud/managedRelayState.ts": 1,
32 - "apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx": 5,
33 - "apps/mobile/src/features/connection/PermissionUpdateNotice.tsx": 2,
34 - "apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx": 6,
35 - "apps/mobile/src/features/devices/DeviceStreamWebView.tsx": 2,
36 - "apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx": 1,
37 - "apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts": 3,
38 - "apps/mobile/src/features/files/AttachmentFileScreen.tsx": 1,
39 - "apps/mobile/src/features/files/AudioFilePreview.tsx": 2,
40 - "apps/mobile/src/features/files/FileTreeBrowser.tsx": 3,
41 - "apps/mobile/src/features/files/FilesHeader.tsx": 1,
42 - "apps/mobile/src/features/files/SourceFileSurface.tsx": 1,
43 - "apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx": 1,
44 - "apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx": 1,
45 - "apps/mobile/src/features/files/useFileTreeEntries.ts": 1,
46 - "apps/mobile/src/features/home/HomeRouteScreen.tsx": 2,
47 - "apps/mobile/src/features/home/HomeScreen.tsx": 4,
48 - "apps/mobile/src/features/home/ThreadListToolbar.tsx": 1,
49 - "apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx": 2,
50 - "apps/mobile/src/features/home/home-list-options.ts": 1,
51 - "apps/mobile/src/features/home/home-route-visibility.ts": 1,
52 - "apps/mobile/src/features/home/thread-swipe-actions.tsx": 5,
53 - "apps/mobile/src/features/keyboard/CommandPalette.tsx": 2,
54 - "apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx": 1,
55 - "apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts": 1,
56 - "apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx": 3,
57 - "apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx": 1,
58 - "apps/mobile/src/features/layout/workspace-inspector-pane.tsx": 2,
59 - "apps/mobile/src/features/projects/AddProjectScreen.tsx": 2,
60 - "apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts": 1,
61 - "apps/mobile/src/features/prompt-links/useThreadPromptLink.ts": 1,
62 - "apps/mobile/src/features/pull-requests/PullRequestFilterMenuContext.tsx": 1,
63 - "apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx": 1,
64 - "apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx": 4,
65 - "apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx": 1,
66 - "apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx": 1,
67 - "apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx": 1,
68 - "apps/mobile/src/features/pull-requests/usePullRequestDiff.ts": 1,
69 - "apps/mobile/src/features/pull-requests/usePullRequestEnvironmentFallback.ts": 1,
70 - "apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts": 4,
71 - "apps/mobile/src/features/pull-requests/usePullRequestList.ts": 3,
72 - "apps/mobile/src/features/pull-requests/usePullRequestReviewDraft.ts": 1,
73 - "apps/mobile/src/features/review/ReviewSheet.tsx": 1,
74 - "apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts": 2,
75 - "apps/mobile/src/features/review/useReviewCommentSelectionController.ts": 2,
76 - "apps/mobile/src/features/review/useReviewDiffData.ts": 2,
77 - "apps/mobile/src/features/review/useReviewDiffPrewarming.ts": 1,
78 - "apps/mobile/src/features/review/useReviewSections.ts": 5,
79 - "apps/mobile/src/features/settings/OutdatedServerUpdateSection.tsx": 1,
80 - "apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx": 1,
81 - "apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx": 2,
82 - "apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx": 1,
83 - "apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx": 1,
84 - "apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx": 2,
85 - "apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx": 1,
86 - "apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx": 2,
87 - "apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx": 2,
88 - "apps/mobile/src/features/settings/components/BranchNamingSettings.tsx": 1,
89 - "apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx": 1,
90 - "apps/mobile/src/features/sharing/IncomingShareProvider.tsx": 4,
91 - "apps/mobile/src/features/shortcuts/useAppShortcuts.ts": 4,
92 - "apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx": 11,
93 - "apps/mobile/src/features/terminal/NativeTerminalSurface.tsx": 4,
94 - "apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx": 14,
95 - "apps/mobile/src/features/terminal/terminalLaunchContext.ts": 1,
96 - "apps/mobile/src/features/terminal/useTerminalGridSync.ts": 1,
97 - "apps/mobile/src/features/terminal/useTerminalLifecycle.ts": 1,
98 - "apps/mobile/src/features/threads/ComposerPopoverAnchor.android.tsx": 2,
99 - "apps/mobile/src/features/threads/ComposerPopoverAnchor.tsx": 1,
100 - "apps/mobile/src/features/threads/CopyTextButton.tsx": 1,
101 - "apps/mobile/src/features/threads/CustomSnoozeSheet.android.tsx": 1,
102 - "apps/mobile/src/features/threads/GitActionProgressOverlay.tsx": 1,
103 - "apps/mobile/src/features/threads/HtmlRenderWebView.tsx": 1,
104 - "apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx": 1,
105 - "apps/mobile/src/features/threads/McpAppWebView.tsx": 7,
106 - "apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx": 2,
107 - "apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx": 5,
108 - "apps/mobile/src/features/threads/NewTaskDraftScreen.tsx": 10,
109 - "apps/mobile/src/features/threads/NewTaskRouteScreen.tsx": 1,
110 - "apps/mobile/src/features/threads/QuestionAttachments.tsx": 2,
111 - "apps/mobile/src/features/threads/ThreadAgentsSheet.tsx": 1,
112 - "apps/mobile/src/features/threads/ThreadArrangementSheet.tsx": 3,
113 - "apps/mobile/src/features/threads/ThreadComposer.tsx": 6,
114 - "apps/mobile/src/features/threads/ThreadDetailScreen.tsx": 20,
115 - "apps/mobile/src/features/threads/ThreadFeed.tsx": 14,
116 - "apps/mobile/src/features/threads/ThreadGuestShareBar.tsx": 1,
117 - "apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx": 2,
118 - "apps/mobile/src/features/threads/ThreadMarkdownImage.tsx": 3,
119 - "apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx": 3,
120 - "apps/mobile/src/features/threads/ThreadQueueControl.tsx": 2,
121 - "apps/mobile/src/features/threads/ThreadRouteScreen.tsx": 2,
122 - "apps/mobile/src/features/threads/ThreadScreenHost.tsx": 2,
123 - "apps/mobile/src/features/threads/ThreadSettingsSheet.tsx": 2,
124 - "apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx": 1,
125 - "apps/mobile/src/features/threads/floating-working-control.tsx": 2,
126 - "apps/mobile/src/features/threads/git/GitOverviewSheet.tsx": 1,
127 - "apps/mobile/src/features/threads/new-task-flow-provider.tsx": 6,
128 - "apps/mobile/src/features/threads/thread-inspector-content-stack.tsx": 1,
129 - "apps/mobile/src/features/threads/thread-list-v2-items.tsx": 1,
130 - "apps/mobile/src/features/threads/thread-subagent-group.tsx": 2,
131 - "apps/mobile/src/features/threads/thread-work-log.tsx": 5,
132 - "apps/mobile/src/features/threads/use-composer-command-menu.ts": 5,
133 - "apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts": 2,
134 - "apps/mobile/src/features/threads/use-visible-second-clock.ts": 2,
135 - "apps/mobile/src/features/threads/use-worktree-setup.ts": 1,
136 - "apps/mobile/src/features/threads/useFileChipShare.ts": 2,
137 - "apps/mobile/src/features/usage/UsageLimitsSection.tsx": 1,
138 - "apps/mobile/src/features/usage/UsageRouteScreen.tsx": 1,
139 - "apps/mobile/src/features/voice-input/ComposerDictationControl.tsx": 3,
140 - "apps/mobile/src/features/voice-input/GlobalVoiceInputControl.tsx": 2,
141 - "apps/mobile/src/features/voice-input/VoiceInputProvider.tsx": 4,
142 - "apps/mobile/src/features/voice-input/useVoiceInputController.ts": 1,
143 - "apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx": 1,
144 - "apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx": 1,
145 - "apps/mobile/src/features/workspace/WorkspaceTabsContext.tsx": 1,
146 - "apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx": 1,
147 - "apps/mobile/src/features/workspace/WorkspaceToolbar.tsx": 2,
148 - "apps/mobile/src/lib/attachmentDocument.ts": 4,
149 - "apps/mobile/src/lib/useDelayedStatus.ts": 2,
150 - "apps/mobile/src/lib/useUiRuntimeMemoryWarningGc.ts": 1,
151 - "apps/mobile/src/lib/videoAudioSession.ts": 1,
152 - "apps/mobile/src/native/NativeHeaderToolbar.tsx": 2,
153 - "apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx": 1,
154 - "apps/mobile/src/native/StackHeader.tsx": 2,
155 - "apps/mobile/src/native/T3ComposerEditor.ios.tsx": 2,
156 - "apps/mobile/src/native/T3ComposerEditor.native.tsx": 2,
157 - "apps/mobile/src/native/V5StackHeader.ios.tsx": 1,
158 - "apps/mobile/src/native/useRetryingImageSource.ts": 1,
159 - "apps/mobile/src/state/composer-attachment-uploads.ts": 2,
160 - "apps/mobile/src/state/mediaActions.ts": 1,
161 - "apps/mobile/src/state/olderSettledShelf.ts": 2,
162 - "apps/mobile/src/state/queries.ts": 2,
163 - "apps/mobile/src/state/thread-order.ts": 1,
164 - "apps/mobile/src/state/threads.ts": 1,
165 - "apps/mobile/src/state/use-composer-attachment-actions.ts": 1,
166 - "apps/mobile/src/state/use-composer-drafts.ts": 3,
167 - "apps/mobile/src/state/use-pull-to-refresh.ts": 1,
168 - "apps/mobile/src/state/use-selected-thread-git-actions.ts": 1,
169 - "apps/mobile/src/state/use-selected-thread-requests.ts": 2,
170 - "apps/mobile/src/state/use-thread-composer-state.ts": 3,
171 - "apps/mobile/src/state/use-thread-outbox-drain.ts": 4,
172 - "apps/mobile/src/state/use-thread-pr.ts": 1,
173 - "apps/mobile/src/state/use-vcs-action-state.ts": 1,
174 - "apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx": 1,
175 - "apps/mobile/src/widgets/useSubscriptionUsage.ts": 1,
176 - "apps/web/src/AppRoot.tsx": 1,
177 - "apps/web/src/browser/BrowserProfileReporter.tsx": 1,
178 - "apps/web/src/browser/BrowserSurfaceSlot.tsx": 2,
179 - "apps/web/src/browser/ElectronBrowserHost.tsx": 3,
180 - "apps/web/src/browser/HostedBrowserWebview.tsx": 6,
181 - "apps/web/src/browser/ServerBrowserSurface.tsx": 5,
182 - "apps/web/src/browser/useBrowserViewportResize.ts": 2,
183 - "apps/web/src/cloud/managedAuth.tsx": 2,
184 - "apps/web/src/cloud/managedRelayState.ts": 2,
185 - "apps/web/src/components/AddProjectToMachineDialog.tsx": 1,
186 - "apps/web/src/components/AnimatedHeight.tsx": 2,
187 - "apps/web/src/components/AnimatedWidth.tsx": 1,
188 - "apps/web/src/components/AppSidebarLayout.tsx": 4,
189 - "apps/web/src/components/BackgroundThreadAnnouncer.tsx": 1,
190 - "apps/web/src/components/BranchPicker.tsx": 2,
191 - "apps/web/src/components/BranchToolbar.tsx": 4,
192 - "apps/web/src/components/BranchToolbarBranchSelector.tsx": 1,
193 - "apps/web/src/components/ChatMarkdown.tsx": 1,
194 - "apps/web/src/components/ChatView.tsx": 23,
195 - "apps/web/src/components/CommandPalette.tsx": 5,
196 - "apps/web/src/components/CommandPaletteContent.tsx": 1,
197 - "apps/web/src/components/ComposerPromptEditorTiptap.tsx": 13,
198 - "apps/web/src/components/ConfirmDialogHost.tsx": 1,
199 - "apps/web/src/components/CustomSnoozeDialog.tsx": 1,
200 - "apps/web/src/components/DiffPanel.tsx": 4,
201 - "apps/web/src/components/DiffWorkerPoolProvider.tsx": 2,
202 - "apps/web/src/components/GitActionsControl.tsx": 4,
203 - "apps/web/src/components/HostFreezeToastCoordinator.tsx": 1,
204 - "apps/web/src/components/LegacySidebar.tsx": 5,
205 - "apps/web/src/components/LegacyThreadMigrationToast.tsx": 2,
206 - "apps/web/src/components/PermissionUpdateNotice.tsx": 1,
207 - "apps/web/src/components/PersistentThreadTerminals.tsx": 1,
208 - "apps/web/src/components/ProjectCloneToastCoordinator.tsx": 2,
209 - "apps/web/src/components/PullRequestThreadDialog.tsx": 1,
210 - "apps/web/src/components/QuitHoldOverlay.tsx": 1,
211 - "apps/web/src/components/ReopenClosedViewShortcut.tsx": 2,
212 - "apps/web/src/components/RightPanelTabs.tsx": 5,
213 - "apps/web/src/components/Sidebar.logic.ts": 2,
214 - "apps/web/src/components/Sidebar.pointer.ts": 1,
215 - "apps/web/src/components/Sidebar.tsx": 10,
216 - "apps/web/src/components/SlowRpcRequestToastCoordinator.tsx": 2,
217 - "apps/web/src/components/ThreadNotificationCoordinator.tsx": 5,
218 - "apps/web/src/components/ThreadRouteView.tsx": 5,
219 - "apps/web/src/components/ThreadTerminalDrawer.tsx": 13,
220 - "apps/web/src/components/auth/ConnectAgentSurface.tsx": 1,
221 - "apps/web/src/components/auth/PairingRouteSurface.tsx": 2,
222 - "apps/web/src/components/chat/AgentElapsed.tsx": 1,
223 - "apps/web/src/components/chat/AssistantCitationChip.tsx": 2,
224 - "apps/web/src/components/chat/AssistantCitationSource.tsx": 1,
225 - "apps/web/src/components/chat/AssistantSelectionToolbar.tsx": 2,
226 - "apps/web/src/components/chat/ChangedFilesTree.tsx": 1,
227 - "apps/web/src/components/chat/ChatCanvas.tsx": 1,
228 - "apps/web/src/components/chat/ChatComposer.tsx": 26,
229 - "apps/web/src/components/chat/ChatHeader.tsx": 2,
230 - "apps/web/src/components/chat/ChatMarkdownMedia.tsx": 1,
231 - "apps/web/src/components/chat/ChatOverlayHosts.tsx": 1,
232 - "apps/web/src/components/chat/CommandOutputPanel.tsx": 1,
233 - "apps/web/src/components/chat/ComposerAttachmentStrip.tsx": 1,
234 - "apps/web/src/components/chat/ComposerBannerStack.tsx": 3,
235 - "apps/web/src/components/chat/ComposerCommandMenu.tsx": 1,
236 - "apps/web/src/components/chat/ComposerCommandMenuLayer.tsx": 1,
237 - "apps/web/src/components/chat/ComposerImageThumbnail.tsx": 1,
238 - "apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx": 2,
239 - "apps/web/src/components/chat/ComposerStashMenu.tsx": 2,
240 - "apps/web/src/components/chat/DraftHeroHeadline.tsx": 1,
241 - "apps/web/src/components/chat/DraftHeroProjectHeading.tsx": 1,
242 - "apps/web/src/components/chat/ExpandedImageDialog.tsx": 4,
243 - "apps/web/src/components/chat/HtmlRenderFrame.tsx": 3,
244 - "apps/web/src/components/chat/MarkdownCodeBlock.tsx": 3,
245 - "apps/web/src/components/chat/MarkdownTable.tsx": 3,
246 - "apps/web/src/components/chat/McpAppFrame.tsx": 10,
247 - "apps/web/src/components/chat/MermaidDiagram.tsx": 1,
248 - "apps/web/src/components/chat/MessagesTimeline.tsx": 10,
249 - "apps/web/src/components/chat/ModelPickerContent.tsx": 4,
250 - "apps/web/src/components/chat/ModelPickerSidebar.tsx": 1,
251 - "apps/web/src/components/chat/OpenInPicker.tsx": 1,
252 - "apps/web/src/components/chat/OpenInPickerShortcut.ts": 1,
253 - "apps/web/src/components/chat/PierreEntryIcon.tsx": 1,
254 - "apps/web/src/components/chat/ProviderModelPicker.tsx": 1,
255 - "apps/web/src/components/chat/ProviderSubagentBar.tsx": 1,
256 - "apps/web/src/components/chat/ThreadActivityAnnouncer.tsx": 1,
257 - "apps/web/src/components/chat/ThreadDetailsCard.tsx": 4,
258 - "apps/web/src/components/chat/ThreadFindBar.tsx": 1,
259 - "apps/web/src/components/chat/ThreadFindProvider.tsx": 1,
260 - "apps/web/src/components/chat/ThreadTimeline.tsx": 1,
261 - "apps/web/src/components/chat/ThreadVisitWatermark.tsx": 2,
262 - "apps/web/src/components/chat/TimelineMinimap.tsx": 1,
263 - "apps/web/src/components/chat/TimelineWorkGroupRows.tsx": 3,
264 - "apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx": 1,
265 - "apps/web/src/components/chat/WorkLog.tsx": 1,
266 - "apps/web/src/components/chat/WorktreeSetupCard.tsx": 1,
267 - "apps/web/src/components/chat/ZoomableImage.tsx": 3,
268 - "apps/web/src/components/chat/composerContextUndo.ts": 1,
269 - "apps/web/src/components/chat/threadContextDrag.ts": 1,
270 - "apps/web/src/components/chat/threadFindHighlights.ts": 3,
271 - "apps/web/src/components/chat/useAssistantCitationTarget.ts": 2,
272 - "apps/web/src/components/chat/useAttachmentPreviewHandoff.ts": 4,
273 - "apps/web/src/components/chat/useChatShortcuts.ts": 1,
274 - "apps/web/src/components/chat/useComposerCommandKey.ts": 1,
275 - "apps/web/src/components/chat/useComposerMultilinePrompt.ts": 1,
276 - "apps/web/src/components/chat/useComposerRestingTransition.ts": 5,
277 - "apps/web/src/components/chat/useComposerSend.ts": 1,
278 - "apps/web/src/components/chat/useComposerStash.ts": 2,
279 - "apps/web/src/components/chat/useComposerTypingGuard.ts": 1,
280 - "apps/web/src/components/chat/useDraftEnvironmentRouting.ts": 3,
281 - "apps/web/src/components/chat/useDraftHeroLayoutTransition.ts": 1,
282 - "apps/web/src/components/chat/usePasteToFocusComposer.ts": 1,
283 - "apps/web/src/components/chat/usePendingThreadRequests.ts": 2,
284 - "apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts": 2,
285 - "apps/web/src/components/chat/useQueuedRunEdit.ts": 1,
286 - "apps/web/src/components/chat/useRestingComposerControlsLayout.ts": 1,
287 - "apps/web/src/components/chat/useRightPanelActions.ts": 1,
288 - "apps/web/src/components/chat/useSystemComposerBanners.tsx": 1,
289 - "apps/web/src/components/chat/useThreadFind.ts": 6,
290 - "apps/web/src/components/chat/useThreadFindNavigation.ts": 5,
291 - "apps/web/src/components/chat/useThreadFindPositionReader.ts": 1,
292 - "apps/web/src/components/chat/useThreadLifecycle.tsx": 1,
293 - "apps/web/src/components/chat/useTimelineFollow.ts": 6,
294 - "apps/web/src/components/chat/useTimelinePositionRestore.ts": 2,
295 - "apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx": 3,
296 - "apps/web/src/components/cloud/ConnectCliAuthSurface.tsx": 1,
297 - "apps/web/src/components/contextChipParts.tsx": 1,
298 - "apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx": 1,
299 - "apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx": 1,
300 - "apps/web/src/components/desktop/SnapShotCoordinator.tsx": 2,
301 - "apps/web/src/components/desktop/SshPasswordPromptDialog.tsx": 3,
302 - "apps/web/src/components/device/DeviceAndroidFoldControls.tsx": 2,
303 - "apps/web/src/components/device/DeviceDuoViewport.tsx": 4,
304 - "apps/web/src/components/device/DevicePanel.tsx": 1,
305 - "apps/web/src/components/device/DevicePhoneViewport.tsx": 3,
306 - "apps/web/src/components/device/DeviceSetup.tsx": 1,
307 - "apps/web/src/components/device/DeviceStreamView.tsx": 4,
308 - "apps/web/src/components/device/DeviceToolsPanel.tsx": 1,
309 - "apps/web/src/components/device/DeviceWorkspace.tsx": 1,
310 - "apps/web/src/components/device/useDeviceControls.ts": 2,
311 - "apps/web/src/components/diffs/DiffCommentAnnotation.tsx": 1,
312 - "apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx": 1,
313 - "apps/web/src/components/diffs/DiffFileTree.tsx": 3,
314 - "apps/web/src/components/diffs/useCodeViewFileReveal.ts": 1,
315 - "apps/web/src/components/diffs/useReviewFilePatches.ts": 1,
316 - "apps/web/src/components/files/AttachmentFilePreview.tsx": 3,
317 - "apps/web/src/components/files/BrowserDocumentFrame.tsx": 7,
318 - "apps/web/src/components/files/FileBrowserPanel.tsx": 9,
319 - "apps/web/src/components/files/FilePreviewPanel.tsx": 3,
320 - "apps/web/src/components/files/useDirectoryEntries.ts": 1,
321 - "apps/web/src/components/files/useFileSaveCoordinator.ts": 2,
322 - "apps/web/src/components/guest/GuestHtmlRender.tsx": 3,
323 - "apps/web/src/components/guest/GuestPage.tsx": 7,
324 - "apps/web/src/components/media/AttachmentImage.tsx": 1,
325 - "apps/web/src/components/media/MediaVideoPlayer.tsx": 2,
326 - "apps/web/src/components/onboarding/FirstRunGate.tsx": 3,
327 - "apps/web/src/components/onboarding/WelcomeWizard.tsx": 7,
328 - "apps/web/src/components/permissions/usePermissionStatus.ts": 1,
329 - "apps/web/src/components/preview/AgentBrowserCursor.tsx": 1,
330 - "apps/web/src/components/preview/PreviewChromeRow.tsx": 1,
331 - "apps/web/src/components/preview/PreviewPanelShell.tsx": 3,
332 - "apps/web/src/components/preview/PreviewView.tsx": 7,
333 - "apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx": 3,
334 - "apps/web/src/components/preview/ZoomIndicator.tsx": 1,
335 - "apps/web/src/components/preview/useAgentOpenedPreviews.ts": 3,
336 - "apps/web/src/components/preview/usePreviewBridge.ts": 2,
337 - "apps/web/src/components/projectScriptEditor.tsx": 1,
338 - "apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsx": 1,
339 - "apps/web/src/components/promptLinks/NewThreadLinkView.tsx": 2,
340 - "apps/web/src/components/promptLinks/ThreadLinkPrompt.tsx": 1,
341 - "apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx": 1,
342 - "apps/web/src/components/pullRequest/PullRequestCodeTab.tsx": 5,
343 - "apps/web/src/components/pullRequest/PullRequestCommentBody.tsx": 1,
344 - "apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx": 5,
345 - "apps/web/src/components/pullRequest/PullRequestGuideTab.tsx": 2,
346 - "apps/web/src/components/pullRequest/PullRequestsColumn.tsx": 5,
347 - "apps/web/src/components/pullRequest/PullRequestsPage.tsx": 9,
348 - "apps/web/src/components/pullRequest/guide/GuideTour.tsx": 1,
349 - "apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx": 2,
350 - "apps/web/src/components/pullRequest/guide/useReviewGuideWriter.ts": 1,
351 - "apps/web/src/components/pullRequest/useInlineActionConfirm.ts": 1,
352 - "apps/web/src/components/pullRequest/usePullRequestDetail.ts": 1,
353 - "apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts": 2,
354 - "apps/web/src/components/pullRequest/useThreadLinkedPullRequest.ts": 1,
355 - "apps/web/src/components/search/ProjectContentSearchDialog.tsx": 1,
356 - "apps/web/src/components/settings/AcpRegistryIcon.tsx": 1,
357 - "apps/web/src/components/settings/AcpRegistrySearchStep.tsx": 2,
358 - "apps/web/src/components/settings/AddCodexAccountDialog.tsx": 1,
359 - "apps/web/src/components/settings/AddEnvironmentDialog.tsx": 1,
360 - "apps/web/src/components/settings/CliCommandSettingsRow.tsx": 1,
361 - "apps/web/src/components/settings/CodexSetupSection.tsx": 6,
362 - "apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx": 1,
363 - "apps/web/src/components/settings/DiagnosticsSettings.tsx": 2,
364 - "apps/web/src/components/settings/EasDeviceHostsSettings.tsx": 1,
365 - "apps/web/src/components/settings/FontFamilyPicker.tsx": 2,
366 - "apps/web/src/components/settings/OpenSourceLicenses.tsx": 1,
367 - "apps/web/src/components/settings/ProjectFaviconThumbnail.tsx": 1,
368 - "apps/web/src/components/settings/ProjectIconPickerDialog.tsx": 1,
369 - "apps/web/src/components/settings/ProjectSettingsPanel.tsx": 2,
370 - "apps/web/src/components/settings/ProviderAccentColorPicker.tsx": 3,
371 - "apps/web/src/components/settings/ProviderAuthCallbackCoordinator.tsx": 1,
372 - "apps/web/src/components/settings/ProviderAuthTerminal.tsx": 2,
373 - "apps/web/src/components/settings/ProviderInstanceCard.tsx": 1,
374 - "apps/web/src/components/settings/ProviderModelsSection.tsx": 1,
375 - "apps/web/src/components/settings/ProviderSettingsForm.tsx": 1,
376 - "apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx": 2,
377 - "apps/web/src/components/settings/SavedEnvironmentRows.tsx": 1,
378 - "apps/web/src/components/settings/ScheduledTasksSettings.tsx": 2,
379 - "apps/web/src/components/settings/SettingsFontPreviews.tsx": 5,
380 - "apps/web/src/components/settings/SettingsPanels.tsx": 1,
381 - "apps/web/src/components/settings/SettingsSidebarNav.tsx": 3,
382 - "apps/web/src/components/settings/SnapShotSettings.tsx": 4,
383 - "apps/web/src/components/settings/TelemetryExportSettings.tsx": 1,
384 - "apps/web/src/components/settings/ThemeColorPicker.tsx": 1,
385 - "apps/web/src/components/settings/ThemeEditorPanel.tsx": 5,
386 - "apps/web/src/components/settings/ThemeImportDialog.tsx": 1,
387 - "apps/web/src/components/settings/ThemeSearchSection.tsx": 3,
388 - "apps/web/src/components/settings/TypographySettings.tsx": 2,
389 - "apps/web/src/components/settings/settingsLayout.tsx": 1,
390 - "apps/web/src/components/settings/useSnapShotShortcutRecorder.tsx": 1,
391 - "apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx": 2,
392 - "apps/web/src/components/sidebar/SidebarThreadRow.tsx": 5,
393 - "apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx": 1,
394 - "apps/web/src/components/sidebar/SidebarUpdatePill.tsx": 1,
395 - "apps/web/src/components/sidebar/mainAppLocation.ts": 1,
396 - "apps/web/src/components/sidebar/updateEverythingRun.tsx": 2,
397 - "apps/web/src/components/ui/sidebar.tsx": 3,
398 - "apps/web/src/components/ui/toast.tsx": 2,
399 - "apps/web/src/components/ui/tooltip.tsx": 1,
400 - "apps/web/src/components/usage/UsageLimits.tsx": 1,
401 - "apps/web/src/components/usage/UsageLimitsPooled.tsx": 1,
402 - "apps/web/src/components/usage/UsagePage.tsx": 3,
403 - "apps/web/src/components/usage/UsageProviderChart.tsx": 1,
404 - "apps/web/src/connection/useDesktopLocalBootstraps.ts": 1,
405 - "apps/web/src/hooks/FileMetadataThreadProvider.tsx": 1,
406 - "apps/web/src/hooks/useCopyToClipboard.ts": 1,
407 - "apps/web/src/hooks/useDefaultTheme.ts": 1,
408 - "apps/web/src/hooks/useDelayedStatus.ts": 2,
409 - "apps/web/src/hooks/useEnvironmentDisconnectDelay.ts": 1,
410 - "apps/web/src/hooks/useEnvironmentTheme.ts": 1,
411 - "apps/web/src/hooks/useLiveRefresh.ts": 1,
412 - "apps/web/src/hooks/useLiveRegion.ts": 1,
413 - "apps/web/src/hooks/useNavigateBack.ts": 1,
414 - "apps/web/src/hooks/usePreviewPanelInlineSize.ts": 1,
415 - "apps/web/src/hooks/useProactivePanels.ts": 1,
416 - "apps/web/src/hooks/useResizableWidth.ts": 2,
417 - "apps/web/src/hooks/useResizeDrag.ts": 2,
418 - "apps/web/src/hooks/useSettings.ts": 1,
419 - "apps/web/src/hooks/useStableCallback.ts": 1,
420 - "apps/web/src/hooks/useTheme.ts": 1,
421 - "apps/web/src/hooks/useThreadVisitedMigration.ts": 1,
422 - "apps/web/src/hooks/useWorkspaceMutationRefresh.ts": 1,
423 - "apps/web/src/panelAnimations.ts": 2,
424 - "apps/web/src/remoteOpen.ts": 1,
425 - "apps/web/src/routes/__root.tsx": 13,
426 - "apps/web/src/routes/_chat.index.tsx": 1,
427 - "apps/web/src/routes/_chat.tsx": 1,
428 - "apps/web/src/shortcutModifierState.ts": 1,
429 - "apps/web/src/state/olderSettledShelf.ts": 2,
430 - "apps/web/src/state/pullRequests.ts": 2,
431 - "apps/web/src/state/queries.ts": 2,
432 - "apps/web/src/state/threads.ts": 1
433 -}
scripts/install.ps1
+2 -13
@@ -133,19 +133,8 @@ if (-not $version) {
133 "preview" { '^v\d+\.\d+\.\d+-preview\.\d+\.\d+$' }
134 default { Fail "T3CODE_CHANNEL must be stable, nightly, or preview" }
135 }
136 - if ($channel -eq "stable") {
137 - # release.yml marks only plain stable releases latest. This is a github.com
138 - # page, so it is not cut off by a page of newer nightlies or the API quota.
139 - $release = Invoke-RestMethod -Uri "https://github.com/$repo/releases/latest" -Headers @{ "User-Agent" = "t3-install"; "Accept" = "application/json" }
140 - $tag = ($release | Where-Object { $_.tag_name -match $tagPattern }).tag_name
141 - } else {
142 - $tag = $null
143 - for ($page = 1; -not $tag -and $page -le 10; $page++) {
144 - $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases?per_page=100&page=$page" -Headers @{ "User-Agent" = "t3-install" }
145 - $tag = ($releases | Where-Object { -not $_.draft -and $_.tag_name -match $tagPattern } | Select-Object -First 1).tag_name
146 - if (-not $releases) { break }
147 - }
148 - }
136 + $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases?per_page=100" -Headers @{ "User-Agent" = "t3-install" }
137 + $tag = ($releases | Where-Object { -not $_.draft -and $_.tag_name -match $tagPattern } | Select-Object -First 1).tag_name
138 if (-not $tag) { Fail "could not find a $channel release; set T3CODE_VERSION" }
139 $version = $tag.Substring(1)
140 }
scripts/install.sh
+4 -16
@@ -53,14 +53,14 @@ step "Finding your release..."
53 # Exit 44 on a 404 so callers can tell "no such asset" from a network failure.
54 fetch() {
55 if command -v curl >/dev/null 2>&1; then
56 - status="$(curl -sSL -H "Accept: ${3:-*/*}" -w '%{http_code}' "$1" -o "$2")" || return 1
56 + status="$(curl -sSL -w '%{http_code}' "$1" -o "$2")" || return 1
57 case "$status" in
58 2??) return 0 ;;
59 404) return 44 ;;
60 *) printf 'GET %s returned HTTP %s\n' "$1" "$status" >&2; return 1 ;;
61 esac
62 elif command -v wget >/dev/null 2>&1; then
63 - wget -q --server-response --header="Accept: ${3:-*/*}" "$1" -O "$2" 2>"$2.headers" && rm -f "$2.headers" && return 0
63 + wget -q --server-response "$1" -O "$2" 2>"$2.headers" && rm -f "$2.headers" && return 0
64 if grep -q ' 404 ' "$2.headers" 2>/dev/null; then rm -f "$2.headers"; return 44; fi
65 cat "$2.headers" >&2; rm -f "$2.headers"; return 1
66 else
@@ -151,20 +151,8 @@ if [ -z "$version" ]; then
151 *) fail "T3CODE_CHANNEL must be stable, nightly, or preview" ;;
152 esac
153 tmp_index="$(mktemp)"
154 - if [ "$channel" = stable ]; then
155 - # release.yml marks only plain stable releases latest. This is a github.com
156 - # page, so it is not cut off by a page of newer nightlies or the API quota.
157 - fetch "https://github.com/${repo}/releases/latest" "$tmp_index" application/json
158 - version="$(sed -n "s/.*\"tag_name\": *\"${tag_pattern}\".*/\1/p" "$tmp_index" | head -n 1)"
159 - else
160 - page=1
161 - while [ -z "$version" ] && [ "$page" -le 10 ]; do
162 - fetch "https://api.github.com/repos/${repo}/releases?per_page=100&page=${page}" "$tmp_index"
163 - version="$(sed -n "s/.*\"tag_name\": *\"${tag_pattern}\".*/\1/p" "$tmp_index" | head -n 1)"
164 - grep -q '"tag_name"' "$tmp_index" || break
165 - page=$((page + 1))
166 - done
167 - fi
154 + fetch "https://api.github.com/repos/${repo}/releases?per_page=100" "$tmp_index"
155 + version="$(sed -n "s/.*\"tag_name\": *\"${tag_pattern}\".*/\1/p" "$tmp_index" | head -n 1)"
156 rm -f "$tmp_index"
157 [ -n "$version" ] || fail "could not find a ${channel} release; set T3CODE_VERSION"
158 fi
scripts/install.test.ts deleted
-80
@@ -1,80 +0,0 @@
1 -// @effect-diagnostics nodeBuiltinImport:off - Drives the real shell installer against a local GitHub fixture.
2 -import * as HostProcess from "@t3tools/shared/HostProcess";
3 -import * as NodeChildProcess from "node:child_process";
4 -import * as NodeFSP from "node:fs/promises";
5 -import * as NodeHttp from "node:http";
6 -import * as NodeOS from "node:os";
7 -import * as NodePath from "node:path";
8 -import { describe, expect, it } from "vite-plus/test";
9 -
10 -const nightlies = Array.from({ length: 100 }, (_, index) => ({
11 - tag_name: `v1.2.4-nightly.20261020.${200 - index}`,
12 -}));
13 -
14 -// regression: #22490
15 -describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer channel lookup", () => {
16 - it.each([
17 - ["stable", "1.2.3"],
18 - ["preview", "1.2.4-preview.20261019.50"],
19 - ])("finds the newest %s release behind a full page of nightlies", async (channel, version) => {
20 - const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-index-"));
21 - const target = NodePath.join(root, "home/runtime/versions", version);
22 - const server = NodeHttp.createServer((request, response) => {
23 - const url = new URL(request.url ?? "/", "http://fixture");
24 - const body =
25 - url.pathname === "/pingdotgg/t3code/releases/latest" &&
26 - request.headers.accept === "application/json"
27 - ? { tag_name: "v1.2.3" }
28 - : url.pathname === "/repos/pingdotgg/t3code/releases"
29 - ? { "1": nightlies, "2": [{ tag_name: `v${version}` }, { tag_name: "v1.2.3" }] }[
30 - url.searchParams.get("page") ?? ""
31 - ]
32 - : undefined;
33 - if (body === undefined) response.statusCode = 404;
34 - // The API pretty-prints and the installer reads it line by line.
35 - response.end(JSON.stringify(body ?? [], null, 2));
36 - });
37 - try {
38 - // An existing completed install isolates release resolution from archive downloads.
39 - await NodeFSP.mkdir(target, { recursive: true });
40 - await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
41 - await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
42 - const address = server.address();
43 - if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
44 - const origin = `http://127.0.0.1:${address.port}`;
45 - const source = await NodeFSP.readFile(
46 - NodePath.resolve(import.meta.dirname, "install.sh"),
47 - "utf8",
48 - );
49 - const installer = NodePath.join(root, "install.sh");
50 - await NodeFSP.writeFile(installer, source.replace(/https:\/\/(api\.)?github\.com/g, origin));
51 - const { code, output } = await new Promise<{ code: number | null; output: string }>(
52 - (resolve, reject) => {
53 - const child = NodeChildProcess.spawn("sh", [installer], {
54 - env: {
55 - ...process.env,
56 - T3CODE_VERSION: "",
57 - T3CODE_CHANNEL: channel,
58 - T3CODE_HOME: NodePath.join(root, "home"),
59 - T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
60 - // A wrong version must fail here instead of downloading a real release.
61 - T3CODE_RELEASE_BASE_URL: origin,
62 - },
63 - stdio: ["ignore", "pipe", "pipe"],
64 - });
65 - let output = "";
66 - child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
67 - child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
68 - child.on("error", reject);
69 - child.on("close", (code) => resolve({ code, output }));
70 - },
71 - );
72 - expect(code, output).toBe(0);
73 - expect(output).toContain(`Installed T3 Code ${version}`);
74 - } finally {
75 - server.closeAllConnections();
76 - await new Promise<void>((resolve) => server.close(() => resolve()));
77 - await NodeFSP.rm(root, { recursive: true, force: true });
78 - }
79 - });
80 -});
scripts/mobile-e2e.ts new
+785
@@ -0,0 +1,785 @@
1 +#!/usr/bin/env node
2 +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator automation uses Node subprocess and timing APIs directly.
3 +
4 +import * as NodeChildProcess from "node:child_process";
5 +import * as NodeFSP from "node:fs/promises";
6 +import * as NodeOS from "node:os";
7 +import * as NodePath from "node:path";
8 +import * as NodeProcess from "node:process";
9 +import * as NodeURL from "node:url";
10 +
11 +import { startShowcaseEnvironments, stopProcess, waitForPort } from "./mobile-showcase.ts";
12 +import { SHOWCASE_ENVIRONMENTS } from "./mobile-showcase-environment.ts";
13 +
14 +const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
15 +const AGENT_DEVICE = NodePath.join(
16 + REPO_ROOT,
17 + "scripts/node_modules/agent-device/bin/agent-device.mjs",
18 +);
19 +const BUNDLE_ID = "com.t3tools.t3code.dev";
20 +const METRO_PORT = 8081;
21 +// Persistent so the XCTest runner agent-device builds per simulator survives between runs.
22 +const AGENT_DEVICE_STATE = NodePath.join(NodeOS.homedir(), ".cache/t3code/mobile-e2e/agent-device");
23 +
24 +export interface E2eDevice {
25 + readonly id: string;
26 + readonly platform: "ios";
27 + readonly deviceType: string;
28 + readonly runtime: string;
29 +}
30 +
31 +const ios = (id: string, deviceType: string): E2eDevice => ({
32 + id,
33 + platform: "ios",
34 + deviceType: `com.apple.CoreSimulator.SimDeviceType.${deviceType}`,
35 + runtime: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",
36 +});
37 +
38 +export const DEVICES: ReadonlyArray<E2eDevice> = [
39 + ios("iphone-se", "iPhone-SE-3rd-generation"),
40 + ios("iphone-13-mini", "iPhone-13-mini"),
41 + ios("iphone-17", "iPhone-17"),
42 + ios("iphone-17-pro", "iPhone-17-Pro"),
43 + ios("iphone-17-pro-max", "iPhone-17-Pro-Max"),
44 + ios("iphone-air", "iPhone-Air"),
45 +];
46 +
47 +interface Rect {
48 + readonly x: number;
49 + readonly y: number;
50 + readonly width: number;
51 + readonly height: number;
52 +}
53 +
54 +export interface SnapshotNode {
55 + readonly type?: string;
56 + readonly role?: string;
57 + readonly identifier?: string;
58 + readonly label?: string;
59 + readonly rect?: Rect;
60 +}
61 +
62 +export interface Snapshot {
63 + readonly nodes: ReadonlyArray<SnapshotNode>;
64 + readonly viewport: { readonly width: number; readonly height: number };
65 +}
66 +
67 +export interface Check {
68 + readonly name: string;
69 + readonly pass: boolean;
70 + readonly detail: string;
71 +}
72 +
73 +interface StepResult {
74 + readonly name: string;
75 + readonly checks: ReadonlyArray<Check>;
76 + readonly screenshot?: string | undefined;
77 + readonly video?: string | undefined;
78 + readonly contactSheet?: string | undefined;
79 + readonly lagFrame?: string | undefined;
80 + readonly samples: number;
81 +}
82 +
83 +interface DeviceResult {
84 + readonly device: E2eDevice;
85 + readonly label: string;
86 + readonly steps: ReadonlyArray<StepResult>;
87 + readonly error?: string;
88 +}
89 +
90 +const onScreen = (node: SnapshotNode, snapshot: Snapshot) =>
91 + node.rect !== undefined &&
92 + node.rect.width > 0 &&
93 + node.rect.height > 0 &&
94 + node.rect.x < snapshot.viewport.width &&
95 + node.rect.y < snapshot.viewport.height &&
96 + node.rect.x + node.rect.width > 0 &&
97 + node.rect.y + node.rect.height > 0;
98 +
99 +const find = (snapshot: Snapshot, match: (node: SnapshotNode) => boolean) =>
100 + snapshot.nodes.filter((node) => match(node) && onScreen(node, snapshot));
101 +
102 +export const chrome = (snapshot: Snapshot) => ({
103 + tabBar: find(snapshot, (node) => node.type === "TabBar")[0],
104 + navigationBar: find(snapshot, (node) => node.type === "NavigationBar")[0],
105 + backButton: find(snapshot, (node) => node.identifier === "BackButton")[0],
106 + send: find(snapshot, (node) => node.type === "Button" && node.label === "Send")[0],
107 + newChat: find(snapshot, (node) => node.type === "Button" && node.label === "New chat")[0],
108 + // Thread rows are full-width context-menu wrappers; the filter pills are narrow ones.
109 + threadRows: find(
110 + snapshot,
111 + (node) =>
112 + node.role === "MenuView" &&
113 + Boolean(node.label) &&
114 + (node.rect?.width ?? 0) >= snapshot.viewport.width * 0.9,
115 + ),
116 +});
117 +
118 +const check = (name: string, pass: boolean, detail: string): Check => ({ name, pass, detail });
119 +const describeRect = (rect: Rect | undefined) =>
120 + rect
121 + ? `${Math.round(rect.x)},${Math.round(rect.y)} ${Math.round(rect.width)}×${Math.round(rect.height)}`
122 + : "absent";
123 +const inside = (rect: Rect, snapshot: Snapshot) =>
124 + rect.x >= 0 &&
125 + rect.y >= 0 &&
126 + rect.x + rect.width <= snapshot.viewport.width + 0.5 &&
127 + rect.y + rect.height <= snapshot.viewport.height + 0.5;
128 +
129 +export function homeChecks(snapshot: Snapshot): Check[] {
130 + const { tabBar, newChat } = chrome(snapshot);
131 + return [
132 + check("tab bar visible", tabBar !== undefined, describeRect(tabBar?.rect)),
133 + check(
134 + "tab bar inside the screen",
135 + tabBar?.rect !== undefined && inside(tabBar.rect, snapshot),
136 + describeRect(tabBar?.rect),
137 + ),
138 + check("new chat button visible", newChat !== undefined, describeRect(newChat?.rect)),
139 + ];
140 +}
141 +
142 +export function threadChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
143 + const { tabBar, backButton, send } = chrome(snapshot);
144 + const overlapping = samples.filter((sample) => {
145 + const state = chrome(sample);
146 + return state.backButton !== undefined && state.tabBar !== undefined;
147 + }).length;
148 + return [
149 + check("tab bar hidden", tabBar === undefined, describeRect(tabBar?.rect)),
150 + check("back button visible", backButton !== undefined, describeRect(backButton?.rect)),
151 + check(
152 + "composer inside the screen",
153 + send?.rect !== undefined && inside(send.rect, snapshot),
154 + describeRect(send?.rect),
155 + ),
156 + check(
157 + "no tabs over the entering thread",
158 + overlapping === 0,
159 + `${overlapping} of ${samples.length} transition samples showed tabs with a Back button`,
160 + ),
161 + ];
162 +}
163 +
164 +export function backChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
165 + const listWithoutTabs = samples.filter((sample) => {
166 + const state = chrome(sample);
167 + return (
168 + state.backButton === undefined && state.newChat !== undefined && state.tabBar === undefined
169 + );
170 + }).length;
171 + return [
172 + ...homeChecks(snapshot),
173 + check(
174 + "tabs return with the list",
175 + listWithoutTabs === 0,
176 + `${listWithoutTabs} of ${samples.length} transition samples showed the list without tabs`,
177 + ),
178 + ];
179 +}
180 +
181 +/** Downsampled grayscale crops of one region, one per video frame (or one for a PNG). */
182 +async function grayFrames(input: string, region: Rect, scale: number): Promise<Uint8Array[]> {
183 + const even = (value: number) => Math.max(2, Math.floor(value / 2) * 2);
184 + const [x, y, width, height] = [
185 + Math.round(region.x * scale),
186 + Math.round(region.y * scale),
187 + even(region.width * scale),
188 + even(region.height * scale),
189 + ];
190 + const [outWidth, outHeight] = [even(width / 6), even(height / 6)];
191 + const bytes = await new Promise<Buffer>((resolve, reject) => {
192 + const child = NodeChildProcess.spawn(
193 + "ffmpeg",
194 + [
195 + "-v",
196 + "error",
197 + "-i",
198 + input,
199 + // One output frame per recorded frame, so indices match select=eq(n,…) for evidence.
200 + "-fps_mode",
201 + "passthrough",
202 + "-vf",
203 + `crop=${width}:${height}:${x}:${y},scale=${outWidth}:${outHeight},format=gray`,
204 + "-f",
205 + "rawvideo",
206 + "-",
207 + ],
208 + { stdio: ["ignore", "pipe", "pipe"] },
209 + );
210 + const chunks: Buffer[] = [];
211 + let stderr = "";
212 + child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
213 + child.stderr.on("data", (chunk) => (stderr += chunk));
214 + child.on("error", reject);
215 + child.on("close", (code) =>
216 + code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`ffmpeg failed: ${stderr}`)),
217 + );
218 + });
219 + const size = outWidth * outHeight;
220 + return Array.from({ length: Math.floor(bytes.length / size) }, (_, index) =>
221 + bytes.subarray(index * size, (index + 1) * size),
222 + );
223 +}
224 +
225 +const distance = (a: Uint8Array, b: Uint8Array) => {
226 + let sum = 0;
227 + for (let index = 0; index < a.length; index++) sum += Math.abs(a[index]! - b[index]!);
228 + return sum / a.length;
229 +};
230 +
231 +/** How far a region has moved from its origin toward its destination look, 0 to 1. */
232 +export interface FrameProgress {
233 + readonly nav: number;
234 + readonly chrome: number;
235 +}
236 +
237 +/**
238 + * A frame lags when the navigation bar is well into the transition while the tab bar region
239 + * still looks like the origin: tabs lingering over an entering thread, or a returned list drawn
240 + * before its tabs.
241 + */
242 +export const chromeLags = (frame: FrameProgress) => frame.nav > 0.3 && frame.chrome < 0.4;
243 +// One lagging frame is capture jitter; a regression lasts several.
244 +const LAG_FRAME_LIMIT = 2;
245 +
246 +const progress = (origin: number, destination: number) =>
247 + origin + destination === 0 ? 0 : origin / (origin + destination);
248 +
249 +async function chromeLagFrames(input: {
250 + readonly video: string;
251 + readonly origin: string;
252 + readonly destination: string;
253 + readonly nav: Rect;
254 + readonly chrome: Rect;
255 + readonly scale: number;
256 +}) {
257 + const [
258 + navFrames,
259 + chromeFrames,
260 + [navOrigin],
261 + [navDestination],
262 + [chromeOrigin],
263 + [chromeDestination],
264 + ] = await Promise.all([
265 + grayFrames(input.video, input.nav, input.scale),
266 + grayFrames(input.video, input.chrome, input.scale),
267 + grayFrames(input.origin, input.nav, input.scale),
268 + grayFrames(input.destination, input.nav, input.scale),
269 + grayFrames(input.origin, input.chrome, input.scale),
270 + grayFrames(input.destination, input.chrome, input.scale),
271 + ]);
272 + if (!navOrigin || !navDestination || !chromeOrigin || !chromeDestination)
273 + throw new Error("Could not read the reference screenshots.");
274 + const verdicts = navFrames.map((nav, index) => {
275 + const chrome = chromeFrames[index]!;
276 + return {
277 + nav: progress(distance(nav, navOrigin), distance(nav, navDestination)),
278 + chrome: progress(distance(chrome, chromeOrigin), distance(chrome, chromeDestination)),
279 + };
280 + });
281 + return verdicts.flatMap((verdict, index) => (chromeLags(verdict) ? [index] : []));
282 +}
283 +
284 +async function saveFrame(video: string, index: number, path: string) {
285 + await run("ffmpeg", [
286 + "-v",
287 + "error",
288 + "-y",
289 + "-i",
290 + video,
291 + "-vf",
292 + `select=eq(n\\,${index})`,
293 + "-frames:v",
294 + "1",
295 + path,
296 + ]);
297 +}
298 +
299 +async function lagCheck(
300 + name: string,
301 + input: Parameters<typeof chromeLagFrames>[0],
302 + evidence: string,
303 +): Promise<{ check: Check; frame?: string }> {
304 + const lagging = await chromeLagFrames(input);
305 + if (lagging.length < LAG_FRAME_LIMIT)
306 + return { check: check(name, true, `${lagging.length} lagging video frames`) };
307 + await saveFrame(input.video, lagging[0]!, evidence);
308 + return {
309 + check: check(name, false, `${lagging.length} video frames (first #${lagging[0]})`),
310 + frame: evidence,
311 + };
312 +}
313 +
314 +function run(
315 + command: string,
316 + args: ReadonlyArray<string>,
317 + options: { readonly env?: NodeJS.ProcessEnv; readonly allowFailure?: boolean } = {},
318 +): Promise<{ readonly code: number; readonly stdout: string; readonly stderr: string }> {
319 + return new Promise((resolve, reject) => {
320 + const child = NodeChildProcess.spawn(command, args, {
321 + cwd: REPO_ROOT,
322 + env: options.env ?? NodeProcess.env,
323 + stdio: ["ignore", "pipe", "pipe"],
324 + });
325 + let stdout = "";
326 + let stderr = "";
327 + child.stdout.on("data", (chunk) => (stdout += chunk));
328 + child.stderr.on("data", (chunk) => (stderr += chunk));
329 + child.on("error", reject);
330 + child.on("close", (code) => {
331 + if (code !== 0 && !options.allowFailure)
332 + reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${stderr || stdout}`));
333 + else resolve({ code: code ?? 1, stdout, stderr });
334 + });
335 + });
336 +}
337 +
338 +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
339 +
340 +class Device {
341 + readonly spec: E2eDevice;
342 + readonly udid: string;
343 +
344 + constructor(spec: E2eDevice, udid: string) {
345 + this.spec = spec;
346 + this.udid = udid;
347 + }
348 +
349 + async agent(args: ReadonlyArray<string>): Promise<Record<string, unknown>> {
350 + const { stdout } = await run(
351 + NodeProcess.execPath,
352 + [
353 + AGENT_DEVICE,
354 + ...args,
355 + "--platform",
356 + "ios",
357 + "--udid",
358 + this.udid,
359 + "--session",
360 + `t3-e2e-${this.spec.id}`,
361 + "--json",
362 + ],
363 + {
364 + env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
365 + allowFailure: true,
366 + },
367 + );
368 + const parsed = JSON.parse(stdout) as {
369 + success: boolean;
370 + data?: Record<string, unknown>;
371 + error?: { message: string };
372 + };
373 + if (!parsed.success) throw new Error(`agent-device ${args[0]}: ${parsed.error?.message}`);
374 + return parsed.data ?? {};
375 + }
376 +
377 + async snapshot(): Promise<Snapshot> {
378 + return (await this.agent(["snapshot"])) as unknown as Snapshot;
379 + }
380 +
381 + async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
382 + const deadline = Date.now() + timeoutMs;
383 + let last: Snapshot | null = null;
384 + while (Date.now() < deadline) {
385 + last = await this.snapshot().catch(() => null);
386 + if (last && predicate(last)) return last;
387 + await delay(500);
388 + }
389 + throw new Error(`${this.spec.id}: timed out waiting for ${label}`);
390 + }
391 +
392 + /** Open a URL the way a user would; iOS asks before opening a custom scheme from another app. */
393 + async openUrl(url: string) {
394 + await run("xcrun", ["simctl", "openurl", this.udid, url]);
395 + await delay(1_500);
396 + await this.agent(["alert", "accept"]).catch(() => undefined);
397 + }
398 +
399 + async screenshot(path: string) {
400 + await run("xcrun", ["simctl", "io", this.udid, "screenshot", path]);
401 + }
402 +
403 + /** Run an action while recording and sampling the accessibility tree until the screen settles. */
404 + async transition(directory: string, name: string, action: () => Promise<unknown>) {
405 + const video = NodePath.join(directory, `${name}.mp4`);
406 + await this.agent(["record", "start", video, "--hide-touches"]);
407 + const samples: Snapshot[] = [];
408 + const sampling = { active: true };
409 + const sampler = (async () => {
410 + while (sampling.active) {
411 + const sample = await this.snapshot().catch(() => null);
412 + if (sample) samples.push(sample);
413 + }
414 + })();
415 + try {
416 + await action();
417 + await delay(2_000);
418 + } finally {
419 + sampling.active = false;
420 + await sampler;
421 + await this.agent(["record", "stop"]).catch(() => undefined);
422 + }
423 + const contactSheet = NodePath.join(directory, `${name}-frames.png`);
424 + const sheet = await run(
425 + NodeProcess.execPath,
426 + [AGENT_DEVICE, "record", "contact-sheet", video, "--out", contactSheet],
427 + {
428 + env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
429 + allowFailure: true,
430 + },
431 + );
432 + return { samples, video, contactSheet: sheet.code === 0 ? contactSheet : undefined };
433 + }
434 +}
435 +
436 +/** Screenshot pixels per snapshot point (3 on most iPhones). */
437 +async function screenshotScale(path: string, snapshot: Snapshot): Promise<number> {
438 + const { stdout } = await run("ffprobe", [
439 + "-v",
440 + "error",
441 + "-select_streams",
442 + "v:0",
443 + "-show_entries",
444 + "stream=width",
445 + "-of",
446 + "csv=p=0",
447 + path,
448 + ]);
449 + return Number(stdout.trim()) / snapshot.viewport.width;
450 +}
451 +
452 +async function ensureSimulator(spec: E2eDevice): Promise<string> {
453 + const name = `T3 E2E ${spec.id}`;
454 + const listing = JSON.parse(
455 + (await run("xcrun", ["simctl", "list", "devices", "available", "-j"])).stdout,
456 + ) as { devices: Record<string, ReadonlyArray<{ udid: string; name: string; state: string }>> };
457 + const existing = (listing.devices[spec.runtime] ?? []).find((device) => device.name === name);
458 + const udid =
459 + existing?.udid ??
460 + (await run("xcrun", ["simctl", "create", name, spec.deviceType, spec.runtime])).stdout.trim();
461 + if (existing?.state !== "Booted")
462 + await run("xcrun", ["simctl", "boot", udid], { allowFailure: true });
463 + await run("xcrun", ["simctl", "bootstatus", udid, "-b"]);
464 + await run("xcrun", ["simctl", "ui", udid, "appearance", "light"]);
465 + await run("xcrun", [
466 + "simctl",
467 + "status_bar",
468 + udid,
469 + "override",
470 + "--time",
471 + "9:41",
472 + "--batteryState",
473 + "charged",
474 + "--batteryLevel",
475 + "100",
476 + ]);
477 + return udid;
478 +}
479 +
480 +function lanAddress(): string {
481 + for (const addresses of Object.values(NodeOS.networkInterfaces())) {
482 + for (const address of addresses ?? []) {
483 + if (address.family === "IPv4" && !address.internal && !address.address.startsWith("169.254."))
484 + return address.address;
485 + }
486 + }
487 + throw new Error("No LAN IPv4 address for the simulator to reach Metro.");
488 +}
489 +
490 +async function runDevice(
491 + spec: E2eDevice,
492 + outputDirectory: string,
493 + environment: { readonly baseDir: string; readonly port: number },
494 + metroHost: string,
495 +): Promise<DeviceResult> {
496 + const steps: StepResult[] = [];
497 + const directory = NodePath.join(outputDirectory, spec.id);
498 + await NodeFSP.mkdir(directory, { recursive: true });
499 + try {
500 + const udid = await ensureSimulator(spec);
501 + const device = new Device(spec, udid);
502 + // A fresh install drops connections paired by earlier runs; the cached client reinstalls in seconds.
503 + await run("xcrun", ["simctl", "uninstall", udid, BUNDLE_ID], { allowFailure: true });
504 + log(spec.id, "installing the dev client");
505 + await run(NodeProcess.execPath, ["scripts/mobile-native-client.ts", "ensure", "ios", udid], {
506 + env: { ...NodeProcess.env, T3_NATIVE_CLIENT_CACHE: NodeProcess.env.T3_NATIVE_CLIENT_CACHE },
507 + });
508 + const metroUrl = encodeURIComponent(`http://${metroHost}:${METRO_PORT}`);
509 + await device.openUrl(
510 + `t3code-dev://expo-development-client/?url=${metroUrl}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
511 + );
512 + // Snapshots read through an agent-device app session; open attaches one to the running app.
513 + await device.agent(["open", BUNDLE_ID]);
514 + // The app ignores the pairing link until its JS has loaded and shown the workspace.
515 + await device.waitFor(
516 + (snapshot) => chrome(snapshot).newChat !== undefined,
517 + "the app to load",
518 + 120_000,
519 + );
520 + const paired = (snapshot: Snapshot) =>
521 + chrome(snapshot).tabBar !== undefined && chrome(snapshot).threadRows.length > 0;
522 + let home: Snapshot | null = null;
523 + for (let attempt = 1; attempt <= 2 && !home; attempt++) {
524 + log(spec.id, attempt === 1 ? "pairing" : "pairing again");
525 + const pairing = new URLSearchParams({
526 + pairingUrl: await issuePairUrl(environment),
527 + autoConnect: "1",
528 + });
529 + await device.openUrl(`t3code-dev://connections/new?${pairing}`);
530 + home = await device.waitFor(paired, "the paired thread list", 45_000).catch(() => null);
531 + }
532 + if (!home) throw new Error("The app did not show the fixture threads after pairing.");
533 + await delay(1_000);
534 + const homeShot = NodePath.join(directory, "home.png");
535 + await device.screenshot(homeShot);
536 + steps.push({ name: "home", checks: homeChecks(home), screenshot: homeShot, samples: 0 });
537 +
538 + log(spec.id, "opening a thread");
539 + const row = chrome(home).threadRows[0];
540 + if (!row?.label) throw new Error("No thread row to open.");
541 + const opened = await device.transition(directory, "open-thread", () =>
542 + device.agent(["press", `label=${JSON.stringify(row.label)}`]),
543 + );
544 + const thread = await device.waitFor(
545 + (snapshot) => chrome(snapshot).backButton !== undefined,
546 + "the thread screen",
547 + );
548 + const threadShot = NodePath.join(directory, "thread.png");
549 + await device.screenshot(threadShot);
550 + const { tabBar, navigationBar } = chrome(home);
551 + const scale = await screenshotScale(homeShot, home);
552 + const regions =
553 + tabBar?.rect && navigationBar?.rect ? { nav: navigationBar.rect, chrome: tabBar.rect } : null;
554 + const openLag = regions
555 + ? await lagCheck(
556 + "no tabs over the entering thread (video)",
557 + { video: opened.video, origin: homeShot, destination: threadShot, scale, ...regions },
558 + NodePath.join(directory, "open-thread-lag.png"),
559 + )
560 + : null;
561 + steps.push({
562 + name: "open thread",
563 + checks: [...threadChecks(thread, opened.samples), ...(openLag ? [openLag.check] : [])],
564 + lagFrame: openLag?.frame,
565 + screenshot: threadShot,
566 + video: opened.video,
567 + contactSheet: opened.contactSheet,
568 + samples: opened.samples.length,
569 + });
570 +
571 + log(spec.id, "going back");
572 + const back = await device.transition(directory, "back", () =>
573 + device.agent(["press", "id=BackButton"]),
574 + );
575 + const list = await device.waitFor(
576 + (snapshot) => chrome(snapshot).backButton === undefined,
577 + "the thread list",
578 + );
579 + const backShot = NodePath.join(directory, "back.png");
580 + await device.screenshot(backShot);
581 + const backLag = regions
582 + ? await lagCheck(
583 + "tabs return with the list (video)",
584 + { video: back.video, origin: threadShot, destination: backShot, scale, ...regions },
585 + NodePath.join(directory, "back-lag.png"),
586 + )
587 + : null;
588 + steps.push({
589 + name: "back",
590 + checks: [...backChecks(list, back.samples), ...(backLag ? [backLag.check] : [])],
591 + lagFrame: backLag?.frame,
592 + screenshot: backShot,
593 + video: back.video,
594 + contactSheet: back.contactSheet,
595 + samples: back.samples.length,
596 + });
597 + return { device: spec, label: spec.id, steps };
598 + } catch (error) {
599 + return {
600 + device: spec,
601 + label: spec.id,
602 + steps,
603 + error: error instanceof Error ? error.message : String(error),
604 + };
605 + }
606 +}
607 +
608 +async function issuePairUrl(environment: { readonly baseDir: string; readonly port: number }) {
609 + const { stdout } = await run(NodeProcess.execPath, [
610 + "apps/server/src/bin.ts",
611 + "auth",
612 + "pairing",
613 + "create",
614 + "--base-dir",
615 + environment.baseDir,
616 + "--base-url",
617 + `http://127.0.0.1:${environment.port}`,
618 + "--ttl",
619 + "15m",
620 + "--json",
621 + ]);
622 + const { pairUrl } = JSON.parse(
623 + stdout.slice(stdout.indexOf("{"), stdout.lastIndexOf("}") + 1),
624 + ) as {
625 + pairUrl?: string;
626 + };
627 + if (!pairUrl) throw new Error("The pairing command returned no pairUrl.");
628 + return pairUrl;
629 +}
630 +
631 +const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
632 +
633 +const escapeHtml = (value: string) =>
634 + value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
635 +
636 +function renderReport(results: ReadonlyArray<DeviceResult>, outputDirectory: string): string {
637 + const relative = (path: string | undefined) =>
638 + path ? escapeHtml(NodePath.relative(outputDirectory, path)) : "";
639 + const rows = results
640 + .map((result) => {
641 + const steps = result.steps
642 + .map((step) => {
643 + const checks = step.checks
644 + .map(
645 + (item) =>
646 + `<li class="${item.pass ? "pass" : "fail"}">${item.pass ? "✓" : "✗"} ${escapeHtml(item.name)} <small>${escapeHtml(item.detail)}</small></li>`,
647 + )
648 + .join("");
649 + const media = [
650 + step.screenshot
651 + ? `<a href="${relative(step.screenshot)}"><img src="${relative(step.screenshot)}"></a>`
652 + : "",
653 + step.lagFrame
654 + ? `<a href="${relative(step.lagFrame)}"><img class="lag" src="${relative(step.lagFrame)}"></a>`
655 + : "",
656 + step.contactSheet
657 + ? `<a href="${relative(step.contactSheet)}">transition frames</a>`
658 + : "",
659 + step.video ? `<a href="${relative(step.video)}">video</a>` : "",
660 + ].join(" ");
661 + return `<td><h3>${escapeHtml(step.name)}</h3><ul>${checks}</ul>${media}</td>`;
662 + })
663 + .join("");
664 + const error = result.error ? `<td class="fail">${escapeHtml(result.error)}</td>` : "";
665 + return `<tr><th>${escapeHtml(result.label)}</th>${steps}${error}</tr>`;
666 + })
667 + .join("");
668 + const failures = results.filter(
669 + (result) => result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
670 + ).length;
671 + return `<!doctype html><meta charset="utf-8"><title>Mobile E2E</title>
672 +<style>body{font:14px system-ui;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:8px;vertical-align:top}img{width:180px;display:block;margin:6px 0}img.lag{outline:3px solid #b42318}.pass{color:#16794a}.fail{color:#b42318}ul{padding-left:16px;margin:4px 0}small{color:#666}</style>
673 +<h1>Mobile E2E · ${failures === 0 ? "all devices passed" : `${failures} device(s) failed`}</h1>
674 +<table>${rows}</table>`;
675 +}
676 +
677 +async function main() {
678 + const args = NodeProcess.argv.slice(2);
679 + if (args.includes("--list")) {
680 + for (const device of DEVICES) NodeProcess.stdout.write(`${device.id}\n`);
681 + return;
682 + }
683 + const selected = args.flatMap((arg, index) => (args[index - 1] === "--device" ? [arg] : []));
684 + const devices = selected.length
685 + ? DEVICES.filter((device) => selected.includes(device.id))
686 + : DEVICES;
687 + const unknown = selected.filter((id) => !DEVICES.some((device) => device.id === id));
688 + if (unknown.length) throw new Error(`Unknown device ${unknown.join(", ")}. Run with --list.`);
689 + const concurrencyArg = args[args.indexOf("--concurrency") + 1];
690 + const concurrency = args.includes("--concurrency") ? Number(concurrencyArg) : 3;
691 +
692 + const stamp = new Date().toISOString().replaceAll(":", "-");
693 + const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", stamp);
694 + await NodeFSP.mkdir(outputDirectory, { recursive: true });
695 + const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
696 + const servers: NodeChildProcess.ChildProcess[] = [];
697 + let metro: NodeChildProcess.ChildProcess | null = null;
698 + try {
699 + log("e2e", "starting the fixture server");
700 + const [environment] = await startShowcaseEnvironments(
701 + rootDir,
702 + (server) => servers.push(server),
703 + SHOWCASE_ENVIRONMENTS.slice(0, 1),
704 + );
705 + if (!environment) throw new Error("The fixture server did not start.");
706 + const metroHost = lanAddress();
707 + metro = NodeChildProcess.spawn(
708 + "vp",
709 + [
710 + "exec",
711 + "expo",
712 + "start",
713 + "--dev-client",
714 + "--scheme",
715 + "t3code-dev",
716 + "--lan",
717 + "--port",
718 + String(METRO_PORT),
719 + ],
720 + {
721 + cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
722 + env: { ...NodeProcess.env, APP_VARIANT: "development", CI: "1" },
723 + stdio: ["ignore", "ignore", "inherit"],
724 + // Its own group, so stopping it also stops the expo child that owns the port.
725 + detached: true,
726 + },
727 + );
728 + await waitForPort(METRO_PORT, "Metro", 120_000);
729 + await run("curl", [
730 + "-sf",
731 + "-o",
732 + "/dev/null",
733 + `http://127.0.0.1:${METRO_PORT}/apps/mobile/index.bundle?platform=ios&dev=true&minify=false`,
734 + ]);
735 +
736 + // The first install may build; later ones reuse its artifact.
737 + const results: DeviceResult[] = [];
738 + const [first, ...rest] = devices;
739 + if (first) results.push(await runDevice(first, outputDirectory, environment, metroHost));
740 + for (let index = 0; index < rest.length; index += concurrency) {
741 + results.push(
742 + ...(await Promise.all(
743 + rest
744 + .slice(index, index + concurrency)
745 + .map((device) => runDevice(device, outputDirectory, environment, metroHost)),
746 + )),
747 + );
748 + }
749 + const report = NodePath.join(outputDirectory, "index.html");
750 + await NodeFSP.writeFile(report, renderReport(results, outputDirectory));
751 + await NodeFSP.writeFile(
752 + NodePath.join(outputDirectory, "report.json"),
753 + JSON.stringify(results, null, 2),
754 + );
755 + const failed = results.filter(
756 + (result) =>
757 + result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
758 + );
759 + for (const result of results) {
760 + const failures = result.steps.flatMap((step) =>
761 + step.checks
762 + .filter((item) => !item.pass)
763 + .map((item) => `${step.name}: ${item.name} (${item.detail})`),
764 + );
765 + log(result.label, result.error ?? (failures.length ? failures.join("; ") : "passed"));
766 + }
767 + NodeProcess.stdout.write(
768 + `${JSON.stringify({ report, devices: results.length, failed: failed.length })}\n`,
769 + );
770 + process.exitCode = failed.length ? 1 : 0;
771 + } finally {
772 + if (metro?.pid) {
773 + try {
774 + process.kill(-metro.pid, "SIGTERM");
775 + } catch {}
776 + await stopProcess(metro);
777 + }
778 + await Promise.all(servers.map((server) => stopProcess(server)));
779 + await NodeFSP.rm(rootDir, { recursive: true, force: true });
780 + }
781 +}
782 +
783 +if (import.meta.main) {
784 + await main();
785 +}
scripts/mobile-showcase.ts
+71 -50
@@ -497,7 +497,7 @@ function delay(milliseconds: number): Promise<void> {
497 return new Promise((resolve) => setTimeout(resolve, milliseconds));
498 }
499
500 -async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
500 +export async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
501 if (child.exitCode !== null || child.signalCode !== null) return;
502
503 const exited = new Promise<void>((resolve) => {
@@ -511,7 +511,11 @@ async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void>
511 await Promise.race([exited, delay(1_000)]);
512 }
513
514 -async function waitForPort(port: number, label = "Process", timeoutMs = 60_000): Promise<void> {
514 +export async function waitForPort(
515 + port: number,
516 + label = "Process",
517 + timeoutMs = 60_000,
518 +): Promise<void> {
519 const deadline = Date.now() + timeoutMs;
520 while (Date.now() < deadline) {
521 const open = await new Promise<boolean>((resolve) => {
@@ -635,6 +639,63 @@ function startShowcaseServer(
639 );
640 }
641
642 +export interface ShowcaseEnvironment {
643 + readonly baseDir: string;
644 + readonly environmentId: string;
645 + readonly label: string;
646 + readonly port: number;
647 +}
648 +
649 +/** Boot one seeded fixture server per showcase environment; `track` receives every spawned server. */
650 +export async function startShowcaseEnvironments(
651 + rootDir: string,
652 + track: (server: NodeChildProcess.ChildProcess) => void,
653 + environments: ReadonlyArray<(typeof SHOWCASE_ENVIRONMENTS)[number]> = SHOWCASE_ENVIRONMENTS,
654 +): Promise<ShowcaseEnvironment[]> {
655 + const started: ShowcaseEnvironment[] = [];
656 + for (const environment of environments) {
657 + const projectId = environment.projectIds[0];
658 + const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === projectId);
659 + if (!project) throw new Error(`Showcase environment '${environment.id}' has no project.`);
660 +
661 + const baseDir = NodePath.join(rootDir, "environments", environment.id);
662 + const workspaceRoot = NodePath.join(baseDir, "workspace", project.directory);
663 + const port = await reserveAvailablePort();
664 + await NodeFSP.mkdir(workspaceRoot, { recursive: true });
665 + const shellPath = await createShowcaseShell(baseDir);
666 + const labelProbeDirectory = await createShowcaseLabelProbe(baseDir, environment.label);
667 + const server = startShowcaseServer(
668 + baseDir,
669 + workspaceRoot,
670 + port,
671 + shellPath,
672 + labelProbeDirectory,
673 + );
674 + track(server);
675 + await waitForPort(port, `${environment.label} server`);
676 + await seedShowcaseEnvironment({ baseDir, projectIds: environment.projectIds });
677 + // Legacy fixture threads are imported into V2 during server startup.
678 + await stopProcess(server);
679 + const seededServer = startShowcaseServer(
680 + baseDir,
681 + workspaceRoot,
682 + port,
683 + shellPath,
684 + labelProbeDirectory,
685 + );
686 + track(seededServer);
687 + await waitForPort(port, `${environment.label} seeded server`);
688 + // The server begins listening before the ServerEnvironment layer
689 + // persists the environment id, so poll rather than read once.
690 + const environmentId = await waitForFileContent(
691 + NodePath.join(baseDir, "userdata", "environment-id"),
692 + `${environment.label} environment id`,
693 + );
694 + started.push({ baseDir, environmentId, label: environment.label, port });
695 + }
696 + return started;
697 +}
698 +
699 export function parsePairingCredentialOutput(output: string): string {
700 const jsonStart = output.indexOf("{");
701 const jsonEnd = output.lastIndexOf("}");
@@ -650,7 +711,7 @@ export function parsePairingCredentialOutput(output: string): string {
711 return parsed.credential;
712 }
713
653 -async function issuePairingCredential(baseDir: string): Promise<string> {
714 +export async function issuePairingCredential(baseDir: string): Promise<string> {
715 const output = await commandOutput(
716 "node",
717 ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", baseDir, "--json"],
@@ -659,7 +720,7 @@ async function issuePairingCredential(baseDir: string): Promise<string> {
720 return parsePairingCredentialOutput(output);
721 }
722
662 -function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
723 +export function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
724 const url = new URL(`http://${host}:${port}/`);
725 url.hash = new URLSearchParams([["token", credential]]).toString();
726 return url.toString();
@@ -1493,57 +1554,17 @@ async function main(): Promise<void> {
1554 NodePath.join(NodeOS.tmpdir(), "t3-mobile-showcase-"),
1555 );
1556 const showcaseServers: NodeChildProcess.ChildProcess[] = [];
1496 - const showcaseEnvironments: Array<{
1497 - readonly baseDir: string;
1498 - readonly environmentId: string;
1499 - readonly label: string;
1500 - readonly port: number;
1501 - }> = [];
1557 + const showcaseEnvironments: ShowcaseEnvironment[] = [];
1558 let metro: NodeChildProcess.ChildProcess | null = null;
1559 const iosCleanups: IosCaptureCleanup[] = [];
1560 const androidCleanups: AndroidCaptureCleanup[] = [];
1561
1562 try {
1507 - for (const environment of SHOWCASE_ENVIRONMENTS) {
1508 - const projectId = environment.projectIds[0];
1509 - const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === projectId);
1510 - if (!project) throw new Error(`Showcase environment '${environment.id}' has no project.`);
1511 -
1512 - const baseDir = NodePath.join(showcaseRootDir, "environments", environment.id);
1513 - const workspaceRoot = NodePath.join(baseDir, "workspace", project.directory);
1514 - const port = await reserveAvailablePort();
1515 - await NodeFSP.mkdir(workspaceRoot, { recursive: true });
1516 - const shellPath = await createShowcaseShell(baseDir);
1517 - const labelProbeDirectory = await createShowcaseLabelProbe(baseDir, environment.label);
1518 - const server = startShowcaseServer(
1519 - baseDir,
1520 - workspaceRoot,
1521 - port,
1522 - shellPath,
1523 - labelProbeDirectory,
1524 - );
1525 - showcaseServers.push(server);
1526 - await waitForPort(port, `${environment.label} server`);
1527 - await seedShowcaseEnvironment({ baseDir, projectIds: environment.projectIds });
1528 - // Legacy fixture threads are imported into V2 during server startup.
1529 - await stopProcess(server);
1530 - const seededServer = startShowcaseServer(
1531 - baseDir,
1532 - workspaceRoot,
1533 - port,
1534 - shellPath,
1535 - labelProbeDirectory,
1536 - );
1537 - showcaseServers.push(seededServer);
1538 - await waitForPort(port, `${environment.label} seeded server`);
1539 - // The server begins listening before the ServerEnvironment layer
1540 - // persists the environment id, so poll rather than read once.
1541 - const environmentId = await waitForFileContent(
1542 - NodePath.join(baseDir, "userdata", "environment-id"),
1543 - `${environment.label} environment id`,
1544 - );
1545 - showcaseEnvironments.push({ baseDir, environmentId, label: environment.label, port });
1546 - }
1563 + showcaseEnvironments.push(
1564 + ...(await startShowcaseEnvironments(showcaseRootDir, (server) =>
1565 + showcaseServers.push(server),
1566 + )),
1567 + );
1568
1569 if (!options.skipMetro) {
1570 metro = startMetro(showcaseConfig);
scripts/package.json
+1
@@ -12,6 +12,7 @@
12 "@electron/osx-sign": "2.7.0",
13 "@t3tools/shared": "workspace:*",
14 "@t3tools/tailscale": "workspace:*",
15 + "agent-device": "0.21.25",
16 "effect": "catalog:",
17 "plist": "catalog:",
18 "pngjs": "7.0.0",
vite.config.ts
-4
@@ -585,10 +585,6 @@ export default defineConfig({
585 files: ["apps/mobile/src/**/*.{ts,tsx}"],
586 rules: { "t3code/no-manual-memo": ["error", { allowMemoHooks: true }] },
587 },
588 - {
589 - files: ["apps/web/src/**", "apps/mobile/src/**", "packages/*/src/**"],
590 - rules: { "t3code/react-effect-budget": "error" },
591 - },
588 {
589 // React Compiler caches use* functions only if they call a hook.
590 files: ["apps/web/src/**/*.{ts,tsx}", "apps/mobile/src/**/*.{ts,tsx}"],