Skip to content

Commit 929a500

Browse files
Merge remote-tracking branch 'origin/main' into L66-20037
# Conflicts: # apps/server/src/mcp/OrchestratorMcpService.ts # apps/server/src/mcp/toolkits/orchestrator/tools.ts
2 parents a9abaa4 + ee3a3e8 commit 929a500

845 files changed

Lines changed: 59440 additions & 29281 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/scripts/ci-changes.cjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const EXTRA_OWNERS = [
3636
// scripts/build-desktop-artifact.ts reads the GNOME extension manifest.
3737
[/^apps\/desktop\/gnome-extension\//, ["@t3tools/scripts"]],
3838
[/^native\/browser-secret\//, ["@t3tools/desktop"]],
39+
[/^native\/kde-snap-shot\//, ["@t3tools/desktop"]],
3940
[/^native\/libghostty-vt\//, ["@t3tools/web"]],
4041
];
4142
const RUST = /^native\/(resource-monitor|kde-snap-shot|hyprland-snap-shot)\//;
@@ -112,10 +113,10 @@ function ownersOf(file, packages) {
112113
// A manifest can change dependencies or versions other packages read.
113114
if (path.posix.basename(file) === "package.json") return null;
114115
if (RUNS_EVERYTHING.some((pattern) => pattern.test(file))) return null;
116+
const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : []));
115117
// scripts/build-desktop-artifact.test.ts reads the crates' sources.
116-
if (RUST.test(file)) return ["@t3tools/scripts"];
118+
if (RUST.test(file)) return ["@t3tools/scripts", ...extra];
117119

118-
const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : []));
119120
const owner = packages
120121
.filter((pkg) => file.startsWith(`${pkg.dir}/`))
121122
.sort((a, b) => b.dir.length - a.dir.length)[0];

‎.github/workflows/cursor-hygiene-webhook.yml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ name: Forward to Cursor hygiene
33
on:
44
push:
55
branches: [main]
6-
pull_request:
6+
# Use trusted workflow code and repository secrets for fork PRs.
7+
# Keep this job payload-only: never check out or run PR code.
8+
pull_request_target:
79
types: [opened, reopened, ready_for_review]
810
issues:
911
types: [opened, closed, reopened]
@@ -34,7 +36,7 @@ jobs:
3436
--output /dev/null --write-out '%{http_code}' \
3537
-H "Authorization: $AUTH" \
3638
-H "Content-Type: application/json" \
37-
-H "X-GitHub-Event: ${{ github.event_name }}" \
39+
-H "X-GitHub-Event: ${{ github.event_name == 'pull_request_target' && 'pull_request' || github.event_name }}" \
3840
-H "X-GitHub-Delivery: ${{ github.run_id }}-${{ github.run_attempt }}" \
3941
--data-binary @"${{ github.event_path }}") || curl_status=$?
4042
if [ "$curl_status" -eq 0 ]; then

‎.github/workflows/deploy-relay.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ jobs:
4141
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
4242
RELAY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_TUNNEL_CLEANUP_MODE }}
4343
RELAY_LEGACY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_LEGACY_TUNNEL_CLEANUP_MODE }}
44+
RELAY_ALERT_NOTIFIER_ID: ${{ vars.RELAY_ALERT_NOTIFIER_ID }}
45+
RELAY_WARNING_NOTIFIER_ID: ${{ vars.RELAY_WARNING_NOTIFIER_ID }}
4446
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
4547
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
4648
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}

‎.macroscope/check-run-agents/effect-service-conventions.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
4444
- Use plain `make` and `layer` in a module named for its implementation (`BunPtyAdapter.ts`). Keep implementation-specific names when one abstract port module holds several implementations (`makeCloudflaredRelayClient`, `layerCloudflared` in `RelayClient.ts`). `infra/relay/src/db.ts` may keep its inline `Layer.succeed(RelayDb, db)`.
4545
- When a service moves, delete the old files and update every consumer, including orchestration, MCP, tests, and integration harnesses. Do not leave compatibility re-export shims.
4646

47+
## Effect functions and tracing
48+
49+
- Reusable functions use named `Effect.fn("Service.operation")`, not functions wrapping
50+
`Effect.gen`. Inline programs, callbacks, and layer construction can keep `Effect.gen`.
51+
- Named `Effect.fn` creates a span; the unnamed form does not. Default to named spans for service
52+
operations and I/O. `Effect.fnUntraced` is deliberate for per-chunk/per-event work, tight loops,
53+
or helpers duplicating an existing tracing boundary; require a nearby reason for new uses.
54+
- Preserve existing span names/options and avoid adding duplicate spans. Pass combinators after
55+
the generator body; transforms receive the original function arguments after the effect.
56+
- Preserve generic signatures, laziness, resource scope, and interruption behavior. An explicit
57+
generator return type is `Effect.fn.Return<A, E, R>`.
58+
4759
## Dependency acquisition and runtime boundaries
4860

4961
- Production service construction acquires its Effect dependencies from the environment with `yield* Foo.Foo`, and `make`/`layer` types expose those requirements. Flag a factory that takes `Foo["Service"]` (or an object of Effect-returning methods) as a parameter when that value is a service dependency. Passing service instances explicitly in tests is fine; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
@@ -57,6 +69,7 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
5769
- Define service failures with `Schema.TaggedError` and structured attributes: operation or stage, resource path or entity identifier, normalized category or status. Derive `message` from those attributes only. Never derive it from `cause`, `cause.message`, or a stringified defect, and do not add a `detail` field that copies `cause.message`.
5870
- When wrapping a real failure, keep the immediate underlying error as `cause` so the chain and stack survive. Make `cause` required if every construction wraps a failure. Pure validation or domain errors created without an underlying failure need no cause.
5971
- Keep attributes and log annotations safe and bounded: no raw wire payloads, command arguments or output, signed URLs, credentials, query strings, or arbitrary defect text. Preserve the exact value only as `cause`; expose normalized categories, lengths, counts, and safe URL protocol or hostname where useful.
72+
The documented exception is `DeviceBootError.diagnostics`: device hub launch commands and failure text are intentionally exposed to authorized device users and agents, capped at 2,000 characters and included in the error message. Do not apply this exception to other service errors.
6073
- At a translation boundary, pass through an already structured domain error when it is part of the target error channel; wrap only unknown or lower-level failures. Map failures where the context is known instead of wrapping a whole multi-step pipeline in one generic error.
6174
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Split into separate error classes when a discriminator drives caller control flow or the user-facing message; a discriminator used only for diagnostics may stay a field. Caller-visible messages exposed through HTTP, RPC, persisted state, or UI are behavior and must survive a structural refactor.
6275
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`. Construct the error at the failure boundary. Keep a mapper only when it performs real normalization, passes through domain errors, or adds reusable context; when such a mapper belongs to the target error type, prefer a static factory on that class.

‎AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,12 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/
153153
- Client mutations use `createEnvironmentRpcCommand`. Add protected methods to `CLIENT_GUARDED_RPC_SCOPES` in contracts and use the command's `permissionAtom` for UI availability. Grants are checked at execution against the destination environment; the server remains authoritative. Keep raw RPC clients inside `rpc/`, and extend the permission behavior tests when adding a protected method.
154154
- Server features are services; transports stay thin. A `ws.ts` RPC handler, HTTP route, or MCP tool decodes input, calls one service method, and maps errors. See [Effect services](docs/internals/effect-services.md).
155155
- `apps/web/src/components/ui` exports own their look. Pick a `variant` or `size`; do not restyle one with `className`. If none fits and the look is a generic concept, add a variant to the component; a look that belongs to one feature stays in that feature's own component, not in `components/ui`. Layout classes (width, flex, margin, position) belong on the parent. `shadcn/no-restyle` fails lint on violations. See [Web UI](docs/internals/web-ui.md).
156+
- Reusable Effect functions use `Effect.fn("Service.operation")` with a stable span name, not a
157+
function wrapping `Effect.gen`. Keep `Effect.gen` for inline programs and layer construction.
158+
Use `Effect.fnUntraced` only when spans would be too frequent (stream chunks, per-event
159+
projection, tight loops) or duplicate an existing tracing boundary; explain that choice nearby.
160+
Named `Effect.fn` creates a span; the unnamed form does not. Preserve existing span names and
161+
options, and pass combinators as additional function-builder arguments.
156162
- Inferred types over annotations. `any` is the enemy.
157163
- Comments say why: a constraint, an external quirk, or an invariant the code can't show. Don't restate names or signatures, narrate steps, or record history. `t3code/no-low-value-comments` catches the mechanical cases.
158164
- 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.

‎apps/desktop/scripts/dev-electron.mjs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,14 @@ function cleanupStaleDevApps() {
9494
return;
9595
}
9696

97-
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
98-
stdio: "ignore",
99-
});
97+
const escapedDesktopDir = desktopDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
98+
NodeChildProcess.spawnSync(
99+
"pkill",
100+
["-f", "--", `(^| )--t3code-dev-root=${escapedDesktopDir}( |$)`],
101+
{
102+
stdio: "ignore",
103+
},
104+
);
100105
}
101106

102107
function startApp() {

‎apps/desktop/scripts/electron-launcher.test.mjs‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import * as NodeChildProcess from "node:child_process";
2+
import * as NodeEvents from "node:events";
13
import * as NodeFS from "node:fs";
24
import * as NodeOS from "node:os";
35
import * as NodePath from "node:path";
6+
import * as NodeVM from "node:vm";
47

58
import { assert, describe, it } from "vite-plus/test";
69

@@ -151,3 +154,93 @@ describe("electron development launcher", () => {
151154
assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns");
152155
});
153156
});
157+
158+
async function startupCleanupPattern(desktopDir) {
159+
const source = NodeFS.readFileSync(new URL("./dev-electron.mjs", import.meta.url), "utf8");
160+
let pattern;
161+
// Supply inert imports so the real startup runs without launching Electron or signalling processes.
162+
await NodeVM.runInNewContext(
163+
`(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`,
164+
{
165+
NodeChildProcess: {
166+
execFileSync: () => undefined,
167+
spawnSync: (command, args) => {
168+
if (command === "pkill" && args.includes("-f")) pattern = args.at(-1);
169+
},
170+
spawn: () => new NodeEvents.EventEmitter(),
171+
},
172+
NodeFS: { watch: () => ({ close: () => undefined }) },
173+
NodeOS: { platform: () => "linux" },
174+
NodePath,
175+
desktopDir,
176+
resolveDevProtocolClient: () => null,
177+
resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }),
178+
waitForResources: async () => undefined,
179+
URL,
180+
process: {
181+
env: { VITE_DEV_SERVER_URL: "http://localhost:1234" },
182+
execPath: "node",
183+
once: () => undefined,
184+
},
185+
},
186+
);
187+
assert.isString(pattern);
188+
return pattern;
189+
}
190+
191+
it
192+
// oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows.
193+
.skipIf(NodeOS.platform() === "win32")
194+
.each([
195+
"/tmp/t3-feature.one/apps/desktop",
196+
"/tmp/t3-feature.one [two](three)+?^${four}|back\\slash*/apps/desktop",
197+
])("dev cleanup matches only the literal root argument: %s", async (desktopDir) => {
198+
const pattern = await startupCleanupPattern(desktopDir);
199+
const flag = `--t3code-dev-root=${desktopDir}`;
200+
const argvCases = [
201+
[flag],
202+
[flag, "main.cjs"],
203+
[flag.replace(".one", "Xone")],
204+
[`${flag}-two`],
205+
[`prefix${flag}`],
206+
[`--t3code-dev-root=/other${desktopDir}`],
207+
];
208+
const children = [];
209+
try {
210+
for (const args of argvCases) {
211+
const child = NodeChildProcess.spawn(
212+
process.execPath,
213+
["-e", "process.send('ready'); setInterval(() => {}, 1000)", "--", ...args],
214+
{ stdio: ["ignore", "ignore", "inherit", "ipc"] },
215+
);
216+
children.push(child);
217+
await Promise.race([
218+
NodeEvents.once(child, "message"),
219+
NodeEvents.once(child, "exit").then(() => {
220+
throw new Error("Fixture exited before readiness");
221+
}),
222+
]);
223+
}
224+
// Use the native ERE engine, but never execute the launcher's signal-producing command.
225+
const result = NodeChildProcess.spawnSync(
226+
"pgrep",
227+
["-P", String(process.pid), "-f", "--", pattern],
228+
{ encoding: "utf8" },
229+
);
230+
assert.equal(result.status, 0, result.stderr);
231+
const matches = result.stdout.trim().split(/\s+/).map(Number);
232+
assert.sameMembers(
233+
matches,
234+
children.slice(0, 2).map((child) => child.pid),
235+
);
236+
} finally {
237+
await Promise.all(
238+
children.map(async (child) => {
239+
if (child.exitCode !== null || child.signalCode !== null) return;
240+
const exited = NodeEvents.once(child, "exit");
241+
child.kill("SIGTERM");
242+
await exited;
243+
}),
244+
);
245+
}
246+
});

‎apps/desktop/src/app/DesktopAppErrors.test.ts‎

Lines changed: 0 additions & 30 deletions
This file was deleted.

‎apps/desktop/src/app/DesktopClerk.test.ts‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Hosted handoff test uses a real localhost listener without an OpenAI account.
22
import * as NodeHttp from "node:http";
3-
import * as NodePath from "@effect/platform-node/NodePath";
3+
import * as NodePath from "node:path";
4+
import * as PlatformNodePath from "@effect/platform-node/NodePath";
45
import { codexAuthHandoffUrl, readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
56
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
67
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -59,11 +60,15 @@ const layerDesktopClerk = (
5960
copyText: () => Effect.void,
6061
},
6162
listeners = new Map<string, (...args: unknown[]) => void>(),
63+
isPackaged = false,
6264
) => {
6365
const environment = DesktopEnvironment.DesktopEnvironment.of({
6466
stateDir: "/tmp/t3-state",
6567
isDevelopment,
6668
appDataDirectory: "/tmp/app-data",
69+
isPackaged,
70+
dirname: platform === "win32" ? String.raw`C:\T3 Code\dist-electron` : "/tmp/dist-electron",
71+
path: platform === "win32" ? NodePath.win32 : NodePath.posix,
6772
platform,
6873
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
6974

@@ -95,7 +100,7 @@ const layerDesktopClerk = (
95100
return DesktopClerk.layer.pipe(
96101
Layer.provide(
97102
Layer.mergeAll(
98-
NodePath.layerPosix,
103+
PlatformNodePath.layerPosix,
99104
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
100105
Layer.succeed(ElectronApp.ElectronApp, electronApp),
101106
Layer.succeed(ElectronShell.ElectronShell, shell),
@@ -112,6 +117,67 @@ describe("DesktopClerk", () => {
112117
storageMock.mockReset();
113118
});
114119

120+
it.effect.each([
121+
{ platform: "win32", isPackaged: false, isDevelopment: false, registers: true },
122+
{ platform: "win32", isPackaged: false, isDevelopment: true, registers: false },
123+
{ platform: "win32", isPackaged: true, isDevelopment: false, registers: false },
124+
{ platform: "darwin", isPackaged: false, isDevelopment: false, registers: false },
125+
{ platform: "linux", isPackaged: false, isDevelopment: false, registers: false },
126+
] as const)(
127+
"registers an entry point only for unpackaged non-development Windows ($platform, packaged=$isPackaged, development=$isDevelopment)",
128+
({ platform, isPackaged, isDevelopment, registers }) => {
129+
const events: string[] = [];
130+
storageMock.mockReturnValue(storageAdapter);
131+
createClerkBridgeMock.mockImplementation(() => {
132+
events.push("bridge");
133+
return { cleanup: vi.fn() };
134+
});
135+
const setAsDefaultProtocolClient = vi.fn(() =>
136+
Effect.sync(() => {
137+
events.push("register");
138+
return true;
139+
}),
140+
);
141+
const electronApp = {
142+
on: () => Effect.void,
143+
setAsDefaultProtocolClient,
144+
} as unknown as ElectronApp.ElectronApp["Service"];
145+
146+
return Effect.gen(function* () {
147+
const clerk = yield* DesktopClerk.DesktopClerk;
148+
yield* clerk.configure;
149+
150+
assert.deepEqual(
151+
setAsDefaultProtocolClient.mock.calls,
152+
registers
153+
? [["t3code", process.execPath, [String.raw`C:\T3 Code\dist-electron\main.cjs`]]]
154+
: [],
155+
);
156+
assert.deepEqual(events, registers ? ["bridge", "register"] : ["bridge"]);
157+
}).pipe(
158+
Effect.scoped,
159+
Effect.provide(
160+
layerDesktopClerk(
161+
isDevelopment,
162+
[],
163+
platform,
164+
undefined,
165+
undefined,
166+
undefined,
167+
isPackaged,
168+
),
169+
),
170+
Effect.provideService(ElectronApp.ElectronApp, electronApp),
171+
Effect.provideService(
172+
ElectronWindow.ElectronWindow,
173+
{} as ElectronWindow.ElectronWindow["Service"],
174+
),
175+
Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
176+
Effect.provideService(HostProcess.Arguments, ["electron"]),
177+
);
178+
},
179+
);
180+
115181
it.effect("acquires and releases the SDK bridge with the layer", () => {
116182
const cleanup = vi.fn();
117183
const events: string[] = [];

‎apps/desktop/src/app/DesktopClerk.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,20 @@ export const make = Effect.gen(function* () {
151151
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
152152
const runPromise = Effect.runPromiseWith(context);
153153

154+
// Clerk's bare scheme registration omits the app entry on unpackaged Windows.
155+
// Development callbacks also need dev server environment this command cannot restore.
156+
if (
157+
!environment.isPackaged &&
158+
!environment.isDevelopment &&
159+
environment.platform === "win32"
160+
) {
161+
yield* electronApp.setAsDefaultProtocolClient(
162+
ElectronProtocol.getDesktopScheme(environment.isDevelopment),
163+
process.execPath,
164+
[environment.path.join(environment.dirname, "main.cjs")],
165+
);
166+
}
167+
154168
const startProviderAuthHandoff = (value: string | undefined) => {
155169
if (!value) return false;
156170
const request = readCodexAuthHandoff(value, environment.isDevelopment);

0 commit comments

Comments
 (0)