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, 20:45 UTC
test(server): prune low-value tests in apps/server (second pass) (#22592)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 20, 2026 at 18:31 UTC
a2f4df041238a29231e2ef2c8f10a64a53ad8546
91 files changed
+58
-2809
apps/server/scripts/migrate-dev-db.test.ts
-27
@@ -194,33 +194,6 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
194
}),
195
);
196
197
- it.effect("fails loudly on a migration slot collision", () =>
198
- Effect.gen(function* () {
199
- const fs = yield* FileSystem.FileSystem;
200
- const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-" });
201
- const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-dest-" });
202
- const source = yield* createFixtureSource(sourceDir);
203
- yield* withDatabase(
204
- source,
205
- Effect.gen(function* () {
206
- const sql = yield* SqlClient.SqlClient;
207
- yield* sql`UPDATE effect_sql_migrations
208
- SET name = 'SomebodyElsesMigration' WHERE migration_id = 1`;
209
- }),
210
- );
211
-
212
- const error = yield* runMigrateDevDb(
213
- { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
214
- { sharedHome: sourceDir },
215
- ).pipe(Effect.flip);
216
- assert.equal(error._tag, "MigrateDevDbSlotCollisionError");
217
- if (error._tag === "MigrateDevDbSlotCollisionError") {
218
- assert.equal(error.slot, 1);
219
- assert.equal(error.appliedName, "SomebodyElsesMigration");
220
- }
221
- }),
222
- );
223
-
197
it.effect("refuses while a dev server holds the destination", () =>
198
Effect.gen(function* () {
199
const fs = yield* FileSystem.FileSystem;
apps/server/src/assets/AssetAccess.test.ts
+1
-34
@@ -163,6 +163,7 @@ describe("AssetAccess", () => {
163
}).pipe(Effect.provide(NodeServices.layer)),
164
);
165
166
+ // regression: #17026 apply host color scheme to saved MCP apps
167
it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
168
Effect.gen(function* () {
169
const fileSystem = yield* FileSystem.FileSystem;
@@ -684,40 +685,6 @@ describe("AssetAccess", () => {
685
}).pipe(Effect.provide(layerTest)),
686
);
687
687
- it.effect("issues draft workspace URLs without a thread", () =>
688
- Effect.gen(function* () {
689
- const fileSystem = yield* FileSystem.FileSystem;
690
- const path = yield* Path.Path;
691
- const root = yield* fileSystem.makeTempDirectoryScoped({
692
- prefix: "t3-asset-draft-",
693
- });
694
- const htmlPath = path.join(root, "report.html");
695
- const cssPath = path.join(root, "report.css");
696
- yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
697
- yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
698
- const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
699
- const canonicalCssPath = yield* fileSystem.realPath(cssPath);
700
-
701
- const result = yield* issueAssetUrl({
702
- resource: { _tag: "draft-workspace-file", cwd: root, path: "report.html" },
703
- workspaceRoot: root,
704
- });
705
- const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
706
- const separatorIndex = suffix.indexOf("/");
707
- const token = suffix.slice(0, separatorIndex);
708
-
709
- expect(yield* resolveAsset(token, "report.html")).toEqual({
710
- kind: "file",
711
- path: canonicalHtmlPath,
712
- });
713
- expect(yield* resolveAsset(token, "report.css")).toEqual({
714
- kind: "file",
715
- path: canonicalCssPath,
716
- });
717
- expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
718
- }).pipe(Effect.provide(layerTest)),
719
- );
720
-
688
it.effect("previews workspace files with literal fragment characters in their paths", () =>
689
Effect.gen(function* () {
690
const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/attachmentStore.test.ts
-35
@@ -13,7 +13,6 @@ import {
13
parseAttachmentUuid,
14
planAttachmentClaim,
15
parseThreadSegmentFromAttachmentId,
16
- resolveAttachmentPathById,
16
sweepStalePendingAttachments,
17
threadHtmlRenderAttachmentIds,
18
} from "./attachmentStore.ts";
@@ -60,21 +59,6 @@ describe("attachmentStore", () => {
59
expect(dashed && parseThreadSegmentFromAttachmentId(dashed)).toBe("thread-a");
60
});
61
63
- it("sanitizes thread ids when creating attachment ids", () => {
64
- const attachmentId = createAttachmentId("thread.folder/unsafe space");
65
- expect(attachmentId).toBeTruthy();
66
- if (!attachmentId) {
67
- return;
68
- }
69
-
70
- const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
71
- expect(threadSegment).toBeTruthy();
72
- expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
73
- expect(threadSegment).not.toContain(".");
74
- expect(threadSegment).not.toContain("%");
75
- expect(threadSegment).not.toContain("/");
76
- });
77
-
62
it("parses exact thread segments from attachment ids without prefix collisions", () => {
63
const fooId = "foo-00000000-0000-4000-8000-000000000001";
64
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
@@ -93,25 +77,6 @@ describe("attachmentStore", () => {
77
);
78
});
79
96
- it("resolves attachment path by id using the extension that exists on disk", () => {
97
- const attachmentsDir = NodeFS.mkdtempSync(
98
- NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
99
- );
100
- try {
101
- const attachmentId = "thread-1-attachment";
102
- const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
103
- NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
104
-
105
- const resolved = resolveAttachmentPathById({
106
- attachmentsDir,
107
- attachmentId,
108
- });
109
- expect(resolved).toBe(pngPath);
110
- } finally {
111
- NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
112
- }
113
- });
114
-
80
it("plans pending attachment claims with direct filename lookups", () => {
81
const attachmentsDir = NodeFS.mkdtempSync(
82
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-claim-"),
apps/server/src/auth/EnvironmentAuth.test.ts
-20
@@ -255,26 +255,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
255
),
256
);
257
258
- it.effect("issues standard pairing credentials by default", () =>
259
- Effect.gen(function* () {
260
- const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
261
- const sessions = yield* SessionStore.SessionStore;
262
-
263
- const pairingCredential = yield* serverAuth.issuePairingCredential();
264
- const exchanged = yield* serverAuth.createBrowserSession(
265
- pairingCredential.credential,
266
- requestMetadata,
267
- );
268
- const verified = yield* serverAuth.authenticateHttpRequest(
269
- makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
270
- );
271
-
272
- expect(verified.sessionId.length).toBeGreaterThan(0);
273
- expect(verified.scopes).toEqual(AuthStandardClientScopes);
274
- expect(verified.subject).toBe("one-time-token");
275
- }).pipe(Effect.provide(layerEnvironmentAuth())),
276
- );
277
-
258
it.effect("prefers a bearer token over a stale legacy cookie", () =>
259
Effect.gen(function* () {
260
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuthPolicy.test.ts
-19
@@ -79,23 +79,4 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
79
),
80
),
81
);
82
-
83
- it.effect("isolates wildcard-bound web development sessions", () =>
84
- Effect.gen(function* () {
85
- const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
86
- const descriptor = yield* policy.getDescriptor();
87
-
88
- expect(descriptor.policy).toBe("remote-reachable");
89
- expect(descriptor.sessionCookieName).toMatch(/^t3_session_5775_[a-f0-9]{12}$/);
90
- }).pipe(
91
- Effect.provide(
92
- layerEnvironmentAuthPolicy({
93
- mode: "web",
94
- host: "0.0.0.0",
95
- port: 5775,
96
- devUrl: new URL("http://127.0.0.1:5736"),
97
- }),
98
- ),
99
- ),
100
- );
82
});
apps/server/src/auth/PairingGrantStore.test.ts
-48
@@ -124,27 +124,6 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
124
}).pipe(Effect.provide(layerPairingGrantStore())),
125
);
126
127
- it.effect("seeds the desktop bootstrap credential as a reusable grant", () =>
128
- Effect.gen(function* () {
129
- const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
130
- const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
131
- const second = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
132
- const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
133
-
134
- expect(first.method).toBe("desktop-bootstrap");
135
- expect(first.scopes).toEqual(AuthStandardClientScopes);
136
- expect(first.subject).toBe("desktop-bootstrap");
137
- expect(second.method).toBe("desktop-bootstrap");
138
- expect(third.method).toBe("desktop-bootstrap");
139
- }).pipe(
140
- Effect.provide(
141
- layerPairingGrantStore({
142
- desktopBootstrapToken: "desktop-bootstrap-token",
143
- }),
144
- ),
145
- ),
146
- );
147
-
127
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
128
Effect.gen(function* () {
129
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
@@ -228,31 +207,4 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
207
}
208
}).pipe(Effect.scoped, Effect.provide(layerPairingGrantStore())),
209
);
231
-
232
- it.effect("lists and revokes active pairing links", () =>
233
- Effect.gen(function* () {
234
- const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
235
- const first = yield* bootstrapCredentials.issueOneTimeToken();
236
- const second = yield* bootstrapCredentials.issueOneTimeToken({
237
- scopes: ["orchestration:read", "access:write"],
238
- });
239
-
240
- const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
241
- expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
242
- expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
243
- for (const entry of activeBeforeRevoke) {
244
- expect(entry).not.toHaveProperty("credential");
245
- }
246
-
247
- const revoked = yield* bootstrapCredentials.revoke(first.id);
248
- const activeAfterRevoke = yield* bootstrapCredentials.listActive();
249
- const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
250
-
251
- expect(revoked).toBe(true);
252
- expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
253
- expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
254
- expect(revokedConsume.message).toContain("no longer available");
255
- expect(revokedConsume._tag).toBe("UnavailableBootstrapCredentialError");
256
- }).pipe(Effect.provide(layerPairingGrantStore())),
257
- );
210
});
apps/server/src/auth/RpcAuthorization.test.ts
+1
-133
@@ -8,12 +8,8 @@ import {
8
ProviderInstanceId,
9
ThreadId,
10
AuthOrchestrationOperateScope,
11
- ORCHESTRATION_V2_WS_METHODS,
11
AuthOrchestrationReadScope,
12
AuthSourceControlWriteScope,
14
- AuthPreviewOperateScope,
15
- AuthRelayReadScope,
16
- AuthRelayWriteScope,
13
AuthTerminalReadScope,
14
AuthTerminalOperateScope,
15
WS_METHODS,
@@ -37,27 +33,6 @@ describe("RPC authorization scopes", () => {
33
expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
34
});
35
40
- it("requires operate access to stop a workflow", () => {
41
- expect(requiredScopeForRpcMethod(ORCHESTRATION_V2_WS_METHODS.stopWorkflow)).toBe(
42
- AuthOrchestrationOperateScope,
43
- );
44
- });
45
-
46
- it("authorizes background policy reporting and observation deliberately", () => {
47
- expect(requiredScopeForRpcMethod(WS_METHODS.serverReportClientActivity)).toBe(
48
- AuthOrchestrationReadScope,
49
- );
50
- expect(requiredScopeForRpcMethod(WS_METHODS.serverReportHostPowerState)).toBe(
51
- AuthEnvironmentMaintainScope,
52
- );
53
- expect(requiredScopeForRpcMethod(WS_METHODS.serverGetBackgroundPolicy)).toBe(
54
- AuthOrchestrationReadScope,
55
- );
56
- expect(requiredScopeForRpcMethod(WS_METHODS.subscribeBackgroundPolicy)).toBe(
57
- AuthOrchestrationReadScope,
58
- );
59
- });
60
-
36
it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
37
for (const method of [
38
WS_METHODS.scheduledTasksListWebhookDeliveries,
@@ -68,109 +43,6 @@ describe("RPC authorization scopes", () => {
43
}
44
});
45
71
- it("allows relay status reads without granting relay installation access", () => {
72
- expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(
73
- AuthRelayReadScope,
74
- );
75
- expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
76
- });
77
-
78
- it("requires permission to operate on a thread before uploading feedback", () => {
79
- expect(requiredScopeForRpcMethod(WS_METHODS.providerUploadFeedback)).toBe(
80
- AuthOrchestrationOperateScope,
81
- );
82
- });
83
-
84
- it("requires write access to import agent session history", () => {
85
- expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsScan)).toBe(
86
- AuthOrchestrationReadScope,
87
- );
88
- expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsImport)).toBe(
89
- AuthOrchestrationOperateScope,
90
- );
91
- });
92
-
93
- it("separates ACP Registry discovery from provisioning", () => {
94
- expect(requiredScopeForRpcMethod(WS_METHODS.serverSearchAcpRegistry)).toBe(
95
- AuthOrchestrationReadScope,
96
- );
97
- expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareAcpRegistryAgent)).toBe(
98
- AuthProvidersManageScope,
99
- );
100
- expect(requiredScopeForRpcMethod(WS_METHODS.serverUninstallAcpRegistryManagedBinary)).toBe(
101
- AuthProvidersManageScope,
102
- );
103
- expect(requiredScopeForRpcMethod(WS_METHODS.serverAcceptAcpRegistryUrlAuth)).toBe(
104
- AuthProvidersManageScope,
105
- );
106
- expect(requiredScopeForRpcMethod(WS_METHODS.serverListAcpRegistrySessions)).toBe(
107
- AuthOrchestrationReadScope,
108
- );
109
- expect(requiredScopeForRpcMethod(WS_METHODS.serverImportAcpRegistrySession)).toBe(
110
- AuthOrchestrationOperateScope,
111
- );
112
- expect(requiredScopeForRpcMethod(WS_METHODS.serverLogoutAcpRegistry)).toBe(
113
- AuthProvidersManageScope,
114
- );
115
- });
116
-
117
- it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
118
- expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsChecks)).toBe(
119
- AuthOrchestrationReadScope,
120
- );
121
- expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsReviewerCandidates)).toBe(
122
- requiredScopeForRpcMethod(WS_METHODS.pullRequestsDetail),
123
- );
124
- expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsRequestReviewers)).toBe(
125
- requiredScopeForRpcMethod(WS_METHODS.pullRequestsComment),
126
- );
127
- });
128
-
129
- it("requires source control writes to start, retry, or cancel project clones", () => {
130
- for (const method of [
131
- WS_METHODS.projectCloneStart,
132
- WS_METHODS.projectCloneRetry,
133
- WS_METHODS.projectCloneCancel,
134
- ]) {
135
- expect(requiredScopeForRpcMethod(method)).toBe(AuthSourceControlWriteScope);
136
- }
137
- expect(requiredScopeForRpcMethod(WS_METHODS.subscribeProjectClones)).toBe(
138
- AuthOrchestrationReadScope,
139
- );
140
- });
141
-
142
- it("separates viewing pull request file progress from writing it", () => {
143
- expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsFilesViewed)).toBe(
144
- AuthOrchestrationReadScope,
145
- );
146
- expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsSetFilesViewed)).toBe(
147
- AuthSourceControlWriteScope,
148
- );
149
- });
150
-
151
- it("separates preview control from observation", () => {
152
- for (const method of [
153
- WS_METHODS.previewOpen,
154
- WS_METHODS.previewNavigate,
155
- WS_METHODS.previewResize,
156
- WS_METHODS.previewRefresh,
157
- WS_METHODS.previewClose,
158
- WS_METHODS.previewReportStatus,
159
- WS_METHODS.previewAdjust,
160
- WS_METHODS.previewClearProfile,
161
- WS_METHODS.previewReportProfiles,
162
- ]) {
163
- expect(requiredScopeForRpcMethod(method)).toBe(AuthPreviewOperateScope);
164
- }
165
- for (const method of [
166
- WS_METHODS.previewList,
167
- WS_METHODS.subscribePreviewEvents,
168
- WS_METHODS.subscribeDiscoveredLocalServers,
169
- ]) {
170
- expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
171
- }
172
- });
173
-
46
it("separates passive terminal observation from operations that can change a shell", () => {
47
for (const method of [
48
WS_METHODS.terminalObserve,
@@ -230,10 +102,6 @@ describe("RPC scope middleware", () => {
102
scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
103
missing: AuthDiagnosticsReadScope,
104
},
233
- {
234
- scopes: [AuthOrchestrationReadScope, AuthDiagnosticsReadScope],
235
- missing: AuthEnvironmentMaintainScope,
236
- },
105
])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
106
Effect.gen(function* () {
107
const handled: Array<string> = [];
@@ -377,7 +245,7 @@ describe("thread context authorization", () => {
245
),
246
);
247
380
- it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] as const)(
248
+ it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
249
"%s needs thread read permission only when generating a PR from a thread",
250
(action) =>
251
Effect.gen(function* () {
apps/server/src/auth/ServerSecretStore.test.ts
-49
@@ -118,16 +118,6 @@ const layerConcurrentCreateSecretStore = () =>
118
);
119
120
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
121
- it.effect("returns Option.none when a secret file does not exist", () =>
122
- Effect.gen(function* () {
123
- const secretStore = yield* ServerSecretStore.ServerSecretStore;
124
-
125
- const secret = yield* secretStore.get("missing-secret");
126
-
127
- assert.isTrue(Option.isNone(secret));
128
- }).pipe(Effect.provide(layerServerSecretStore())),
129
- );
130
-
121
it.effect("reuses an existing secret instead of regenerating it", () =>
122
Effect.gen(function* () {
123
const secretStore = yield* ServerSecretStore.ServerSecretStore;
@@ -158,45 +148,6 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
148
}).pipe(Effect.provide(layerConcurrentCreateSecretStore())),
149
);
150
161
- it.effect("uses restrictive permissions for the secret directory and files", () =>
162
- Effect.gen(function* () {
163
- const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
164
- const layerRecordingFileSystem = Layer.effect(
165
- FileSystem.FileSystem,
166
- Effect.gen(function* () {
167
- const fileSystem = yield* FileSystem.FileSystem;
168
-
169
- return {
170
- ...fileSystem,
171
- makeDirectory: () => Effect.void,
172
- writeFile: () => Effect.void,
173
- rename: () => Effect.void,
174
- chmod: (path, mode) =>
175
- Effect.sync(() => {
176
- chmodCalls.push({ path: String(path), mode });
177
- }),
178
- } satisfies FileSystem.FileSystem;
179
- }),
180
- ).pipe(Layer.provide(NodeServices.layer));
181
-
182
- const secretStore = yield* Effect.service(ServerSecretStore.ServerSecretStore).pipe(
183
- Effect.provide(
184
- ServerSecretStore.layer.pipe(
185
- Layer.provide(layerServerConfig()),
186
- Layer.provideMerge(layerRecordingFileSystem),
187
- ),
188
- ),
189
- );
190
-
191
- yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
192
-
193
- assert.isTrue(
194
- chmodCalls.some((call) => call.mode === 0o700 && /[\\/]secrets$/.test(call.path)),
195
- );
196
- assert.isAtLeast(chmodCalls.filter((call) => call.mode === 0o600).length, 2);
197
- }).pipe(Effect.provide(NodeServices.layer)),
198
- );
199
-
151
it.effect("propagates read failures other than missing-file errors", () =>
152
Effect.gen(function* () {
153
const secretStore = yield* ServerSecretStore.ServerSecretStore;
apps/server/src/auth/SessionStore.test.ts
+1
-153
@@ -1,5 +1,5 @@
1
import * as NodeServices from "@effect/platform-node/NodeServices";
2
-import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
import { expect, it } from "@effect/vitest";
4
import * as Duration from "effect/Duration";
5
import * as Effect from "effect/Effect";
@@ -14,10 +14,8 @@ import * as SqlClient from "effect/sql/SqlClient";
14
15
import * as ServerConfig from "../config.ts";
16
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
17
-import { PersistenceSqlError } from "../persistence/Errors.ts";
17
18
import * as SqlitePersistence from "../persistence/Sqlite.ts";
20
-import * as AuthSessions from "../persistence/AuthSessions.ts";
19
import * as SessionStore from "./SessionStore.ts";
20
import * as ServerSecretStore from "./ServerSecretStore.ts";
21
import { base64UrlDecodeUtf8, base64UrlEncode, signPayload } from "./utils.ts";
@@ -84,34 +82,6 @@ const makeDiskSessionStoreLayer = Effect.fn("makeDiskSessionStoreLayer")(functio
82
);
83
});
84
87
-const repositoryFailure = new PersistenceSqlError({
88
- operation: "AuthSessionRepository.getById:query",
89
- detail: "sqlite is unavailable",
90
-});
91
-
92
-const layerFailingSessionLookupRepository = Layer.succeed(AuthSessions.AuthSessionRepository, {
93
- create: () => Effect.void,
94
- createReplacingActive: () => Effect.succeed([]),
95
- createIfAbsent: () => Effect.void,
96
- getById: () => Effect.fail(repositoryFailure),
97
- listActive: () => Effect.succeed([]),
98
- revoke: () => Effect.fail(repositoryFailure),
99
- revokeAllExcept: () => Effect.fail(repositoryFailure),
100
- setLastConnectedAt: () => Effect.void,
101
- setClientConnection: () => Effect.void,
102
-});
103
-
104
-const layerFailingSessionLookupCredential = Layer.effect(
105
- SessionStore.SessionStore,
106
- SessionStore.make,
107
-).pipe(
108
- Layer.provide(layerFailingSessionLookupRepository),
109
- Layer.provide(ServerSecretStore.layer),
110
- Layer.provide(SqlitePersistence.layerMemory),
111
- Layer.provide(layerServerEnvironment(EnvironmentId.make("test-environment"))),
112
- Layer.provide(layerServerConfig()),
113
-);
114
-
85
it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
86
it.effect.each(["revoke", "revokeAllExcept", "replace"] as const)(
87
"invalidates every connection for a session on %s and leaves other sessions active",
@@ -277,30 +247,6 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
247
}),
248
);
249
280
- it.effect("issues and verifies signed browser session tokens", () =>
281
- Effect.gen(function* () {
282
- const sessions = yield* SessionStore.SessionStore;
283
- const issued = yield* sessions.issue({
284
- subject: "desktop-bootstrap",
285
- scopes: ["orchestration:read", "access:write"],
286
- client: {
287
- label: "Desktop app",
288
- deviceType: "desktop",
289
- os: "macOS",
290
- browser: "Electron",
291
- ipAddress: "127.0.0.1",
292
- },
293
- });
294
- const verified = yield* sessions.verify(issued.token);
295
-
296
- expect(verified.method).toBe("browser-session-cookie");
297
- expect(verified.subject).toBe("desktop-bootstrap");
298
- expect(verified.scopes).toEqual(["orchestration:read", "access:write"]);
299
- expect(verified.client.label).toBe("Desktop app");
300
- expect(verified.client.browser).toBe("Electron");
301
- expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
302
- }).pipe(Effect.provide(layerSessionStore())),
303
- );
250
it.effect("carries a runtime-mode ceiling only on sessions issued with one", () =>
251
Effect.gen(function* () {
252
const sessions = yield* SessionStore.SessionStore;
@@ -342,66 +288,6 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
288
),
289
);
290
345
- it.effect("rejects malformed session tokens", () =>
346
- Effect.gen(function* () {
347
- const sessions = yield* SessionStore.SessionStore;
348
- const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
349
-
350
- expect(error._tag).toBe("MalformedSessionTokenError");
351
- expect(error.message).toContain("Malformed session token");
352
- }).pipe(Effect.provide(layerSessionStore())),
353
- );
354
- it.effect("preserves repository failures while verifying session and websocket credentials", () =>
355
- Effect.gen(function* () {
356
- const sessions = yield* SessionStore.SessionStore;
357
- const issued = yield* sessions.issue({
358
- method: "bearer-access-token",
359
- subject: "repository-failure",
360
- });
361
- const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
362
-
363
- const sessionError = yield* Effect.flip(sessions.verify(issued.token));
364
- const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
365
- const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
366
- const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
367
-
368
- expect(sessionError._tag).toBe("SessionCredentialVerificationError");
369
- expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
370
- expect(sessionError.cause).toBe(repositoryFailure);
371
- expect(websocketError.cause).toBe(repositoryFailure);
372
- if (sessionError._tag === "SessionCredentialVerificationError") {
373
- expect(sessionError.sessionId).toBe(issued.sessionId);
374
- }
375
- if (websocketError._tag === "WebSocketTokenVerificationError") {
376
- expect(websocketError.sessionId).toBe(issued.sessionId);
377
- }
378
- expect(revokeError).toMatchObject({
379
- _tag: "SessionRevocationError",
380
- sessionId: issued.sessionId,
381
- cause: repositoryFailure,
382
- });
383
- expect(revokeOthersError).toMatchObject({
384
- _tag: "OtherSessionsRevocationError",
385
- currentSessionId: issued.sessionId,
386
- cause: repositoryFailure,
387
- });
388
- }).pipe(Effect.provide(layerFailingSessionLookupCredential)),
389
- );
390
- it.effect("verifies session tokens against the Effect clock", () =>
391
- Effect.gen(function* () {
392
- const sessions = yield* SessionStore.SessionStore;
393
- const issued = yield* sessions.issue({
394
- method: "bearer-access-token",
395
- subject: "test-clock",
396
- });
397
- const verified = yield* sessions.verify(issued.token);
398
-
399
- expect(verified.method).toBe("bearer-access-token");
400
- expect(verified.subject).toBe("test-clock");
401
- expect(verified.scopes).toEqual(AuthStandardClientScopes);
402
- }).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
403
- );
404
-
291
it.effect("atomically replaces active sessions with the same subject and method", () =>
292
Effect.gen(function* () {
293
const sessions = yield* SessionStore.SessionStore;
@@ -539,44 +425,6 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
425
}).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
426
);
427
542
- it.effect("includes expiry context when session and websocket tokens expire", () =>
543
- Effect.gen(function* () {
544
- const sessions = yield* SessionStore.SessionStore;
545
- const issued = yield* sessions.issue({
546
- method: "bearer-access-token",
547
- subject: "short-lived-token",
548
- ttl: Duration.seconds(1),
549
- });
550
- const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
551
- ttl: Duration.seconds(1),
552
- });
553
-
554
- yield* TestClock.adjust(Duration.seconds(2));
555
-
556
- const sessionError = yield* Effect.flip(sessions.verify(issued.token));
557
- const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
558
-
559
- expect(sessionError._tag).toBe("SessionTokenExpiredError");
560
- if (sessionError._tag === "SessionTokenExpiredError") {
561
- expect(sessionError.sessionId).toBe(issued.sessionId);
562
- expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
563
- expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
564
- sessionError.expiresAt.epochMilliseconds,
565
- );
566
- }
567
- expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
568
- if (websocketError._tag === "WebSocketTokenExpiredError") {
569
- expect(websocketError.sessionId).toBe(issued.sessionId);
570
- expect(websocketError.expiresAt.epochMilliseconds).toBe(
571
- websocket.expiresAt.epochMilliseconds,
572
- );
573
- expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
574
- websocketError.expiresAt.epochMilliseconds,
575
- );
576
- }
577
- }).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
578
- );
579
-
428
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
429
Effect.gen(function* () {
430
const sessions = yield* SessionStore.SessionStore;
apps/server/src/auth/SessionStore.ts
+1
-1
@@ -482,7 +482,7 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
482
};
483
}
484
485
-export const make = Effect.gen(function* () {
485
+const make = Effect.gen(function* () {
486
const crypto = yield* Crypto.Crypto;
487
const serverConfig = yield* ServerConfig.ServerConfig;
488
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
apps/server/src/auth/utils.test.ts
+1
@@ -77,6 +77,7 @@ describe("session cookie isolation", () => {
77
expect(first).not.toBe(second);
78
});
79
80
+ // regression: #8085 isolate remote web session cookies
81
it("isolates remote web servers by server state", () => {
82
const first = resolveSessionCookieName({
83
mode: "web",
apps/server/src/background/BackgroundPolicy.test.ts
-17
@@ -256,23 +256,6 @@ describe("BackgroundPolicy", () => {
256
}).pipe(Effect.provide(layerFor(nominalHostPower))),
257
);
258
259
- it.effect(
260
- "performance profile allows background scoped work while a scoped lease is active",
261
- () =>
262
- Effect.gen(function* () {
263
- const policy = yield* BackgroundPolicy.BackgroundPolicy;
264
- yield* policy.reportClientActivity(
265
- AuthSessionId.make("session-1"),
266
- RpcClientId.make(1),
267
- makeReport({ focused: false, visible: false }),
268
- );
269
-
270
- assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
271
- }).pipe(
272
- Effect.provide(layerFor(nominalHostPower, { backgroundActivityProfile: "performance" })),
273
- ),
274
- );
275
-
259
it.effect("battery saver profile pauses scoped work on battery", () =>
260
Effect.gen(function* () {
261
const policy = yield* BackgroundPolicy.BackgroundPolicy;
apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
-20
@@ -68,26 +68,6 @@ function layerFor(input: {
68
);
69
}
70
71
-it.effect("preserves the typed unavailable-range error contract", () => {
72
- const layer = layerFor({ projection: Effect.succeed(makeProjection()) });
73
-
74
- return Effect.gen(function* () {
75
- const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
76
- const error = yield* query
77
- .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 3 })
78
- .pipe(Effect.flip);
79
-
80
- assert.instanceOf(error, CheckpointTurnRangeUnavailableError);
81
- assert.deepEqual(
82
- {
83
- requestedTurnCount: error.requestedTurnCount,
84
- availableTurnCount: error.availableTurnCount,
85
- },
86
- { requestedTurnCount: 3, availableTurnCount: 2 },
87
- );
88
- }).pipe(Effect.provide(layer));
89
-});
90
-
71
it.effect("excludes ready checkpoints from rolled-back runs", () => {
72
const projection = makeProjection();
73
const layer = layerFor({
apps/server/src/cli/app.test.ts
-18
@@ -215,24 +215,6 @@ describe("t3 server command safety", () => {
215
});
216
217
describe("t3 app", () => {
218
- it.effect("does not create state when only a server or no desktop app is running", () =>
219
- withTempDirectory("t3-app-missing-test-", (root) =>
220
- Effect.gen(function* () {
221
- const baseDir = NodePath.join(root, "missing-t3-home");
222
- const error = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
223
-
224
- expect(error).toMatchObject({
225
- _tag: "DesktopAppUnreachableError",
226
- candidateAddresses: [expect.any(String)],
227
- workspaceRoot: yield* HostProcess.WorkingDirectory,
228
- message: expect.stringContaining("Could not reach the T3 Code desktop app."),
229
- cause: { code: "ENOENT" },
230
- });
231
- expect(yield* pathExists(baseDir)).toBe(false);
232
- }),
233
- ),
234
- );
235
-
218
it.effect("uses T3CODE_HOME or --base-dir and sends the default or explicit path", () =>
219
withTempDirectory("t3-app-command-test-", (root) =>
220
Effect.gen(function* () {
apps/server/src/cli/config.test.ts
-43
@@ -592,49 +592,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
592
}),
593
);
594
595
- it.effect("decodes percent-encoded OTLP headers from env", () =>
596
- Effect.gen(function* () {
597
- const { join } = yield* Path.Path;
598
- const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-base");
599
-
600
- const resolved = yield* resolveServerConfig(
601
- {
602
- mode: Option.some("web"),
603
- port: Option.some(3773),
604
- host: Option.none(),
605
- baseDir: Option.some(baseDir),
606
- cwd: Option.none(),
607
- devUrl: Option.none(),
608
- noBrowser: Option.none(),
609
- bootstrapFd: Option.none(),
610
- autoBootstrapProjectFromCwd: Option.none(),
611
- logWebSocketEvents: Option.none(),
612
- tailscaleServeEnabled: Option.none(),
613
- tailscaleServePort: Option.none(),
614
- },
615
- Option.none(),
616
- ).pipe(
617
- Effect.provide(
618
- Layer.mergeAll(
619
- ConfigProvider.layer(
620
- ConfigProvider.fromEnv({
621
- env: {
622
- T3CODE_OTLP_HEADERS: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
623
- },
624
- }),
625
- ),
626
- NetService.layer,
627
- ),
628
- ),
629
- );
630
-
631
- expect(resolved.otlpTracesExport.headers).toEqual({
632
- authorization: "Basic abc==",
633
- "x-tenant": "t3",
634
- });
635
- }),
636
- );
637
-
595
it.effect("keeps whitespace-separated pairs and literal equals signs in OTLP headers", () =>
596
Effect.gen(function* () {
597
const { join } = yield* Path.Path;
apps/server/src/cli/connect.test.ts
+1
-54
@@ -1,14 +1,9 @@
1
import * as RelayClient from "@t3tools/shared/relayClient";
2
import { assert, it } from "@effect/vitest";
3
-import * as Cause from "effect/Cause";
4
-import * as Console from "effect/Console";
3
import * as Effect from "effect/Effect";
6
-import * as Exit from "effect/Exit";
7
-import * as Logger from "effect/Logger";
4
import * as Option from "effect/Option";
9
-import * as References from "effect/References";
5
11
-import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
6
+import { acquireRelayClientForLink } from "./connect.ts";
7
8
const managedExecutable = {
9
status: "available",
@@ -45,51 +40,3 @@ it.effect("does not install the relay client when the user declines the managed
40
assert.equal(installCalls, 0);
41
}),
42
);
48
-
49
-it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {
50
- const warnings: ReadonlyArray<unknown>[] = [];
51
- const logs: Readonly<Record<string, unknown>>[] = [];
52
- const testConsole = {
53
- ...globalThis.console,
54
- warn: (...args: ReadonlyArray<unknown>) => {
55
- warnings.push(args);
56
- },
57
- } satisfies Console.Console;
58
- const logger = Logger.make(({ fiber }) => {
59
- logs.push(fiber.getRef(References.CurrentLogAnnotations));
60
- });
61
- const liveFailure = "live unlink private diagnostic";
62
- const relayFailure = "relay revoke private diagnostic";
63
-
64
- return reportCloudDisconnectResults({
65
- clearAuthorization: true,
66
- liveResult: {
67
- status: "failed",
68
- cause: Cause.fail(new Error(liveFailure)),
69
- },
70
- relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),
71
- }).pipe(
72
- Effect.provideService(Console.Console, testConsole),
73
- Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
74
- Effect.tap(() =>
75
- Effect.sync(() => {
76
- assert.lengthOf(warnings, 2);
77
- const warningText = warnings.flat().map(String).join("\n");
78
- assert.include(warningText, "running server could not stop its tunnel");
79
- assert.include(warningText, "Could not revoke the relay-side environment record");
80
- assert.notInclude(warningText, liveFailure);
81
- assert.notInclude(warningText, relayFailure);
82
- assert.deepEqual(
83
- logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),
84
- [
85
- { operation: "live-server-unlink", clearAuthorization: true },
86
- { operation: "relay-environment-unlink", clearAuthorization: true },
87
- ],
88
- );
89
- const loggedCauses = logs.map((log) => String(log.cause)).join("\n");
90
- assert.include(loggedCauses, liveFailure);
91
- assert.include(loggedCauses, relayFailure);
92
- }),
93
- ),
94
- );
95
-});
apps/server/src/cli/connect.ts
+1
-1
@@ -441,7 +441,7 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
441
* A missing CLI login or a failed relay DELETE leaves that record registered, so
442
* those outcomes warn to deregister it from the T3 Connect account page.
443
*/
444
-export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
444
+const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
445
function* (input: {
446
readonly clearAuthorization: boolean;
447
readonly liveResult: LiveCloudActionResult;
apps/server/src/cli/pair.test.ts
-23
@@ -287,29 +287,6 @@ describe("t3 pair", () => {
287
).pipe(Effect.provide(NodeServices.layer)),
288
);
289
290
- it.effect("ignores stale runtime state pointing at a dead server", () =>
291
- Effect.gen(function* () {
292
- const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
293
- const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
294
- yield* persistServerRuntimeState({
295
- path: statePath,
296
- state: yield* makePersistedServerRuntimeState({
297
- config: { host: "127.0.0.1", devUrl: undefined },
298
- port: 1,
299
- }),
300
- });
301
-
302
- const error = yield* provideCliTestLayers(
303
- runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
304
- );
305
-
306
- const rendered = String(
307
- typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
308
- );
309
- assert.include(rendered, "No running T3 Code server found.");
310
- }).pipe(Effect.provide(NodeServices.layer)),
311
- );
312
-
290
// Without the capability `tailscale serve` blocks on an enablement URL, so
291
// pairing must stop at status instead of spawning it.
292
it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
apps/server/src/cli/project.test.ts
-21
@@ -39,10 +39,6 @@ import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolv
39
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
40
import * as ServerSettings from "../serverSettings.ts";
41
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
42
-import {
43
- ProjectLiveServerRequestError,
44
- projectCommandErrorFromLiveServerRequest,
45
-} from "./project.ts";
42
43
const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
44
const runCli = (args: ReadonlyArray<string>) =>
@@ -105,17 +101,6 @@ const readProjects = (baseDir: string) =>
101
);
102
});
103
108
-it("preserves unexpected server failures without deriving the message from them", () => {
109
- const cause = new Error("credential abc123 was rejected");
110
-
111
- const error = projectCommandErrorFromLiveServerRequest(cause);
112
-
113
- assert.instanceOf(error, ProjectLiveServerRequestError);
114
- assert.strictEqual(error.operation, "callLiveServer");
115
- assert.strictEqual(error.message, "Failed to call the running server.");
116
- assert.strictEqual(error.cause, cause);
117
-});
118
-
104
it.effect("adds, renames, and removes projects through the V2 project CLI domain", () =>
105
Effect.gen(function* () {
106
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-"));
@@ -234,12 +219,6 @@ const readNativeThreadState = Effect.fn("ProjectCliTest.readNativeThreadState")(
219
it.layer(NodeServices.layer)("project deletion with native V2 threads", (it) => {
220
it.effect.each([
221
{ label: "an active thread", archived: false, missing: false },
237
- { label: "an archived thread", archived: true, missing: false },
238
- {
239
- label: "an active thread after its workspace disappears",
240
- archived: false,
241
- missing: true,
242
- },
222
{
223
label: "an archived thread after its workspace disappears",
224
archived: true,
apps/server/src/cli/project.ts
+1
-1
@@ -169,7 +169,7 @@ export const ProjectCommandError = Schema.Union([
169
]);
170
export type ProjectCommandError = typeof ProjectCommandError.Type;
171
172
-export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
172
+function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
173
if (isEnvironmentHttpCommonError(cause)) {
174
return new ProjectLiveServerDeclaredResponseError({
175
operation: "callLiveServer",
apps/server/src/cli/service.test.ts
+1
@@ -112,6 +112,7 @@ it.effect("leaves a newer service unchanged during onboarding without prompting"
112
}),
113
);
114
115
+// regression: #9602 diagnose incomplete headless server setup
116
it.effect("keeps the manual-server fallback when background prerequisites fail", () =>
117
Effect.gen(function* () {
118
const ready = yield* recoverServiceOnboardingOffer(
apps/server/src/cli/theme.test.ts
-75
@@ -112,23 +112,6 @@ describe("t3 theme", () => {
112
}),
113
);
114
115
- it.effect("publishes nothing when the settings file cannot be used", () =>
116
- Effect.gen(function* () {
117
- const baseDir = makeBaseDir();
118
- NodeFS.mkdirSync(NodePath.dirname(settingsPathFor(baseDir)), { recursive: true });
119
- NodeFS.writeFileSync(settingsPathFor(baseDir), "{ not json");
120
- const themeFile = NodePath.join(baseDir, "nightfall.json");
121
- NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
122
-
123
- const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
124
- Effect.flip,
125
- );
126
-
127
- assert.include(String(failure), "not a JSON object");
128
- assert.equal(NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes")), false);
129
- }),
130
- );
131
-
115
it.effect.skipIf(!symlinksSupported)("never writes through a symlink at the staging path", () =>
116
Effect.gen(function* () {
117
const baseDir = makeBaseDir();
@@ -171,20 +154,6 @@ describe("t3 theme", () => {
154
}),
155
);
156
174
- it.effect("rejects a path that does not exist instead of storing it as an id", () =>
175
- Effect.gen(function* () {
176
- const baseDir = makeBaseDir();
177
- const failure = yield* runCli([
178
- "theme",
179
- "set",
180
- `${baseDir}/missing.json`,
181
- "--base-dir",
182
- baseDir,
183
- ]).pipe(Effect.flip);
184
- assert.include(String(failure), "Could not read");
185
- }),
186
- );
187
-
157
it.effect.skipIf(windowsHost)("refuses to write when the settings file cannot be read", () =>
158
Effect.gen(function* () {
159
const baseDir = makeBaseDir();
@@ -201,48 +170,4 @@ describe("t3 theme", () => {
170
assert.equal(Object.hasOwn(readSettings(baseDir), "defaultTheme"), false);
171
}),
172
);
204
-
205
- it.effect("accepts an id a published file provides", () =>
206
- Effect.gen(function* () {
207
- const baseDir = makeBaseDir();
208
- const themeFile = NodePath.join(baseDir, "nightfall.json");
209
- NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
210
- yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
211
-
212
- yield* runCli(["theme", "clear", "--base-dir", baseDir]);
213
- yield* runCli(["theme", "set", "nightfall", "--base-dir", baseDir]);
214
- assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
215
- }),
216
- );
217
-
218
- it.effect("rejects an id whose published file the watcher would skip", () =>
219
- Effect.gen(function* () {
220
- const baseDir = makeBaseDir();
221
- const themesDir = NodePath.join(baseDir, "userdata", "themes");
222
- NodeFS.mkdirSync(themesDir, { recursive: true });
223
- NodeFS.writeFileSync(NodePath.join(themesDir, "broken.json"), "{ not json\n");
224
-
225
- const failure = yield* runCli(["theme", "set", "broken", "--base-dir", baseDir]).pipe(
226
- Effect.flip,
227
- );
228
- assert.include(String(failure), "No theme named");
229
- }),
230
- );
231
-
232
- it.effect("rejects a theme file larger than the watcher will read", () =>
233
- Effect.gen(function* () {
234
- const baseDir = makeBaseDir();
235
- const themeFile = NodePath.join(baseDir, "huge.json");
236
- const padding = "x".repeat(40 * 1024);
237
- NodeFS.writeFileSync(
238
- themeFile,
239
- `{ "name": "Huge", "appearance": "dark", "canvas": "#1a1b26", "accent": "#7aa2f7", "note": "${padding}" }\n`,
240
- );
241
-
242
- const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
243
- Effect.flip,
244
- );
245
- assert.include(String(failure), "larger than");
246
- }),
247
- );
173
});
apps/server/src/cloud/CliTokenManager.test.ts
-2
@@ -213,9 +213,7 @@ it.effect(
213
it.effect.each([
214
{ status: 400, code: "invalid_grant", requiresLogin: true, diagnostic: true },
215
{ status: 403, code: "private-provider-secret", requiresLogin: true, diagnostic: false },
216
- { status: 408, code: "invalid_grant", requiresLogin: false, diagnostic: false },
216
{ status: 429, code: "invalid_grant", requiresLogin: false, diagnostic: false },
218
- { status: 500, code: "invalid_grant", requiresLogin: false, diagnostic: false },
217
])(
218
"refresh HTTP $status exposes only a safe login diagnostic",
219
({ status, code, requiresLogin, diagnostic }) =>
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+2
-127
@@ -97,89 +97,6 @@ describe("consumeCloudReplayGuards", () => {
97
expect(consumed).toBe(false);
98
}),
99
);
100
-
101
- it.effect("preserves replay-store availability failures", () =>
102
- Effect.gen(function* () {
103
- const failure = storeFailure("PermissionDenied");
104
- const error = yield* Effect.flip(
105
- consumeCloudReplayGuards({
106
- secrets: makeSecretStore(() => Effect.fail(failure)),
107
- names: ["cloud-jti", "cloud-nonce"],
108
- value: new Uint8Array(),
109
- }),
110
- );
111
-
112
- expect(error).toBe(failure);
113
- }),
114
- );
115
-});
116
-
117
-describe("reconcileDesiredCloudLink", () => {
118
- it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
119
- Effect.gen(function* () {
120
- const link = yield* CloudLink.CloudLink;
121
- const error = yield* Effect.flip(link.reconcileDesiredLink("http://127.0.0.1:3774"));
122
-
123
- expect(error._tag).toBe("CloudLinkAuthorizationMissingError");
124
- }).pipe(
125
- Effect.provide(CloudLink.layer),
126
- Effect.provideService(
127
- ConnectReachability.ConnectReachability,
128
- ConnectReachability.ConnectReachability.of({
129
- check: Effect.die("unused"),
130
- latest: Effect.succeed(Option.none()),
131
- }),
132
- ),
133
- Effect.provideService(HttpServer.HttpServer, idleHttpServer),
134
- Effect.provideService(
135
- ServerConfigModule.ServerConfig,
136
- ServerConfigModule.ServerConfig.of({} as ServerConfigModule.ServerConfig["Service"]),
137
- ),
138
- Effect.provideService(
139
- ServerSecretStore.ServerSecretStore,
140
- makeSecretStore(unusedSecretStoreOperation),
141
- ),
142
- Effect.provideService(
143
- ServerEnvironment.ServerEnvironment,
144
- ServerEnvironment.ServerEnvironment.of({
145
- getEnvironmentId: unusedSecretStoreOperation(),
146
- getDescriptor: unusedSecretStoreOperation(),
147
- }),
148
- ),
149
- Effect.provideService(
150
- ManagedEndpointRuntime.CloudManagedEndpointRuntime,
151
- ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
152
- applyConfig: unusedSecretStoreOperation,
153
- recoveryRequests: Stream.empty,
154
- requestRecovery: () => Effect.void,
155
- tunnelConnected: Stream.empty,
156
- inspectConnector: Effect.succeed(null),
157
- readinessChanged: Stream.empty,
158
- withLinkStateLock: (effect) => effect,
159
- } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
160
- ),
161
- Effect.provideService(
162
- EnvironmentAuth.EnvironmentAuth,
163
- EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
164
- ),
165
- Effect.provideService(
166
- CliTokenManager.CloudCliTokenManager,
167
- CliTokenManager.CloudCliTokenManager.of({
168
- get: unusedSecretStoreOperation(),
169
- getExisting: Effect.succeedNone,
170
- hasCredential: unusedSecretStoreOperation(),
171
- store: () => unusedSecretStoreOperation(),
172
- clear: unusedSecretStoreOperation(),
173
- }),
174
- ),
175
- Effect.provideService(
176
- HttpClient.HttpClient,
177
- HttpClient.make(() => unusedSecretStoreOperation()),
178
- ),
179
- Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
180
- Effect.provide(NodeServices.layer),
181
- ),
182
- );
100
});
101
102
describe("releaseManagedTunnelOnShutdown", () => {
@@ -389,26 +306,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
306
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
307
});
308
392
- it.effect("leaves the tunnel of a publish-only desired link untouched", () => {
393
- const { store, values } = makeMemorySecretStore([
394
- [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
395
- [RELAY_URL_SECRET, "https://relay.example.test"],
396
- [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],
397
- ]);
398
- const applyConfigCalls: Array<unknown> = [];
399
- const requests: Array<HttpClientRequest.HttpClientRequest> = [];
400
-
401
- return Effect.gen(function* () {
402
- const link = yield* CloudLink.CloudLink;
403
- const released = yield* link.releaseManagedTunnelOnShutdown();
404
-
405
- expect(released).toBe(false);
406
- expect(applyConfigCalls).toEqual([]);
407
- expect(requests).toEqual([]);
408
- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
409
- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
410
- });
411
-
309
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
310
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
311
const applyConfigCalls: Array<unknown> = [];
@@ -461,6 +358,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
358
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
359
});
360
361
+ // regression: 808d6853555 keep the managed tunnel across remote update restarts
362
it.effect("still releases when the recorded update already settled", () => {
363
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
364
const applyConfigCalls: Array<unknown> = [];
@@ -531,29 +429,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
429
);
430
});
431
534
- it.effect("keeps the stored connector token when the relay release request fails", () => {
535
- const { store, values } = makeMemorySecretStore(managedLinkSecrets);
536
- const applyConfigCalls: Array<unknown> = [];
537
- const requests: Array<HttpClientRequest.HttpClientRequest> = [];
538
-
539
- return Effect.gen(function* () {
540
- const link = yield* CloudLink.CloudLink;
541
- const result = yield* Effect.result(link.releaseManagedTunnelOnShutdown());
542
-
543
- expect(result._tag).toBe("Failure");
544
- expect(requests).toHaveLength(1);
545
-
546
- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
547
- }).pipe(
548
- provideReleaseHarness({
549
- store,
550
- applyConfigCalls,
551
- requests,
552
- respond: () => Response.json({ ok: false }, { status: 503 }),
553
- }),
554
- );
555
- });
556
-
432
it.effect("registers an existing tunnel and starts the confirmed connector", () => {
433
const { store } = makeMemorySecretStore([
434
[
@@ -808,6 +683,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
683
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
684
});
685
686
+ // regression: #9386 remove tunnels after hosts go offline
687
it.effect(
688
"starts the stored connector without a marker when confirmation is not required",
689
() => {
@@ -1007,7 +883,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
883
});
884
885
it.effect.each([
1010
- { status: 401, body: {}, rejection: "unauthorized" },
886
{
887
status: 401,
888
body: {
apps/server/src/cloud/CloudLink.test.ts
-13
@@ -185,19 +185,6 @@ it.effect("keeps both settings unchanged when the relay refuses the hold change"
185
),
186
);
187
188
-it.effect("changes nothing when the current activity setting can't be read", () =>
189
- withService({ failActivityRead: true, relayFails: true }, ({ preferences, stored, relayCalls }) =>
190
- Effect.gen(function* () {
191
- const error = yield* preferences
192
- .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
193
- .pipe(Effect.flip);
194
- assert.deepInclude(error, { _tag: "CloudLinkInternalError", operation: "read-preferences" });
195
- assert.deepEqual(relayCalls, []);
196
- assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
197
- }),
198
- ),
199
-);
200
-
188
it.effect("two overlapping updates are applied one after the other", () => {
189
let release!: () => void;
190
let started!: () => void;
apps/server/src/cloud/ConnectReachability.test.ts
-14
@@ -19,23 +19,9 @@ const facts = (overrides: Partial<ReachabilityFacts>): ReachabilityFacts => ({
19
});
20
21
describe("classifyReachability", () => {
22
- it("names a generic blocker when no exit node is on", () => {
23
- const result = classifyReachability(
24
- facts({ connector: notConnected, edgeReachable: false }),
25
- checkedAt,
26
- );
27
-
28
- expect(result).toMatchObject({
29
- cause: "edge_unreachable",
30
- hint: "A VPN, proxy, or firewall may block it.",
31
- });
32
- });
33
-
22
it.each([
23
[{ kind: "status", status: 502 }, "origin_unreachable"],
24
[{ kind: "status", status: 530 }, "no_connector"],
37
- [{ kind: "status", status: 404 }, "unexpected_response"],
38
- [{ kind: "dns_failed" }, "dns_failed"],
25
[{ kind: "network_error" }, "timeout"],
26
] as const)("maps endpoint result %o to %s", (endpoint, cause) => {
27
expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject(
apps/server/src/cloud/bootService.test.ts
+3
-17
@@ -65,26 +65,9 @@ it.each([
65
).toBe(program);
66
});
67
68
-const macRuntime = "/Users/theo/.t3/runtime/versions/1.2.3/t3";
69
-const macPlan = {
70
- program: [macRuntime, "__service-launcher"],
71
- baseDir: "/Users/theo/.t3",
72
- logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
73
- unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
74
-};
68
const macInstallerPath =
69
"/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
70
78
-it("escapes XML in host paths", () => {
79
- const plist = BootService.renderBootServicePlist(
80
- { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
81
- { homeDir: "/Users/theo", environmentPath: "/Users/theo/Tools & <Scripts>:/usr/bin" },
82
- );
83
-
84
- expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
85
- expect(plist).toContain("<string>/Users/theo/Tools & <Scripts>:/usr/bin</string>");
86
-});
87
-
71
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
72
platform: NodeJS.Platform = "linux",
73
installerPath = macInstallerPath,
@@ -372,6 +355,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
355
}),
356
);
357
358
+ // regression: #5302 prevent accidental service downgrades
359
it.effect("reports an unknown version for invalid service state", () =>
360
Effect.gen(function* () {
361
const { service, fs, statePath } = yield* makeHarness();
@@ -427,6 +411,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
411
}),
412
);
413
414
+ // regression: #5302 prevent accidental service downgrades
415
it.effect("allows an explicit downgrade", () =>
416
Effect.gen(function* () {
417
const { service, fs, statePath } = yield* makeHarness();
@@ -797,6 +782,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
782
}),
783
);
784
785
+ // regression: #8173 keep provider CLIs available in the macOS service
786
it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
787
Effect.gen(function* () {
788
const { service, fs } = yield* makeHarness("darwin", "");
apps/server/src/cloud/publicConfig.test.ts
-21
@@ -55,27 +55,6 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
55
}),
56
);
57
58
-it.effect("reports malformed Clerk publishable keys as typed configuration failures", () =>
59
- Effect.gen(function* () {
60
- const result = yield* makeCloudCliOAuthConfig({
61
- clerkPublishableKeyFallback: "pk_test_not-base64!!",
62
- clerkCliOAuthClientIdFallback: "oauth_client_embedded",
63
- }).pipe(provideEnv({}), Effect.result);
64
-
65
- assert.isTrue(Result.isFailure(result));
66
- if (Result.isFailure(result)) {
67
- assert.equal(result.failure.cause._tag, "SourceError");
68
- if (result.failure.cause._tag === "SourceError") {
69
- assert.equal(
70
- result.failure.cause.message,
71
- "Failed to derive Clerk Frontend API URL from the publishable key.",
72
- );
73
- assert.instanceOf(result.failure.cause.cause, Error);
74
- }
75
- }
76
- }),
77
-);
78
-
58
it("product opt-out disables relay tracing with either built-in or runtime credentials", () => {
59
const fallback = {
60
tracesUrl: "https://embedded.example.test/v1/traces",
apps/server/src/cloud/selfUpdate.test.ts
+1
@@ -285,6 +285,7 @@ it.layer(NodeServices.layer)("server self update", (it) => {
285
}),
286
);
287
288
+ // regression: #5181 make remote updates rollback-safe
289
it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
290
Effect.gen(function* () {
291
const web = yield* makeHarness();
apps/server/src/device/DeviceHubProxy.test.ts
+8
-11
@@ -231,14 +231,11 @@ it.each([
231
expect(requests).toEqual([]);
232
});
233
234
-it.each(["/panel/2/stream.avcc", "/panel/1/webrtc/offer", "/panel/3/exec"])(
235
- "rejects unsupported Duo route %s",
236
- async (route) => {
237
- const { handler, requests } = fixture([AuthOrchestrationReadScope]);
238
- const response = await handler(
239
- new Request(`http://t3.test/api/device-hub/vendor/serve-sim/helper/duo${route}`),
240
- );
241
- expect(response.status).toBe(404);
242
- expect(requests).toEqual([]);
243
- },
244
-);
234
+it("rejects unsupported Duo routes", async () => {
235
+ const { handler, requests } = fixture([AuthOrchestrationReadScope]);
236
+ const response = await handler(
237
+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/duo/panel/1/webrtc/offer"),
238
+ );
239
+ expect(response.status).toBe(404);
240
+ expect(requests).toEqual([]);
241
+});
apps/server/src/device/DeviceService.test.ts
+1
-13
@@ -541,6 +541,7 @@ it.effect.each([
541
}).pipe(Effect.scoped),
542
);
543
544
+// regression: #22012 report Android emulator boot failures
545
it.effect("includes nested hub boot diagnostics and bounds them to 2,000 characters", () =>
546
Effect.gen(function* () {
547
const diagnostic = "Error: emulator binary missing\n" + "diagnostic output\n".repeat(200);
@@ -886,19 +887,6 @@ it.effect("retry keeps device and agent consent unchanged", () =>
887
}).pipe(Effect.scoped),
888
);
889
889
-it.effect("version discovery does not grant consent or start device tools", () =>
890
- Effect.gen(function* () {
891
- const { service, starts, agentStarts, requests } = yield* fixture();
892
- const state = yield* service.inspect;
893
- expect(state.supportsToolInspection).toBe(true);
894
- expect(state.hostStatus).toBe("disabled");
895
- expect(state.hosts).toHaveLength(1);
896
- expect(starts).toEqual([]);
897
- expect(agentStarts).toEqual([]);
898
- expect(requests).toEqual([]);
899
- }).pipe(Effect.scoped),
900
-);
901
-
890
it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
891
Effect.gen(function* () {
892
const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
apps/server/src/device/EasDeviceHost.test.ts
-19
@@ -472,23 +472,4 @@ describe("EAS Simulator host", () => {
472
expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
473
}).pipe(Effect.scoped, Effect.provide(layer)),
474
);
475
-
476
- it.effect("holds the slot when a failed create’s session is listed but its stop fails", () =>
477
- Effect.gen(function* () {
478
- let stopFails = true;
479
- // Create fails, Expo lists the session by name, and stopping it fails too.
480
- const expo = fakeExpo({ failCreate: true, failStop: () => stopFails });
481
- const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
482
- const ready = yield* host.ensureReady(() => Effect.void);
483
- const [catalogDevice] = (yield* ready.devices.list).devices;
484
- yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
485
- const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
486
- expect(refused.message).toContain("still being cleaned up");
487
- stopFails = false;
488
- yield* ready.devices.list;
489
- expect(expo.stopped()).toContain("orphan");
490
- expo.allowCreate();
491
- expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
492
- }).pipe(Effect.scoped, Effect.provide(layer)),
493
- );
475
});
apps/server/src/device/LocalDeviceHost.test.ts
+1
@@ -279,6 +279,7 @@ describe("Android SDK availability", () => {
279
}),
280
);
281
282
+ // regression: #12017 detect unsupported legacy Android command-line tools
283
it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
284
Effect.gen(function* () {
285
const root = "/test/home/Library/Android/sdk";
apps/server/src/device/deviceToolMaintenance.test.ts
+1
@@ -97,6 +97,7 @@ describe.each([false, true])("device tool cleanup, flat=%s", (flat) => {
97
});
98
});
99
100
+// regression: #12819 safely reclaim obsolete managed tool versions
101
it.effect("maintenance failures retain safe context and the original process result", () =>
102
Effect.gen(function* () {
103
const output = {
apps/server/src/device/easProjectId.test.ts
+4
-147
@@ -88,16 +88,6 @@ it.effect.each([
88
},
89
expected: Option.none(),
90
},
91
- {
92
- case: "gives no answer for a config naming two projects, even with app.json",
93
- files: {
94
- "app.config.js": `export default () => ({
95
- extra: { eas: { projectId: process.env.PROD ? "${ID_A}" : "${ID_B}" } },
96
- });`,
97
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
98
- },
99
- expected: Option.none(),
100
- },
91
{
92
case: "gives no answer when one app sets its project from a variable",
93
files: {
@@ -121,37 +111,6 @@ it.effect.each([
111
},
112
expected: Option.none(),
113
},
124
- {
125
- case: "gives no answer when a config joins the project id from pieces",
126
- files: {
127
- "apps/mobile/app.config.ts": `export default {
128
- extra: { eas: { projectId: "${ID_A.slice(0, 9)}" + "${ID_A.slice(9)}" } },
129
- };`,
130
- "apps/kiosk/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_B } } } }),
131
- },
132
- expected: Option.none(),
133
- },
134
- {
135
- case: "reads a project id a comment follows",
136
- files: {
137
- "app.config.ts": `export default {
138
- extra: { eas: { projectId: "${ID_A}" /* production */ // the only one
139
- } },
140
- };`,
141
- },
142
- expected: Option.some(ID_A),
143
- },
144
- {
145
- case: "gives no answer when a separator inside a comment precedes the rest of the id",
146
- files: {
147
- "apps/mobile/app.config.ts": `export default {
148
- extra: { eas: { projectId: "${ID_A.slice(0, 9)}" // prefix, continued (below)
149
- + "${ID_A.slice(9)}" } },
150
- };`,
151
- "apps/kiosk/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_B } } } }),
152
- },
153
- expected: Option.none(),
154
- },
114
{
115
case: "gives no answer when a spread after the project id may replace it",
116
files: {
@@ -160,14 +119,6 @@ it.effect.each([
119
},
120
expected: Option.none(),
121
},
163
- {
164
- case: "gives no answer when a spread at the top of the config may replace the project id",
165
- files: {
166
- "apps/mobile/app.config.js": `import { brand } from "./app.shared.js";
167
- export default { extra: { eas: { projectId: "${ID_A}" } }, ...brand };`,
168
- },
169
- expected: Option.none(),
170
- },
122
{
123
case: "gives no answer when the config is assigned over after naming the project id",
124
files: {
@@ -179,16 +130,6 @@ it.effect.each([
130
},
131
expected: Option.none(),
132
},
182
- {
183
- case: "gives no answer when the config is assigned over from defaults that name the project id",
184
- files: {
185
- "app.config.js": `module.exports = Object.assign(
186
- { name: "Mobile", extra: { eas: { projectId: "${ID_A}" } } },
187
- require("./app.config.local.js"),
188
- );`,
189
- },
190
- expected: Option.none(),
191
- },
133
{
134
case: "gives no answer when a config spreads another file over app.json's project id",
135
files: {
@@ -205,35 +146,6 @@ it.effect.each([
146
},
147
expected: Option.none(),
148
},
208
- {
209
- case: "does not let a sibling win over an app whose config returns app.json's config changed",
210
- files: {
211
- "apps/mobile/app.config.js": `module.exports = ({ config }) => {
212
- config.name = "Mobile";
213
- return config;
214
- };`,
215
- "apps/mobile/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
216
- "apps/kiosk/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_B } } } }),
217
- },
218
- expected: Option.none(),
219
- },
220
- {
221
- case: "gives no answer when a spread of an identifier starting with config may replace app.json's id",
222
- files: {
223
- "app.config.js": `const config$ = require("./app.local.js");
224
- module.exports = ({ config }) => ({ ...config, ...config$ });`,
225
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
226
- },
227
- expected: Option.none(),
228
- },
229
- {
230
- case: "gives no answer when a config spreads the config but replaces extra",
231
- files: {
232
- "app.config.js": `module.exports = ({ config }) => ({ ...config, extra: {} });`,
233
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
234
- },
235
- expected: Option.none(),
236
- },
149
{
150
case: "gives no answer when a config has more extra entries than are read",
151
files: {
@@ -242,44 +154,6 @@ it.effect.each([
154
},
155
expected: Option.none(),
156
},
245
- {
246
- case: "gives no answer when a config assigns extra in brackets after a literal id",
247
- files: {
248
- "app.config.js": `module.exports = ({ config }) => {
249
- const c = { ...config, extra: { eas: { projectId: "${ID_A}" } } };
250
- c["extra"] = other();
251
- return c;
252
- };`,
253
- },
254
- expected: Option.none(),
255
- },
256
- {
257
- case: "gives no answer when a config deletes from the config it spreads",
258
- files: {
259
- "app.config.js": `module.exports = ({ config }) => {
260
- delete config.extra;
261
- return { ...config };
262
- };`,
263
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
264
- },
265
- expected: Option.none(),
266
- },
267
- {
268
- case: "gives no answer when a config spreads part of the config over it",
269
- files: {
270
- "app.config.js": `module.exports = ({ config }) => ({ ...config, ...config.extra.preview });`,
271
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
272
- },
273
- expected: Option.none(),
274
- },
275
- {
276
- case: "gives no answer when an extra entry spreads the whole config, not its extra",
277
- files: {
278
- "app.config.js": `module.exports = ({ config }) => ({ ...config, extra: { ...config } });`,
279
- "app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }),
280
- },
281
- expected: Option.none(),
282
- },
157
{
158
case: "reads app.json's id through extra and eas entries that spread their own",
159
files: {
@@ -291,15 +165,6 @@ it.effect.each([
165
},
166
expected: Option.some(ID_A),
167
},
294
- {
295
- case: "gives no answer when a config may return another file's config on some builds",
296
- files: {
297
- "app.config.js": `module.exports = process.env.PROD
298
- ? { extra: { eas: { projectId: "${ID_A}" } } }
299
- : require("./app.config.staging.js");`,
300
- },
301
- expected: Option.none(),
302
- },
168
{
169
case: "reads a project id that follows spreads",
170
files: {
@@ -329,14 +194,6 @@ it.effect.each([
194
},
195
expected: Option.none(),
196
},
332
- {
333
- case: "reads a static config that is not wrapped in `expo`",
334
- files: {
335
- "apps/mobile/app.config.json": JSON.stringify({ extra: { eas: { projectId: ID_A } } }),
336
- "apps/README.md": "one app",
337
- },
338
- expected: Option.some(ID_A),
339
- },
197
{
198
case: "does not guess between an unwrapped static config and a wrapped one",
199
files: {
@@ -359,14 +216,14 @@ it.effect.each([
216
}).pipe(Effect.scoped, Effect.provide(layer)),
217
);
218
362
-it.effect.each(["\r", "\u2028", "\u2029"])(
363
- "gives no answer when a comment ending in %o precedes the rest of a joined id",
364
- (terminator) =>
219
+it.effect(
220
+ "gives no answer when a comment ending in a non-LF line terminator precedes the rest of a joined id",
221
+ () =>
222
Effect.gen(function* () {
223
// A line comment ends at any ECMAScript line terminator, not only LF.
224
const root = yield* workspace({
225
"apps/mobile/app.config.ts":
369
- `export default { extra: { eas: { projectId: "${ID_A.slice(0, 9)}" // prefix${terminator}` +
226
+ `export default { extra: { eas: { projectId: "${ID_A.slice(0, 9)}" // prefix\u2028` +
227
`+ "${ID_A.slice(9)}" } } };`,
228
"apps/kiosk/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_B } } } }),
229
});
apps/server/src/git/GitManager.test.ts
+1
-187
@@ -12,10 +12,8 @@ import * as Deferred from "effect/Deferred";
12
import * as Fiber from "effect/Fiber";
13
import * as FileSystem from "effect/FileSystem";
14
import * as Layer from "effect/Layer";
15
-import * as Logger from "effect/Logger";
15
import * as Option from "effect/Option";
16
import * as PlatformError from "effect/PlatformError";
18
-import * as References from "effect/References";
17
import * as Result from "effect/Result";
18
import * as Schema from "effect/Schema";
19
import * as Scope from "effect/Scope";
@@ -1677,6 +1675,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1675
}),
1676
);
1677
1678
+ // regression: #8600 settle threads server-side
1679
it.effect("branch PR lookup propagates provider failures", () =>
1680
Effect.gen(function* () {
1681
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2428,75 +2427,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2427
}),
2428
);
2429
2431
- it.effect("status is resilient to gh lookup failures and returns pr null", () =>
2432
- Effect.gen(function* () {
2433
- const repoDir = yield* makeTempDir("t3code-git-manager-");
2434
- yield* initRepo(repoDir);
2435
- yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
2436
- const remoteDir = yield* createBareRemote();
2437
- yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2438
- yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
2439
-
2440
- const { manager } = yield* makeManager({
2441
- ghScenario: {
2442
- failWith:
2443
- "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
2444
- },
2445
- });
2446
-
2447
- const status = yield* manager.status({ cwd: repoDir });
2448
- expect(status.refName).toBe("feature/status-no-gh");
2449
- expect(status.pr).toBeNull();
2450
- }),
2451
- );
2452
-
2453
- it.effect("status logs actionable provider detail without exposing the upstream cause", () =>
2454
- Effect.gen(function* () {
2455
- const repoDir = yield* makeTempDir("t3code-git-manager-");
2456
- yield* initRepo(repoDir);
2457
- yield* runGit(repoDir, ["checkout", "-b", "feature/status-rate-limited"]);
2458
- const remoteDir = yield* createBareRemote();
2459
- yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2460
- yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-rate-limited"]);
2461
-
2462
- const upstreamCause = "GraphQL rate limit for user ID 51714798 and token secret-value";
2463
- const { manager } = yield* makeManager({
2464
- ghScenario: {
2465
- failWith: "GitHub API rate limit exceeded. Requests resume when the limit resets.",
2466
- failCause: new Error(upstreamCause),
2467
- },
2468
- });
2469
- const logs: Array<{ message: string; annotations: Record<string, unknown> }> = [];
2470
- const logger = Logger.make<unknown, void>(({ fiber, message }) => {
2471
- logs.push({
2472
- message: String(message),
2473
- annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
2474
- });
2475
- });
2476
-
2477
- const status = yield* manager
2478
- .status({ cwd: repoDir })
2479
- .pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
2480
-
2481
- expect(status.pr).toBeNull();
2482
- const warning = logs.find((entry) => entry.message.includes("PR lookup failed"));
2483
- expect(warning?.annotations).toMatchObject({
2484
- operation: "lookupStatusPr",
2485
- branch: "feature/status-rate-limited",
2486
- errorTag: "SourceControlProviderError",
2487
- provider: SourceControlProviderKind.make("github"),
2488
- providerOperation: "listChangeRequests",
2489
- errorDetail: "GitHub API rate limit exceeded. Requests resume when the limit resets.",
2490
- });
2491
- const loggedText = [
2492
- warning?.message ?? "",
2493
- ...Object.values(warning?.annotations ?? {}).map(String),
2494
- ].join("\n");
2495
- expect(loggedText).not.toContain(upstreamCause);
2496
- expect(loggedText).not.toContain("secret-value");
2497
- }),
2498
- );
2499
-
2430
it.effect("status keeps the last known PR when a later lookup fails", () =>
2431
Effect.gen(function* () {
2432
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2577,45 +2507,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2507
}),
2508
);
2509
2580
- it.effect("status drops the last known PR when the tracked remote is repointed", () =>
2581
- Effect.gen(function* () {
2582
- const repoDir = yield* makeTempDir("t3code-git-manager-");
2583
- yield* initRepo(repoDir);
2584
- yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
2585
- const originalRemoteDir = yield* createBareRemote();
2586
- yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
2587
- yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
2588
-
2589
- const existingPr = {
2590
- number: 216,
2591
- title: "Old remote PR",
2592
- url: "https://github.com/pingdotgg/codething-mvp/pull/216",
2593
- baseRefName: "main",
2594
- headRefName: "feature/pr-repointed",
2595
- };
2596
- const { manager } = yield* makeManager({
2597
- ghScenario: {
2598
- prListSequence: [JSON.stringify([existingPr])],
2599
- failWith:
2600
- "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
2601
- failAfterCalls: 1,
2602
- },
2603
- });
2604
-
2605
- const first = yield* manager.status({ cwd: repoDir });
2606
- expect(first.pr?.number).toBe(216);
2607
-
2608
- const replacementRemoteDir = yield* createBareRemote();
2609
- yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
2610
- yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
2611
- yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
2612
- yield* manager.invalidateStatus(repoDir);
2613
-
2614
- const second = yield* manager.status({ cwd: repoDir });
2615
- expect(second.pr).toBeNull();
2616
- }),
2617
- );
2618
-
2510
it.effect("creates a commit when working tree is dirty", () =>
2511
Effect.gen(function* () {
2512
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2846,56 +2737,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2737
}),
2738
);
2739
2849
- it.effect("uses custom commit message when provided", () =>
2850
- Effect.gen(function* () {
2851
- const repoDir = yield* makeTempDir("t3code-git-manager-");
2852
- yield* initRepo(repoDir);
2853
- // Patch generation would invoke this unavailable converter. A supplied
2854
- // message must commit without generating a patch it will not use.
2855
- NodeFS.writeFileSync(
2856
- NodePath.join(repoDir, ".git/info/attributes"),
2857
- "README.md diff=probe\n",
2858
- );
2859
- yield* runGit(repoDir, ["config", "diff.probe.textconv", "t3-missing-textconv-for-test"]);
2860
- NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\ncustom\n");
2861
- let generatedCount = 0;
2862
-
2863
- const { manager } = yield* makeManager({
2864
- textGeneration: {
2865
- generateCommitMessage: (input) =>
2866
- Effect.sync(() => {
2867
- generatedCount += 1;
2868
- return {
2869
- subject: "this should not be used",
2870
- body: "",
2871
- ...(input.includeBranch ? { branch: "feature/unused" } : {}),
2872
- };
2873
- }),
2874
- },
2875
- });
2876
- const result = yield* runStackedAction(manager, {
2877
- cwd: repoDir,
2878
- action: "commit",
2879
- commitMessage: "feat: custom summary line\n\n- details from user",
2880
- });
2881
-
2882
- expect(result.branch.status).toBe("skipped_not_requested");
2883
- expect(result.commit.status).toBe("created");
2884
- expect(result.commit.subject).toBe("feat: custom summary line");
2885
- expect(generatedCount).toBe(0);
2886
- expect(
2887
- yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
2888
- Effect.map((result) => result.stdout.trim()),
2889
- ),
2890
- ).toBe("feat: custom summary line");
2891
- expect(
2892
- yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(
2893
- Effect.map((result) => result.stdout.trim()),
2894
- ),
2895
- ).toContain("- details from user");
2896
- }),
2897
- );
2898
-
2740
it.effect("commits only selected files when filePaths is provided", () =>
2741
Effect.gen(function* () {
2742
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -3024,33 +2865,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2865
}),
2866
);
2867
3027
- it.effect("commits and pushes with upstream auto-setup when needed", () =>
3028
- Effect.gen(function* () {
3029
- const repoDir = yield* makeTempDir("t3code-git-manager-");
3030
- yield* initRepo(repoDir);
3031
- yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
3032
- const remoteDir = yield* createBareRemote();
3033
- yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
3034
- NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
3035
-
3036
- const { manager } = yield* makeManager();
3037
- const result = yield* runStackedAction(manager, {
3038
- cwd: repoDir,
3039
- action: "commit_push",
3040
- });
3041
-
3042
- expect(result.branch.status).toBe("skipped_not_requested");
3043
- expect(result.commit.status).toBe("created");
3044
- expect(result.push.status).toBe("pushed");
3045
- expect(result.push.setUpstream).toBe(true);
3046
- expect(
3047
- yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
3048
- Effect.map((result) => result.stdout.trim()),
3049
- ),
3050
- ).toBe("origin/feature/stacked-flow");
3051
- }),
3052
- );
3053
-
2868
it.effect(
2869
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
2870
() =>
apps/server/src/git/linkCreatedPullRequest.test.ts
-27
@@ -162,33 +162,6 @@ describe("linkCreatedPullRequest", () => {
162
]);
163
}),
164
);
165
-
166
- it.effect("swallows an already-linked rejection and other dispatch failures", () =>
167
- Effect.gen(function* () {
168
- const rejecting: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) =>
169
- Effect.fail(
170
- new Orchestrator.OrchestratorDispatchError({
171
- commandId: command.commandId,
172
- commandType: command.type,
173
- cause: "already linked",
174
- }),
175
- );
176
- const result = prResult({
177
- status: "opened_existing",
178
- number: 7,
179
- url: "https://github.com/t3tools/t3code/pull/7",
180
- });
181
- yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
182
- Effect.provide(layerDependenciesFor(rejecting)),
183
- );
184
- yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
185
- Effect.provide(layerDependenciesFor(() => Effect.die(new Error("engine down")))),
186
- );
187
- yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
188
- Effect.provide(layerDependenciesFor(() => Effect.die(new Error("unreachable")), null)),
189
- );
190
- }),
191
- );
165
});
166
167
it.effect(
apps/server/src/http.test.ts
+1
-25
@@ -26,12 +26,7 @@ import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
26
27
import * as ServerConfig from "./config.ts";
28
29
-import {
30
- assetResponseHeaders,
31
- assetFileResponse,
32
- downloadContentDisposition,
33
- resolveDevRedirectUrl,
34
-} from "./http.ts";
29
+import { assetResponseHeaders, assetFileResponse, downloadContentDisposition } from "./http.ts";
30
import * as ServerHttp from "./http.ts";
31
32
describe("MCP app asset responses", () => {
@@ -698,17 +693,6 @@ describe("video asset byte ranges", () => {
693
);
694
});
695
701
-describe("http dev routing", () => {
702
- it("preserves path and query when redirecting to the dev server", () => {
703
- const devUrl = new URL("http://127.0.0.1:5173/");
704
- const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
705
-
706
- expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
707
- "http://127.0.0.1:5173/pair?token=test-token",
708
- );
709
- });
710
-});
711
-
696
describe("assetResponseHeaders", () => {
697
it("sandboxes SVG assets", () => {
698
expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
@@ -732,14 +716,6 @@ describe("assetResponseHeaders", () => {
716
"Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
717
});
718
});
735
- it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
736
- for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
737
- expect(assetResponseHeaders(path)).toMatchObject({
738
- "Content-Type": "text/html; charset=utf-8",
739
- "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
740
- });
741
- }
742
- });
719
720
it("downloads uploaded documents without executing their content", () => {
721
expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
apps/server/src/http.ts
+1
-1
@@ -283,7 +283,7 @@ function isLoopbackHostname(hostname: string): boolean {
283
return LOOPBACK_HOSTNAMES.has(normalizedHostname);
284
}
285
286
-export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
286
+function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
287
const redirectUrl = new URL(devUrl.toString());
288
redirectUrl.pathname = requestUrl.pathname;
289
redirectUrl.search = requestUrl.search;
apps/server/src/imageMime.test.ts
+1
-8
@@ -10,14 +10,6 @@ describe("imageMime", () => {
10
});
11
});
12
13
- it("rejects non-base64 data URL", () => {
14
- expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
15
- });
16
-
17
- it("rejects missing mime type", () => {
18
- expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
19
- });
20
-
13
it("parses base64 data URL with spaces in payload", () => {
14
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
15
mimeType: "image/png",
@@ -30,6 +22,7 @@ describe("imageMime", () => {
22
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
23
});
24
25
+ // regression: #3952 image upload crashed dispatchCommand with a stack overflow
26
it("rejects structurally malformed base64", () => {
27
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
28
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
apps/server/src/keybindings.test.ts
-22
@@ -484,28 +484,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
484
}).pipe(Effect.provide(layerKeybindings())),
485
);
486
487
- it.effect("updates cached resolved config after upsert", () =>
488
- Effect.gen(function* () {
489
- const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
490
- yield* writeKeybindingsConfig(keybindingsConfigPath, [
491
- { key: "mod+j", command: "terminal.toggle" },
492
- ]);
493
-
494
- const loadedAfterUpsert = yield* Effect.gen(function* () {
495
- const keybindings = yield* Keybindings.Keybindings;
496
- yield* keybindings.loadConfigState;
497
- yield* keybindings.upsertKeybindingRule({
498
- key: "mod+shift+r",
499
- command: "script.run-tests.run",
500
- });
501
- return (yield* keybindings.loadConfigState).keybindings;
502
- });
503
-
504
- assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run"));
505
- assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle"));
506
- }).pipe(Effect.provide(layerKeybindings())),
507
- );
508
-
487
it.effect("serializes concurrent upserts to avoid lost updates", () =>
488
Effect.gen(function* () {
489
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
apps/server/src/mcp/McpHttpServer.test.ts
+2
@@ -495,6 +495,7 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () =>
495
).pipe(Effect.provide(layerTest)),
496
);
497
498
+// regression: #10501 keep preview snapshots usable by the agent
499
it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
500
Effect.scoped(
501
Effect.gen(function* () {
@@ -527,6 +528,7 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are
528
).pipe(Effect.provide(layerTest)),
529
);
530
531
+// regression: #13558 preview snapshots overflowed the agent's tool output
532
it.effect("bounds page text made of wide characters before dropping locators", () =>
533
Effect.scoped(
534
Effect.gen(function* () {
apps/server/src/mcp/McpSessionRegistry.test.ts
+1
@@ -102,6 +102,7 @@ it.effect("always grants pull-requests and gates browser and device access indep
102
}),
103
);
104
105
+// regression: #3114 use bound host for MCP endpoint
106
it.effect("builds MCP endpoints from the bound server host", () =>
107
Effect.gen(function* () {
108
const cases = [
apps/server/src/mcp/PreviewAutomationBroker.test.ts
-64
@@ -3,7 +3,6 @@ import { expect, it } from "@effect/vitest";
3
import {
4
EnvironmentId,
5
PreviewAutomationClientDisconnectedError,
6
- PreviewAutomationInvalidSelectorError,
6
PreviewAutomationMalformedResponseError,
7
PreviewAutomationNoAvailableHostError,
8
PreviewTabId,
@@ -288,69 +287,6 @@ it.effect("announces a live replacement stream before delivering requests", () =
287
),
288
);
289
291
-it.effect("preserves bounded request and remote selector diagnostics", () => {
292
- const locator = "role=button[name='request-secret']";
293
- const remoteMessage = "Unexpected token near remote-secret.";
294
- const remoteError = {
295
- _tag: "PreviewAutomationInvalidSelectorError",
296
- message: remoteMessage,
297
- detail: { selector: "role=button[name='remote-secret']" },
298
- } as const;
299
-
300
- return Effect.scoped(
301
- Effect.gen(function* () {
302
- const broker = yield* makeBroker;
303
- const requests = requestsFrom(yield* broker.connect(makeHost()));
304
- yield* Stream.runForEach(requests, (request) =>
305
- broker.respond({
306
- clientId: "client-1",
307
- connectionId: request.connectionId,
308
- requestId: request.requestId,
309
- ok: false,
310
- error: remoteError,
311
- }),
312
- ).pipe(Effect.forkScoped);
313
- yield* Effect.yieldNow;
314
-
315
- const error = yield* broker
316
- .invoke<void>({
317
- scope,
318
- operation: "click",
319
- input: { locator },
320
- tabId: PreviewTabId.make("tab-1"),
321
- timeoutMs: 1_234,
322
- })
323
- .pipe(Effect.flip);
324
-
325
- expect(error).toBeInstanceOf(PreviewAutomationInvalidSelectorError);
326
- expect(error).toMatchObject({
327
- operation: "click",
328
- environmentId: scope.environmentId,
329
- threadId: scope.thread.threadId,
330
- providerSessionId: scope.thread.providerSessionId,
331
- providerInstanceId: scope.thread.providerInstanceId,
332
- clientId: "client-1",
333
- requestId: "preview-0",
334
- tabId: "tab-1",
335
- timeoutMs: 1_234,
336
- selectorKind: "locator",
337
- selectorLength: locator.length,
338
- remoteTag: "PreviewAutomationInvalidSelectorError",
339
- remoteMessageLength: remoteMessage.length,
340
- remoteDetailKind: "object",
341
- });
342
- expect(error.message).toBe(
343
- `Preview automation click received an invalid locator (${locator.length} characters).`,
344
- );
345
- expect(error.message).not.toContain("secret");
346
- expect(error.cause).toBe(remoteError);
347
- expect("selector" in error).toBe(false);
348
- expect("remoteMessage" in error).toBe(false);
349
- expect("remoteDetail" in error).toBe(false);
350
- }),
351
- );
352
-});
353
-
290
it.effect.each([
291
{ clientId: SERVER_BROWSER_AUTOMATION_CLIENT_ID, shown: true },
292
{ clientId: "client-1", shown: false },
apps/server/src/mcp/WorktreeMcpService.test.ts
-81
@@ -470,42 +470,6 @@ describe("t3_worktree_handoff", () => {
470
});
471
});
472
473
- it.effect("fails when the thread does not exist", () => {
474
- const harness = makeHarness({ thread: null });
475
- return Effect.gen(function* () {
476
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" }));
477
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
478
- expect(harness.createWorktree).not.toHaveBeenCalled();
479
- });
480
- });
481
-
482
- it.effect("treats a soft-deleted thread as not found", () => {
483
- const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } });
484
- return Effect.gen(function* () {
485
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" }));
486
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
487
- expect(harness.createWorktree).not.toHaveBeenCalled();
488
- });
489
- });
490
-
491
- it.effect("fails when the project does not exist", () => {
492
- const harness = makeHarness({ projectMissing: true });
493
- return Effect.gen(function* () {
494
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" }));
495
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
496
- expect(harness.createWorktree).not.toHaveBeenCalled();
497
- });
498
- });
499
-
500
- it.effect("fails when the project workspace is not a git repository", () => {
501
- const harness = makeHarness({ notARepo: true });
502
- return Effect.gen(function* () {
503
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" }));
504
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
505
- expect(harness.createWorktree).not.toHaveBeenCalled();
506
- });
507
- });
508
-
473
it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
474
const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
475
return Effect.gen(function* () {
@@ -546,16 +510,6 @@ describe("t3_worktree_handoff", () => {
510
});
511
});
512
549
- it.effect("maps a worktree creation failure to operation_failed", () => {
550
- const harness = makeHarness({ createWorktreeFails: true });
551
- return Effect.gen(function* () {
552
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" }));
553
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
554
- expect(harness.dispatch).not.toHaveBeenCalled();
555
- expect(harness.removeWorktree).not.toHaveBeenCalled();
556
- });
557
- });
558
-
513
it.effect("falls back to the local base when no remote holds it", () => {
514
const harness = makeHarness({ worktreeBaseMissing: true });
515
return Effect.gen(function* () {
@@ -632,15 +586,6 @@ describe("t3_worktree_handoff", () => {
586
});
587
});
588
635
- it.effect("rejects a handoff for an archived thread", () => {
636
- const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } });
637
- return Effect.gen(function* () {
638
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" }));
639
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
640
- expect(harness.createWorktree).not.toHaveBeenCalled();
641
- });
642
- });
643
-
589
it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
590
Effect.gen(function* () {
591
const gate = yield* Deferred.make<void>();
@@ -665,16 +610,6 @@ describe("t3_worktree_handoff", () => {
610
}),
611
);
612
668
- it.effect("still fails with a typed error when the rollback removal also fails", () => {
669
- const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true });
670
- return Effect.gen(function* () {
671
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" }));
672
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
673
- expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
674
- expect(harness.deleteLocalBranch).not.toHaveBeenCalled();
675
- });
676
- });
677
-
613
it.effect("creates the worktree in the managed directory even when a call names a path", () => {
614
const harness = makeHarness();
615
return Effect.gen(function* () {
@@ -706,14 +641,6 @@ describe("t3_worktree_handoff", () => {
641
});
642
});
643
709
- it.effect("fails when the worktree capability is missing", () => {
710
- const harness = makeHarness({ capabilities: new Set(["preview"]) });
711
- return Effect.gen(function* () {
712
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" }));
713
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
714
- });
715
- });
716
-
644
it.effect("serializes concurrent handoffs for the same thread", () =>
645
Effect.gen(function* () {
646
const gate = yield* Deferred.make<void>();
@@ -738,14 +665,6 @@ describe("t3_worktree_handoff", () => {
665
}),
666
);
667
741
- it.effect("fails when baseRef is omitted and HEAD is detached", () => {
742
- const harness = makeHarness({ currentBranch: null });
743
- return Effect.gen(function* () {
744
- const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" }));
745
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
746
- });
747
- });
748
-
668
it.effect("reports a setup script defect without failing the handoff", () => {
669
const harness = makeHarness({ setupScript: "dies" });
670
return Effect.gen(function* () {
apps/server/src/mcp/toolkits/preview/handlers.test.ts
+1
-9
@@ -11,15 +11,7 @@ import {
11
parseThreadSegmentFromAttachmentId,
12
} from "../../../attachmentStore.ts";
13
import * as ServerConfig from "../../../config.ts";
14
-import { claimPreviewRecording, normalizePreviewOpenInput } from "./handlers.ts";
15
-
16
-describe("normalizePreviewOpenInput", () => {
17
- it("leaves an unstated visibility for the client preference to decide", () => {
18
- // Filling `open` in here would outrank `browserAutoShowFloatingPreview`,
19
- // which is desktop-local and cannot be read from the server.
20
- expect(normalizePreviewOpenInput({})).toEqual({ reuseExistingTab: true });
21
- });
22
-});
14
+import { claimPreviewRecording } from "./handlers.ts";
15
16
describe("claimPreviewRecording", () => {
17
it.effect("overlapping and repeated claims return the same retained recording", () =>
apps/server/src/mcp/toolkits/preview/handlers.ts
+1
-3
@@ -38,9 +38,7 @@ import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "
38
* preference, which is desktop-local and unreadable from here — filling in
39
* `true` would silently override it for every `preview_open`.
40
*/
41
-export function normalizePreviewOpenInput(
42
- input: PreviewAutomationOpenInput,
43
-): PreviewAutomationOpenInput {
41
+function normalizePreviewOpenInput(input: PreviewAutomationOpenInput): PreviewAutomationOpenInput {
42
const open = input.open ?? input.show;
43
return {
44
...input,
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
-18
@@ -447,24 +447,6 @@ describe("pull request toolkit handlers", () => {
447
}),
448
);
449
450
- it.effect("rejects a target that names neither a URL nor repository and number", () =>
451
- Effect.gen(function* () {
452
- const harness = yield* makeHarness();
453
- const error = yield* harness
454
- .call("link_pull_request", { repository: "x/y" })
455
- .pipe(Effect.flip);
456
- expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
457
- const unknown = yield* harness
458
- .call("link_pull_request", {
459
- url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
460
- })
461
- .pipe(Effect.flip);
462
- expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
463
- expect(unknown.message).not.toContain("private-value");
464
- expect(yield* Ref.get(harness.commands)).toEqual([]);
465
- }),
466
- );
467
-
450
it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
451
Effect.gen(function* () {
452
const harness = yield* makeHarness({
apps/server/src/mcpApps/McpAppRequests.test.ts
-22
@@ -251,26 +251,4 @@ describe("McpAppRequests", () => {
251
assert.isTrue(storedContext.has(`${deepForkId(70)}/${itemId}`));
252
}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))),
253
);
254
-
255
- it.effect("reports why a request cannot run", () =>
256
- Effect.gen(function* () {
257
- const run = (layer: ReturnType<typeof makeLayer>) =>
258
- Effect.gen(function* () {
259
- const requests = yield* McpAppRequests.McpAppRequests;
260
- return yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/x" }));
261
- }).pipe(Effect.provide(layer));
262
- assert.equal(
263
- yield* run(makeLayer({ item: appItem({ result: "plain" }), mcpApps })),
264
- "not-an-app",
265
- );
266
- assert.equal(
267
- yield* run(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps, live: false })),
268
- "session-stopped",
269
- );
270
- assert.equal(
271
- yield* run(makeLayer({ item: appItem({ t3McpApp: app }) })),
272
- "provider-unsupported",
273
- );
274
- }),
275
- );
254
});
apps/server/src/persistence/OrchestrationEventStore.test.ts
-52
@@ -295,58 +295,6 @@ layer("OrchestrationEventStore", (it) => {
295
}),
296
);
297
298
- it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
299
- Effect.gen(function* () {
300
- const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
301
- const sql = yield* SqlClient.SqlClient;
302
- const now = "2026-01-01T00:00:00.000Z";
303
-
304
- yield* sql`
305
- INSERT INTO orchestration_events (
306
- event_id,
307
- aggregate_kind,
308
- stream_id,
309
- stream_version,
310
- event_type,
311
- occurred_at,
312
- command_id,
313
- causation_event_id,
314
- correlation_id,
315
- actor_kind,
316
- payload_json,
317
- metadata_json
318
- )
319
- VALUES (
320
- ${EventId.make("evt-store-invalid-json")},
321
- ${"project"},
322
- ${ProjectId.make("project-invalid-json")},
323
- ${0},
324
- ${"project.created"},
325
- ${now},
326
- ${CommandId.make("cmd-store-invalid-json")},
327
- ${null},
328
- ${null},
329
- ${"server"},
330
- ${"{"},
331
- ${"{}"}
332
- )
333
- `;
334
-
335
- const replayResult = yield* Effect.result(
336
- Stream.runCollect(
337
- eventStore.readApplicationEvents({
338
- afterSequence: 0,
339
- throughSequence: Number.MAX_SAFE_INTEGER,
340
- }),
341
- ),
342
- );
343
- assert.equal(replayResult._tag, "Failure");
344
- if (replayResult._tag === "Failure") {
345
- assert.ok(isPersistenceDecodeError(replayResult.failure));
346
- }
347
- }),
348
- );
349
-
298
it.effect("orders project and V2 agent events in the retained application event source", () =>
299
Effect.gen(function* () {
300
const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
apps/server/src/preview/Manager.test.ts
-22
@@ -2,7 +2,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { it } from "@effect/vitest";
4
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
5
-import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
5
import * as Effect from "effect/Effect";
6
import * as Layer from "effect/Layer";
7
import * as PubSub from "effect/PubSub";
@@ -158,27 +157,6 @@ it.layer(layer)("PreviewManager", (it) => {
157
}),
158
);
159
161
- it.effect("preserves URL parser failures as the invalid URL cause chain", () =>
162
- Effect.gen(function* () {
163
- const threadId = freshThreadId();
164
- const manager = yield* PreviewManager.PreviewManager;
165
- const rawUrl = "https://user:password@example.com:bad/path?access_token=secret#fragment";
166
- const error = yield* Effect.flip(manager.open({ threadId, url: rawUrl }));
167
-
168
- expect(error).toMatchObject({
169
- inputLength: rawUrl.length,
170
- reason: "parse",
171
- protocol: "https:",
172
- });
173
- expect(error).not.toHaveProperty("rawUrl");
174
- expect(error.cause).toBeInstanceOf(PreviewUrlNormalizationError);
175
- const normalizationError = error.cause as PreviewUrlNormalizationError;
176
- expect(normalizationError.cause).toBeInstanceOf(Error);
177
- expect(error.message).not.toContain((normalizationError.cause as Error).message);
178
- expect(error.message).not.toMatch(/user|password|access_token|secret|fragment/);
179
- }),
180
- );
181
-
160
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
161
Effect.gen(function* () {
162
const threadId = freshThreadId();
apps/server/src/processRunner.test.ts
-38
@@ -117,44 +117,6 @@ describe("runProcess", () => {
117
);
118
});
119
120
- it.effect("preserves resolved spawn context and cause", () =>
121
- Effect.gen(function* () {
122
- const cause = PlatformError.systemError({
123
- _tag: "PermissionDenied",
124
- module: "ChildProcessSpawner",
125
- method: "spawn",
126
- pathOrDescriptor: "/actual/fake",
127
- });
128
- const spawner = makeSpawner(() => Effect.fail(cause));
129
-
130
- const error = yield* runWith(spawner)({
131
- command: "fake",
132
- args: ["--flag", "secret-token-value"],
133
- cwd: "/logical",
134
- spawnCwd: "/actual",
135
- }).pipe(Effect.flip);
136
-
137
- expect(error._tag).toBe("ProcessSpawnError");
138
- if (error._tag !== "ProcessSpawnError") {
139
- return expect.fail("Expected ProcessSpawnError");
140
- }
141
- expect(error).toMatchObject({
142
- command: "fake",
143
- argumentCount: 2,
144
- cwd: "/logical",
145
- spawnCwd: "/actual",
146
- resolvedCommand: "fake",
147
- resolvedArgumentCount: 2,
148
- shell: false,
149
- });
150
- expect(error.cause).toBe(cause);
151
- expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
152
- expect(error).not.toHaveProperty("args");
153
- expect(error).not.toHaveProperty("resolvedArgs");
154
- expect(error.message).not.toContain("secret-token-value");
155
- }),
156
- );
157
-
120
it.effect("types spawn failures that the platform spawner throws synchronously", () =>
121
Effect.gen(function* () {
122
// A non-directory entry on PATH makes node's spawn throw ENOTDIR
apps/server/src/project/AgentSessionScanner.test.ts
-67
@@ -2152,53 +2152,6 @@ describe("parseAgentSessionTranscript", () => {
2152
]);
2153
});
2154
2155
- it("preserves a canonical Codex event that starts with context markup", () => {
2156
- const prompt =
2157
- "<environment_context>\n<cwd>/tmp/project</cwd>\n</environment_context>\n\nCreate a useful project.";
2158
- const thread = AgentSessionScanner.parseAgentSessionTranscript({
2159
- contents: [
2160
- encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
2161
- encodeTranscriptRecord({
2162
- type: "event_msg",
2163
- payload: {
2164
- type: "user_message",
2165
- message: prompt,
2166
- },
2167
- }),
2168
- ].join("\n"),
2169
- source: "codex",
2170
- providerInstanceId: ProviderInstanceId.make("codex"),
2171
- fallbackSessionId: "fallback",
2172
- lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
2173
- });
2174
-
2175
- expect(thread?.title).toBe("Create a useful project.");
2176
- expect(thread?.messages.map((message) => message.text)).toEqual([prompt]);
2177
- });
2178
-
2179
- it("preserves a Codex request heading in a canonical event", () => {
2180
- const prompt = "\n ## My request for Codex:\n\nFix the visible bug";
2181
- const thread = AgentSessionScanner.parseAgentSessionTranscript({
2182
- contents: [
2183
- encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
2184
- encodeTranscriptRecord({
2185
- type: "event_msg",
2186
- payload: {
2187
- type: "user_message",
2188
- message: prompt,
2189
- },
2190
- }),
2191
- ].join("\n"),
2192
- source: "codex",
2193
- providerInstanceId: ProviderInstanceId.make("codex"),
2194
- fallbackSessionId: "fallback",
2195
- lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
2196
- });
2197
-
2198
- expect(thread?.title).toBe("Fix the visible bug");
2199
- expect(thread?.messages.map((message) => message.text)).toEqual([prompt]);
2200
- });
2201
-
2155
it("titles a Codex event after the request that follows injected setup blocks", () => {
2156
const prompt = [
2157
"<recommended_plugins>\nGitHub\n</recommended_plugins>",
@@ -2224,26 +2177,6 @@ describe("parseAgentSessionTranscript", () => {
2177
expect(thread?.messages.map((message) => message.text)).toEqual([prompt]);
2178
});
2179
2227
- it("keeps context markup quoted inside visible Codex user text", () => {
2228
- const quoted =
2229
- "Do not remove this example:\n<environment_context>\n<cwd>/tmp/example</cwd>\n</environment_context>";
2230
- const thread = AgentSessionScanner.parseAgentSessionTranscript({
2231
- contents: [
2232
- encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }),
2233
- encodeTranscriptRecord({
2234
- type: "event_msg",
2235
- payload: { type: "user_message", message: quoted },
2236
- }),
2237
- ].join("\n"),
2238
- source: "codex",
2239
- providerInstanceId: ProviderInstanceId.make("codex"),
2240
- fallbackSessionId: "fallback",
2241
- lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"),
2242
- });
2243
-
2244
- expect(thread?.messages.map((message) => message.text)).toEqual([quoted]);
2245
- });
2246
-
2180
it("skips sessions without a visible user message", () => {
2181
const thread = AgentSessionScanner.parseAgentSessionTranscript({
2182
contents: JSON.stringify({
apps/server/src/project/ProjectFaviconResolver.test.ts
+1
@@ -207,6 +207,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => {
207
}),
208
);
209
210
+ // regression: #5538 favicon resolution pinned the event loop
211
it.effect("skips icon metadata without an href and keeps scanning", () =>
212
Effect.gen(function* () {
213
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
apps/server/src/project/T3ProjectFileLoader.test.ts
-23
@@ -28,29 +28,6 @@ const writeProjectFile = Effect.fn("writeProjectFile")(function* (cwd: string, c
28
29
it.layer(layerTest)("T3ProjectFileLoader", (it) => {
30
describe("load", () => {
31
- it.effect("loads and decodes a valid t3.json", () =>
32
- Effect.gen(function* () {
33
- const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
34
- const cwd = yield* makeTempDir;
35
- yield* writeProjectFile(
36
- cwd,
37
- `{
38
- // JSONC is tolerated
39
- "iconPath": "assets/logo.svg",
40
- "scripts": [{ "name": "Dev", "command": "pnpm dev" }],
41
- }`,
42
- );
43
-
44
- const loaded = yield* loader.load(cwd);
45
-
46
- expect(Option.isSome(loaded)).toBe(true);
47
- if (Option.isSome(loaded)) {
48
- expect(loaded.value.iconPath).toBe("assets/logo.svg");
49
- expect(loaded.value.scripts).toEqual([{ name: "Dev", command: "pnpm dev" }]);
50
- }
51
- }),
52
- );
53
-
31
it.effect("returns none for malformed JSON without failing", () =>
32
Effect.gen(function* () {
33
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
apps/server/src/provider/AcpRegistryProbe.test.ts
-44
@@ -374,50 +374,6 @@ describe("ACP Registry probe", () => {
374
);
375
});
376
377
- it.effect("preserves the ACP method error for unsupported session management", () => {
378
- const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
379
- search: () => Effect.die("unused search"),
380
- prepare: () => Effect.die("unused prepare"),
381
- inspect: () => Effect.die("unused inspect"),
382
- uninstallManagedBinary: () => Effect.die("unused uninstall"),
383
- resolve: () =>
384
- Effect.succeed({
385
- agent: {
386
- id: "mock-agent",
387
- name: "Mock Agent",
388
- version: "1.0.0",
389
- description: "ACP unsupported management test agent",
390
- distribution: { npx: { package: "mock-agent@1.0.0" } },
391
- },
392
- distribution: "npx" as const,
393
- spawn: {
394
- command: "node",
395
- args: [mockAgentPath],
396
- env: { ...process.env, T3_ACP_OMIT_SESSION_LIST_HANDLER: "1" },
397
- },
398
- }),
399
- });
400
-
401
- return Effect.gen(function* () {
402
- const failure = yield* listAcpRegistrySessions({
403
- instanceId,
404
- settings: decodeSettings({ agentId: "mock-agent" }),
405
- cwd: process.cwd(),
406
- environment: process.env,
407
- }).pipe(Effect.flip);
408
-
409
- expect(failure).toMatchObject({
410
- reason: "session_list_unsupported",
411
- message: "The ACP agent does not advertise session listing.",
412
- cause: { _tag: "AcpRequestError", code: -32601 },
413
- });
414
- }).pipe(
415
- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
416
- Effect.provide(NodeServices.layer),
417
- Effect.scoped,
418
- );
419
- });
420
-
377
it("distinguishes authentication failures from generic probe failures", () => {
378
const advertised = normalizeAcpRegistryAuthMethods([
379
{ id: "grok-login", name: "Log in with Grok" },
apps/server/src/provider/CodexMcpElicitation.test.ts
+1
@@ -60,6 +60,7 @@ describe("Codex MCP elicitation approvals", () => {
60
});
61
});
62
63
+ // regression: #8058 show Codex app access approval prompts
64
it("returns persistent approval in the MCP response", () => {
65
NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "acceptAlways"), {
66
action: "accept",
apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts
+1
@@ -10,6 +10,7 @@ const skillMap = (names: Iterable<string>) =>
10
const SKILLS = skillMap(["2spec", "implement", "review", "re-release-version"]);
11
12
describe("planClaudeSkillDispatch", () => {
13
+ // regression: #9128 skills picked from the composer did not run
14
it("leaves a prompt without a known skill untouched", () => {
15
expect(planClaudeSkillDispatch("fix the build", SKILLS)).toBeUndefined();
16
expect(planClaudeSkillDispatch("echo $HOME then $unknown", SKILLS)).toBeUndefined();
apps/server/src/provider/Drivers/ClaudeSkills.test.ts
+1
@@ -807,6 +807,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
807
}),
808
);
809
810
+ // regression: #9128 skills picked from the composer did not run
811
it.effect("switches a skill off by its directory name", () =>
812
Effect.gen(function* () {
813
const fs = yield* FileSystem.FileSystem;
apps/server/src/provider/Drivers/claudeUsage.test.ts
-5
@@ -86,9 +86,4 @@ describe("parseClaudeLine", () => {
86
expect(claudeUsageFormat.parseLine(JSON.stringify(synthetic), undefined)).toEqual([]);
87
expect(claudeUsageFormat.parseProjected(synthetic, undefined)).toEqual([]);
88
});
89
-
90
- it("ignores records that are not assistant messages", () => {
91
- expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
92
- expect(parseClaudeLine("not json")).toBeNull();
93
- });
89
});
apps/server/src/provider/EventNdjsonLogger.test.ts
-33
@@ -338,39 +338,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => {
338
}),
339
);
340
341
- it.effect("contains hostile event accessors inside guarded serialization", () =>
342
- Effect.gen(function* () {
343
- const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
344
- const basePath = NodePath.join(tempDir, "events.log");
345
-
346
- try {
347
- const logger = yield* makeEventNdjsonLogger(basePath, {
348
- stream: "canonical",
349
- batchWindowMs: 0,
350
- });
351
- assert.exists(logger);
352
- if (!logger) return;
353
- const hostile = new Proxy(
354
- { id: "hostile" },
355
- {
356
- get(_target, property) {
357
- if (property === "type") throw new Error("blocked");
358
- return undefined;
359
- },
360
- },
361
- );
362
-
363
- yield* logger.write(hostile, ThreadId.make("thread-hostile"));
364
- yield* logger.close();
365
-
366
- const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8");
367
- assert.notInclude(contents, "blocked");
368
- } finally {
369
- NodeFS.rmSync(tempDir, { recursive: true, force: true });
370
- }
371
- }),
372
- );
373
-
341
it.effect("serializes concurrent first writes for the same segment", () =>
342
Effect.gen(function* () {
343
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
apps/server/src/provider/GrokProvider.test.ts
+1
@@ -425,6 +425,7 @@ describe("Grok usage limits", () => {
425
}
426
});
427
428
+ // regression: #17061 show zero-use Grok billing periods
429
it("rejects impossible calendar dates at either period boundary", () => {
430
for (const [start, end] of [
431
["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"],
apps/server/src/provider/ProviderRegistry.test.ts
-27
@@ -2287,32 +2287,5 @@ it.layer(
2287
),
2288
),
2289
);
2290
-
2291
- it.effect("returns error when version check fails with non-zero exit code", () => {
2292
- const secretStderr = "Something went wrong: secret-token-value";
2293
- return Effect.gen(function* () {
2294
- const status = yield* checkClaudeProviderStatus(
2295
- defaultClaudeSettings,
2296
- claudeCapabilities(),
2297
- );
2298
- assert.strictEqual(status.status, "error");
2299
- assert.strictEqual(status.installed, true);
2300
- assert.strictEqual(status.message, "Claude Agent CLI is installed but failed to run.");
2301
- assert.ok(!(status.message ?? "").includes(secretStderr));
2302
- }).pipe(
2303
- Effect.provide(
2304
- layerMockSpawner((args) => {
2305
- const joined = args.join(" ");
2306
- if (joined === "--version")
2307
- return {
2308
- stdout: "",
2309
- stderr: secretStderr,
2310
- code: 1,
2311
- };
2312
- throw new Error(`Unexpected args: ${joined}`);
2313
- }),
2314
- ),
2315
- );
2316
- });
2290
});
2291
});
apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+1
@@ -1009,6 +1009,7 @@ describe("AcpSessionRuntime", () => {
1009
),
1010
);
1011
1012
+ // regression: #3156 harden ACP resume with replay-idle load readiness
1013
it.effect("fails session startup when session/load returns an error", () =>
1014
Effect.gen(function* () {
1015
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
-17
@@ -485,21 +485,4 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
485
});
486
}),
487
);
488
-
489
- it.effect("rejects an empty turn", () =>
490
- Effect.gen(function* () {
491
- const fixture = yield* makeAttachmentFixture();
492
- const error = yield* buildAntigravityPrompt({
493
- input: " ",
494
- attachments: [],
495
- attachmentsDir: fixture.attachmentsDir,
496
- }).pipe(Effect.flip);
497
-
498
- expect(error).toMatchObject({
499
- _tag: "AcpRequestError",
500
- code: -32602,
501
- errorMessage: "A turn requires text or supported attachments.",
502
- });
503
- }),
504
- );
488
});
apps/server/src/provider/antigravityAuthSupport.test.ts
-21
@@ -211,16 +211,6 @@ describe("Antigravity process environment", () => {
211
});
212
213
describe("Antigravity authorization URL", () => {
214
- it.effect("returns the official Google URL and its owned loopback target", () =>
215
- Effect.gen(function* () {
216
- expect(yield* parseAntigravityAuthorizationUrl(authorizationUrl)).toEqual({
217
- authorizationUrl,
218
- redirectUri: "http://127.0.0.1:46353/",
219
- state: "test-opaque-state",
220
- });
221
- }),
222
- );
223
-
214
it.effect(
215
"rejects other origins, ambiguous state, and non-loopback redirects without retaining them",
216
() =>
@@ -304,17 +294,6 @@ describe("Antigravity stdout compatibility", () => {
294
}),
295
);
296
307
- it.effect("handles an auth line without a final newline", () =>
308
- Effect.gen(function* () {
309
- const urls: string[] = [];
310
- const result = yield* makeAntigravityStdoutTransform({
311
- onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
312
- })(Stream.make(encode(authLine.slice(0, -1)))).pipe(Stream.runCollect);
313
- expect(result).toEqual([]);
314
- expect(urls).toEqual([authorizationUrl]);
315
- }),
316
- );
317
-
297
it.effect("ends normal work with a safe sign-in error instead of waiting for OAuth", () =>
298
Effect.gen(function* () {
299
const result = yield* makeAntigravityStdoutTransform()(Stream.make(encode(authLine))).pipe(
apps/server/src/provider/providerStatusCache.test.ts
+1
-41
@@ -7,15 +7,8 @@ import {
7
} from "@t3tools/contracts";
8
import { createModelCapabilities } from "@t3tools/shared/model";
9
import { assert, it } from "@effect/vitest";
10
-import * as Effect from "effect/Effect";
11
-import * as FileSystem from "effect/FileSystem";
12
-import * as Logger from "effect/Logger";
10
14
-import {
15
- hydrateCachedProvider,
16
- isCachedProviderCorrelated,
17
- readProviderStatusCache,
18
-} from "./providerStatusCache.ts";
11
+import { hydrateCachedProvider, isCachedProviderCorrelated } from "./providerStatusCache.ts";
12
13
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
14
const CODEX_DRIVER = ProviderDriverKind.make("codex");
@@ -39,39 +32,6 @@ const makeProvider = (
32
});
33
34
it.layer(NodeServices.layer)("providerStatusCache", (it) => {
42
- it.effect("logs structural diagnostics without retaining invalid cache contents", () => {
43
- const messages: Array<unknown> = [];
44
- const logger = Logger.make<unknown, void>((options) => {
45
- if (Array.isArray(options.message)) {
46
- messages.push(...options.message);
47
- } else {
48
- messages.push(options.message);
49
- }
50
- });
51
-
52
- return Effect.gen(function* () {
53
- const fs = yield* FileSystem.FileSystem;
54
- const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-invalid-" });
55
- const cachePath = `${tempDir}/provider.json`;
56
- const secretCacheValue = "secret-cache-value";
57
- yield* fs.writeFileString(cachePath, `{ "token": "${secretCacheValue}" }`);
58
-
59
- const result = yield* readProviderStatusCache(cachePath);
60
-
61
- assert.strictEqual(result, undefined);
62
- const failure = messages.find(
63
- (message): message is Record<string, unknown> =>
64
- typeof message === "object" && message !== null && "path" in message,
65
- );
66
- assert.exists(failure);
67
- assert.strictEqual(failure.path, cachePath);
68
- assert.strictEqual(typeof failure.errorTag, "string");
69
- assert.ok(!("cause" in failure));
70
- assert.ok(!("issues" in failure));
71
- assert.ok(!Object.values(failure).map(String).join("\n").includes(secretCacheValue));
72
- }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
73
- });
74
-
35
it("hydrates cached provider status while preserving current settings-derived models", () => {
36
const cachedCodex = makeProvider(CODEX_DRIVER, {
37
checkedAt: "2026-04-10T12:00:00.000Z",
apps/server/src/pullRequest/PullRequestService.test.ts
+1
-48
@@ -477,31 +477,6 @@ it.effect("says where each repository carries on, and from nothing it has run ou
477
}),
478
);
479
480
-it.effect("offers no continuation for a host that cannot be carried on from", () =>
481
- Effect.gen(function* () {
482
- const service = yield* makeService({
483
- projects: [
484
- project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
485
- ],
486
- providers: [
487
- fakeProvider(SourceControlProviderKind.make("github"), {
488
- listChangeRequests: () =>
489
- Effect.succeed({
490
- items: [changeRequest(1, "2026-07-02T00:00:00Z")],
491
- truncated: true,
492
- continues: false,
493
- }),
494
- }),
495
- ],
496
- });
497
-
498
- const result = yield* service.list({ state: "open" });
499
-
500
- assert.isTrue(result.truncated);
501
- assert.deepStrictEqual(result.nextCursors, {});
502
- }),
503
-);
504
-
480
it.effect("uses a provider's raw cursor advance when it consumed malformed rows", () =>
481
Effect.gen(function* () {
482
const service = yield* makeService({
@@ -1827,6 +1802,7 @@ it.effect("prefers a matching checkout over a non-repository project's directory
1802
}),
1803
);
1804
1805
+// regression: #17167 refresh linked PRs without a checkout
1806
it.effect("requires an explicit host for a non-repository project's linked PR", () =>
1807
Effect.gen(function* () {
1808
const service = yield* makeService({
@@ -2160,29 +2136,6 @@ it.effect("close and reopen notify subscribed readers after invalidating their c
2136
),
2137
);
2138
2163
-it.effect("does not cache a failed listing", () =>
2164
- Effect.gen(function* () {
2165
- let hostCalls = 0;
2166
- const service = yield* makeService({
2167
- projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2168
- providers: [
2169
- fakeProvider(SourceControlProviderKind.make("github"), {
2170
- getViewer: () => {
2171
- hostCalls += 1;
2172
- return hostCalls === 1 ? Effect.fail(requestFailed) : Effect.succeed("bilal");
2173
- },
2174
- }),
2175
- ],
2176
- });
2177
-
2178
- const error = yield* Effect.flip(service.list({ state: "open" }));
2179
- assert.strictEqual(error._tag, "PullRequestOperationError");
2180
- const second = yield* service.list({ state: "open" });
2181
- assert.strictEqual(hostCalls, 2);
2182
- assert.strictEqual(second.providers[0]?.configured, true);
2183
- }),
2184
-);
2185
-
2139
it.effect("reads a host's repositories in one search, and files the rows back under each", () =>
2140
Effect.gen(function* () {
2141
const asked: Array<ReadonlyArray<string>> = [];
apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts
-12
@@ -121,18 +121,6 @@ describe("normalizeReviewGuide", () => {
121
expect(result.stops).toHaveLength(1);
122
});
123
124
- it("keeps a long excerpt to its first 25 lines", () => {
125
- const long = parseReviewGuideChange(
126
- "big.ts\0",
127
- "--- a/big.ts\n+++ b/big.ts\n@@ -0,0 +1,100 @@\n",
128
- );
129
- const result = normalizeReviewGuide(
130
- guide({ stops: [stop({ excerpts: [excerpt("big.ts", 1, 100)] })] }),
131
- long,
132
- );
133
- expect(result.stops[0]?.excerpts).toEqual([excerpt("big.ts", 1, 25)]);
134
- });
135
-
124
it("drops notes outside the stop's remaining excerpts", () => {
125
const result = normalizeReviewGuide(
126
guide({
apps/server/src/resourceTelemetry/ResourceMonitorBinary.test.ts
+1
@@ -65,6 +65,7 @@ describe("ResourceMonitorBinary", () => {
65
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
66
);
67
68
+ // regression: #16838 a directory resolved as the resource monitor binary
69
it.effect("rejects a directory override", () =>
70
Effect.gen(function* () {
71
const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
-41
@@ -566,27 +566,6 @@ it.effect("a save without a secret keeps a secret changed after it was read", ()
566
),
567
);
568
569
-it.effect("logs a body's first 64 KiB by bytes, not characters", () =>
570
- withService(({ service }) =>
571
- Effect.gen(function* () {
572
- const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false }));
573
- const text = "界".repeat(30_000);
574
- const body = new TextEncoder().encode(text);
575
- yield* service.triggerWebhook(requestFor(task, { body, bodyText: text }));
576
- const [summary] = (yield* service.listWebhookDeliveries({
577
- id: task.id,
578
- acceptAnyOutcome: true,
579
- })).deliveries;
580
- const { delivery } = yield* service.getWebhookDelivery({
581
- id: task.id,
582
- deliveryId: summary!.id,
583
- });
584
- assert.isTrue(delivery.bodyTruncated);
585
- assert.isAtMost(new TextEncoder().encode(delivery.body).byteLength, 64 * 1024 + 3);
586
- }),
587
- ),
588
-);
589
-
569
it.effect("a held request already delivered directly runs only once", () =>
570
withService(({ service, launches }) =>
571
Effect.gen(function* () {
@@ -1024,26 +1003,6 @@ it.effect("rolls back replay and pending state when recording a delivery fails",
1003
);
1004
});
1005
1027
-it.effect("a partially missing key is empty even with a literal prefix", () =>
1028
- withService(({ service, launches }) =>
1029
- Effect.gen(function* () {
1030
- const { task } = yield* service.upsert(
1031
- yield* webhookTaskInput({
1032
- schedule: {
1033
- type: "webhook",
1034
- dedupe: { replayKey: "gh:{{headers.absent}}", coalesceKey: "pr:{{body.absent}}" },
1035
- },
1036
- }),
1037
- );
1038
- for (let i = 0; i < 2; i++) {
1039
- const result = yield* service.triggerWebhook(requestFor(task, { headers: { absent: "" } }));
1040
- assert.equal(result._tag === "accepted" && result.outcome, "accepted");
1041
- yield* Queue.take(launches);
1042
- }
1043
- }),
1044
- ),
1045
-);
1046
-
1006
it.effect("queue-full deliveries release replay keys so a later retry runs", () =>
1007
Effect.gen(function* () {
1008
const gate = yield* Deferred.make<void>();
apps/server/src/scheduledTasks/webhookRoute.test.ts
-29
@@ -113,35 +113,6 @@ const post = (
113
) => new Request(`http://env.local${path}`, { method: "POST", body, headers });
114
115
describe("webhook route", () => {
116
- it("passes the raw request to the service and answers 202 with the delivery id", async () => {
117
- let received: WebhookTriggerRequest | undefined;
118
- const { handler, dispose } = handlerFor((request) => {
119
- received = request;
120
- return Effect.succeed({
121
- _tag: "accepted",
122
- deliveryId: ScheduledTaskWebhookDeliveryId.make("delivery:1"),
123
- outcome: "accepted",
124
- });
125
- });
126
- try {
127
- const response = await handler(
128
- post("/api/hooks/scheduled-task%3Ahook/tok?x=1", '{"a":1}', {
129
- "Content-Type": "application/json",
130
- "X-GitHub-Event": "push",
131
- }),
132
- );
133
- expect(response.status).toBe(202);
134
- expect(await response.json()).toEqual({ deliveryId: "delivery:1" });
135
- expect(received?.hookId).toBe("scheduled-task:hook");
136
- expect(received?.token).toBe("tok");
137
- expect(received?.query).toBe("x=1");
138
- expect(received?.headers["x-github-event"]).toBe("push");
139
- expect(received?.bodyText).toBe('{"a":1}');
140
- } finally {
141
- await dispose();
142
- }
143
- });
144
-
116
it.live("trusts the relay's delivery id and receive time only with its signed proof", () =>
117
Effect.gen(function* () {
118
const received: Array<WebhookTriggerRequest> = [];
apps/server/src/serverLogger.test.ts
+1
@@ -165,6 +165,7 @@ describe("ServerLoggerLive", () => {
165
}),
166
);
167
168
+ // regression: #16642 logs printed causes as [Object]
169
it.effect("leaves getters uncalled while printing a cause field", () =>
170
Effect.gen(function* () {
171
const output = yield* printThroughConsole({
apps/server/src/serverRuntimeState.test.ts
-49
@@ -4,12 +4,9 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
4
import * as Effect from "effect/Effect";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Layer from "effect/Layer";
7
-import * as Logger from "effect/Logger";
7
import * as Option from "effect/Option";
8
import * as Path from "effect/Path";
10
-import * as References from "effect/References";
9
import * as Runtime from "effect/Runtime";
12
-import * as Schema from "effect/Schema";
10
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12
import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
@@ -19,8 +16,6 @@ import * as ProcessRunner from "./processRunner.ts";
16
import * as ServerOwnership from "./serverOwnership.ts";
17
import * as ServerRuntimeState from "./serverRuntimeState.ts";
18
22
-const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
23
-
19
const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: {
20
readonly platform: "darwin" | "linux";
21
readonly outputs: Readonly<Record<string, { readonly code: number; readonly stdout?: string }>>;
@@ -132,11 +127,6 @@ const startBesideBootService = Effect.fn("test.startBesideBootService")(function
127
return { result, t3Home };
128
});
129
135
-interface CapturedLog {
136
- readonly message: unknown;
137
- readonly annotations: Readonly<Record<string, unknown>>;
138
-}
139
-
130
describe("server ownership", () => {
131
// An empty home, so no boot service unit installed on this machine is read.
132
const layerOwnership = Layer.mergeAll(
@@ -407,42 +397,3 @@ describe("server ownership", () => {
397
);
398
});
399
});
410
-
411
-describe("serverRuntimeState", () => {
412
- it.effect("preserves malformed state decode failures", () => {
413
- const logs: CapturedLog[] = [];
414
- const logger = Logger.make(({ fiber, message }) => {
415
- logs.push({
416
- message,
417
- annotations: fiber.getRef(References.CurrentLogAnnotations),
418
- });
419
- });
420
-
421
- return Effect.gen(function* () {
422
- const fileSystem = yield* FileSystem.FileSystem;
423
- const path = yield* Path.Path;
424
- const root = yield* fileSystem.makeTempDirectoryScoped({
425
- prefix: "t3-server-runtime-state-test-",
426
- });
427
- const statePath = path.join(root, "server.json");
428
- yield* fileSystem.writeFileString(statePath, "{not json");
429
-
430
- const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
431
-
432
- assert.isTrue(Option.isNone(restored));
433
- assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
434
- const error = logs[0]?.annotations.cause;
435
- assert.isTrue(isServerRuntimeStateError(error));
436
- if (isServerRuntimeStateError(error)) {
437
- assert.equal(error.operation, "decode");
438
- assert.equal(error.statePath, statePath);
439
- assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
440
- assert.deepInclude(error.cause, { _tag: "SchemaError" });
441
- }
442
- }).pipe(
443
- Effect.provide(
444
- Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
445
- ),
446
- );
447
- });
448
-});
apps/server/src/serverSettings.test.ts
-45
@@ -234,51 +234,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
234
}).pipe(Effect.provide(layerServerSettings())),
235
);
236
237
- it.effect("preserves context when reading a provider environment secret fails", () => {
238
- const platformCause = PlatformError.systemError({
239
- _tag: "PermissionDenied",
240
- module: "FileSystem",
241
- method: "readFile",
242
- pathOrDescriptor: "provider environment secret",
243
- description: "Secret backend unavailable.",
244
- });
245
- const cause = new ServerSecretStore.SecretStoreReadError({
246
- resource: "provider environment secret",
247
- cause: platformCause,
248
- });
249
- const layerConfig = Layer.fresh(
250
- ServerConfig.layerTest(process.cwd(), {
251
- prefix: "t3code-server-settings-secret-failure-test-",
252
- }),
253
- );
254
- const layerSettings = ServerSettingsModule.layer.pipe(
255
- Layer.provide(layerFailingSecretStore(cause)),
256
- Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
257
- Layer.provideMerge(layerConfig),
258
- );
259
-
260
- return Effect.gen(function* () {
261
- const serverConfig = yield* ServerConfig.ServerConfig;
262
- const fileSystem = yield* FileSystem.FileSystem;
263
- const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
264
- yield* fileSystem.writeFileString(
265
- serverConfig.settingsPath,
266
- '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}',
267
- );
268
-
269
- const error = yield* Effect.flip(serverSettings.getSettings);
270
-
271
- assert.deepInclude(error, {
272
- _tag: "ServerSettingsError",
273
- operation: "read-secret",
274
- providerInstanceId: "codex_personal",
275
- environmentVariable: "OPENROUTER_API_KEY",
276
- });
277
- assert.strictEqual(error.cause, cause);
278
- assert.notInclude(error.message, cause.message);
279
- }).pipe(Effect.provide(layerSettings));
280
- });
281
-
237
it.effect("retries a failed settings read instead of keeping the failure", () =>
238
Effect.gen(function* () {
239
const serverConfig = yield* ServerConfig.ServerConfig;
apps/server/src/sourceControl/BitbucketApi.test.ts
-51
@@ -424,57 +424,6 @@ it.effect(
424
},
425
);
426
427
-it.effect(
428
- "falls back to the repository main branch when the Bitbucket branching model is unavailable",
429
- () => {
430
- const { layer } = makeLayer({
431
- response: (request) =>
432
- request.url.endsWith("/branching-model")
433
- ? Response.json({ error: { message: "Not found" } }, { status: 404 })
434
- : Response.json(repositoryJson),
435
- });
436
-
437
- return Effect.gen(function* () {
438
- const bitbucket = yield* BitbucketApi.BitbucketApi;
439
- const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
440
-
441
- assert.strictEqual(defaultBranch, "main");
442
- }).pipe(Effect.provide(layer));
443
- },
444
-);
445
-
446
-it.effect("creates repositories through the Bitbucket REST API", () => {
447
- const { execute, layer } = makeLayer({
448
- response: () => Response.json(repositoryJson),
449
- });
450
-
451
- return Effect.gen(function* () {
452
- const bitbucket = yield* BitbucketApi.BitbucketApi;
453
- const cloneUrls = yield* bitbucket.createRepository({
454
- cwd: "/repo",
455
- repository: "pingdotgg/t3code",
456
- visibility: "private",
457
- });
458
-
459
- assert.deepStrictEqual(cloneUrls, {
460
- nameWithOwner: "pingdotgg/t3code",
461
- url: "https://bitbucket.org/pingdotgg/t3code.git",
462
- sshUrl: "git@bitbucket.org:pingdotgg/t3code.git",
463
- });
464
-
465
- const request = execute.mock.calls[0]?.[0];
466
- assert.strictEqual(request?.url, "https://api.test.local/2.0/repositories/pingdotgg/t3code");
467
- assert.strictEqual(request?.method, "POST");
468
- assert.ok(request);
469
- const rawBody = (request.body as { readonly body?: Uint8Array }).body;
470
- assert.ok(rawBody);
471
- assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
472
- scm: "git",
473
- is_private: true,
474
- });
475
- }).pipe(Effect.provide(layer));
476
-});
477
-
427
it.effect("creates pull requests using the official REST payload shape", () => {
428
const { execute, layer } = makeLayer({
429
response: () => Response.json(bitbucketPullRequest),
apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
+1
@@ -431,6 +431,7 @@ it.effect("explains a rejected SSH push after creating the repository", () =>
431
}).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
432
);
433
434
+// regression: #19219 publishing did not explain why the first push failed
435
it.effect("says the repository exists when an unclassified publish push fails", () =>
436
Effect.gen(function* () {
437
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
apps/server/src/terminal/Manager.test.ts
-129
@@ -8,7 +8,6 @@ import {
8
type TerminalRestartInput,
9
ProviderDriverKind,
10
ProviderInstanceId,
11
- ServerSettingsError,
11
TerminalProviderInstanceNotFoundError,
12
} from "@t3tools/contracts";
13
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -561,14 +560,6 @@ it.layer(
560
}),
561
);
562
564
- const makeDirectory = (filePath: string) =>
565
- Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
566
- fs.makeDirectory(filePath, { recursive: true }),
567
- );
568
-
569
- const chmod = (filePath: string, mode: number) =>
570
- Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.chmod(filePath, mode));
571
-
563
const pathExists = (filePath: string) =>
564
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath));
565
@@ -580,32 +571,6 @@ it.layer(
571
fs.writeFileString(filePath, contents),
572
);
573
583
- it.effect("preserves non-notFound cwd stat failures", () =>
584
- Effect.gen(function* () {
585
- if ((yield* HostProcess.Platform) === "win32") return;
586
-
587
- const path = yield* Path.Path;
588
-
589
- const { manager, baseDir } = yield* createManager();
590
- const blockedRoot = path.join(baseDir, "blocked-root");
591
- const blockedCwd = path.join(blockedRoot, "cwd");
592
- yield* makeDirectory(blockedCwd);
593
- yield* chmod(blockedRoot, 0o000);
594
-
595
- const error = yield* Effect.flip(manager.open(openInput({ cwd: blockedCwd }))).pipe(
596
- Effect.ensuring(chmod(blockedRoot, 0o755).pipe(Effect.ignore)),
597
- );
598
-
599
- expect(error).toMatchObject({
600
- _tag: "TerminalCwdStatError",
601
- cwd: blockedCwd,
602
- cause: {
603
- _tag: "PlatformError",
604
- },
605
- });
606
- }),
607
- );
608
-
574
it.effect("handles an exit replayed during subscription after publishing startup", () =>
575
Effect.gen(function* () {
576
const ptyAdapter = new FakePtyAdapter();
@@ -636,60 +601,6 @@ it.layer(
601
}),
602
);
603
639
- it.effect("preserves structured context and causes for PTY I/O failures", () =>
640
- Effect.gen(function* () {
641
- const { manager, ptyAdapter } = yield* createManager();
642
- yield* manager.open(openInput());
643
- const process = ptyAdapter.processes[0];
644
- expect(process).toBeDefined();
645
- if (!process) return;
646
-
647
- const writeCause = new Error("PTY input handle is unavailable");
648
- process.writeFailure = writeCause;
649
- const writeError = yield* Effect.flip(
650
- manager.write({
651
- threadId: "thread-1",
652
- terminalId: DEFAULT_TERMINAL_ID,
653
- data: "secret input that must not be attached to the error",
654
- }),
655
- );
656
-
657
- expect(writeError).toMatchObject({
658
- _tag: "TerminalWriteError",
659
- threadId: "thread-1",
660
- terminalId: DEFAULT_TERMINAL_ID,
661
- terminalPid: process.pid,
662
- });
663
- expect(writeError.cause).toBe(writeCause);
664
- expect(writeError).not.toHaveProperty("data");
665
-
666
- const resizeCause = new Error("PTY resize handle is unavailable");
667
- process.resizeFailure = resizeCause;
668
- const resizeError = yield* Effect.flip(
669
- manager.resize({
670
- threadId: "thread-1",
671
- terminalId: DEFAULT_TERMINAL_ID,
672
- cols: 132,
673
- rows: 40,
674
- }),
675
- );
676
-
677
- expect(resizeError).toMatchObject({
678
- _tag: "TerminalResizeError",
679
- threadId: "thread-1",
680
- terminalId: DEFAULT_TERMINAL_ID,
681
- terminalPid: process.pid,
682
- cols: 132,
683
- rows: 40,
684
- });
685
- expect(resizeError.cause).toBe(resizeCause);
686
-
687
- process.resizeFailure = undefined;
688
- yield* manager.open(openInput({ cols: 132, rows: 40 }));
689
- expect(process.resizeCalls).toEqual([{ cols: 132, rows: 40 }]);
690
- }),
691
- );
692
-
604
it.effect("supports multiple terminals per thread independently", () =>
605
Effect.gen(function* () {
606
const { manager, ptyAdapter } = yield* createManager();
@@ -1293,46 +1204,6 @@ it.layer(
1204
}),
1205
);
1206
1296
- it.effect("preserves the settings failure when provider environment resolution fails", () =>
1297
- Effect.gen(function* () {
1298
- const path = yield* Path.Path;
1299
- const providerInstanceId = ProviderInstanceId.make("codex_work");
1300
- const settingsCause = new Error("secret store read failed");
1301
- const settingsError = new ServerSettingsError({
1302
- settingsPath: "/test/settings.json",
1303
- operation: "read-secret",
1304
- providerInstanceId,
1305
- environmentVariable: "OPENROUTER_API_KEY",
1306
- cause: settingsCause,
1307
- });
1308
- const serverSettings = ServerSettings.ServerSettingsService.of({
1309
- start: Effect.void,
1310
- ready: Effect.void,
1311
- getSettings: Effect.fail(settingsError),
1312
- updateSettings: () => Effect.fail(settingsError),
1313
- updateProviderInstance: () => Effect.fail(settingsError),
1314
- withSettingsSnapshot: () => Effect.fail(settingsError),
1315
- streamChanges: Stream.empty,
1316
- subscribeChanges: Effect.succeed(Stream.empty),
1317
- });
1318
-
1319
- const error = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
1320
- serverSettings,
1321
- path,
1322
- rawProviderInstanceId: providerInstanceId,
1323
- env: undefined,
1324
- }).pipe(Effect.flip);
1325
-
1326
- expect(error).toMatchObject({
1327
- _tag: "TerminalProviderEnvironmentError",
1328
- providerInstanceId,
1329
- });
1330
- expect(error.cause).toBe(settingsError);
1331
- expect(error.message).not.toContain(settingsError.message);
1332
- expect(error.message).not.toContain("OPENROUTER_API_KEY");
1333
- }),
1334
- );
1335
-
1207
it.effect.each([
1208
{
1209
name: "Codex home",
apps/server/src/terminal/nodePtyConsoleList.test.ts
+1
@@ -61,6 +61,7 @@ describe("node-pty console process list helper", () => {
61
expect(list).toEqual([SHELL_PID]);
62
});
63
64
+ // regression: #18519 Windows terminal kill waited on timeouts
65
it("falls back to the shell PID when the helper fails to spawn", async () => {
66
const list = await getConsoleProcessList((helper) => {
67
helper.emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }));
apps/server/src/textGeneration/GrokTextGeneration.test.ts
-20
@@ -132,24 +132,4 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => {
132
}),
133
),
134
);
135
-
136
- it.effect("fails with TextGenerationError when output is unparseable JSON", () =>
137
- withFakeAcpGrok(
138
- {
139
- T3_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model",
140
- },
141
- (textGeneration) =>
142
- Effect.gen(function* () {
143
- const error = yield* Effect.flip(
144
- textGeneration.generateThreadTitle({
145
- cwd: process.cwd(),
146
- message: "anything",
147
- modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
148
- }),
149
- );
150
- expect(error._tag).toBe("TextGenerationError");
151
- expect(error.detail).toMatch(/invalid structured output/i);
152
- }),
153
- ),
154
- );
135
});
apps/server/src/textGeneration/TextGeneration.test.ts
deleted
-107
@@ -1,107 +0,0 @@
1
-import { it } from "@effect/vitest";
2
-import * as Effect from "effect/Effect";
3
-import * as PubSub from "effect/PubSub";
4
-import * as Stream from "effect/Stream";
5
-import { describe, expect } from "vite-plus/test";
6
-
7
-import { ProviderInstanceId } from "@t3tools/contracts";
8
-import { createModelSelection } from "@t3tools/shared/model";
9
-
10
-import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
11
-import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
12
-import * as TextGeneration from "./TextGeneration.ts";
13
-import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
14
-import * as Layer from "effect/Layer";
15
-
16
-const makeStubTextGeneration = (
17
- overrides: Partial<TextGeneration.TextGeneration["Service"]>,
18
-): TextGeneration.TextGeneration["Service"] =>
19
- TextGeneration.TextGeneration.of({
20
- generateCommitMessage: () =>
21
- Effect.die("generateCommitMessage stub not configured for this test"),
22
- generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),
23
- generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),
24
- generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),
25
- generateReviewGuide: () => Effect.die("generateReviewGuide stub not configured for this test"),
26
- ...overrides,
27
- });
28
-
29
-const makeStubInstance = (
30
- instanceId: ProviderInstanceId,
31
- textGeneration: TextGeneration.TextGeneration["Service"],
32
-): ProviderInstance =>
33
- ({
34
- instanceId,
35
- driverKind: instanceId as unknown as ProviderInstance["driverKind"],
36
- continuationIdentity: {
37
- driverKind: instanceId as unknown as ProviderInstance["driverKind"],
38
- continuationKey: `${instanceId}:test`,
39
- },
40
- displayName: undefined,
41
- enabled: true,
42
- snapshot: {} as ProviderInstance["snapshot"],
43
- orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
44
- textGeneration,
45
- }) satisfies ProviderInstance;
46
-
47
-const makeStubRegistry = (
48
- instances: ReadonlyArray<ProviderInstance>,
49
-): ProviderInstanceRegistry.ProviderInstanceRegistry["Service"] => {
50
- const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const));
51
- return {
52
- getInstance: (id) => Effect.succeed(byId.get(id)),
53
- listInstances: Effect.succeed(instances),
54
- listUnavailable: Effect.succeed([]),
55
- streamChanges: Stream.empty,
56
- subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
57
- PubSub.subscribe(pubsub),
58
- ),
59
- };
60
-};
61
-
62
-describe("TextGeneration.make", () => {
63
- it.effect("delegates to the matching instance's textGeneration closure", () =>
64
- Effect.gen(function* () {
65
- const personalId = ProviderInstanceId.make("codex_personal");
66
- const personalCalls: string[] = [];
67
- const personal = makeStubInstance(
68
- personalId,
69
- makeStubTextGeneration({
70
- generateBranchName: (input) => {
71
- personalCalls.push(input.message);
72
- return Effect.succeed({ branch: "personal-branch" });
73
- },
74
- }),
75
- );
76
-
77
- const workId = ProviderInstanceId.make("codex_work");
78
- const work = makeStubInstance(
79
- workId,
80
- makeStubTextGeneration({
81
- generateBranchName: () => Effect.succeed({ branch: "work-branch" }),
82
- }),
83
- );
84
-
85
- const tg = yield* TextGeneration.make.pipe(
86
- Effect.provideService(
87
- ProviderInstanceRegistry.ProviderInstanceRegistry,
88
- makeStubRegistry([personal, work]),
89
- ),
90
- Effect.provide(
91
- Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
92
- resolveLink: () => Effect.die("No link lookup expected"),
93
- }),
94
- ),
95
- );
96
-
97
- const result = yield* tg.generateBranchName({
98
- cwd: process.cwd(),
99
- message: "Refactor the routing layer",
100
- modelSelection: createModelSelection(ProviderInstanceId.make("codex_personal"), "gpt-5"),
101
- });
102
-
103
- expect(result.branch).toBe("personal-branch");
104
- expect(personalCalls).toEqual(["Refactor the routing layer"]);
105
- }),
106
- );
107
-});
apps/server/src/usage/cliproxyApi.test.ts
+1
@@ -156,6 +156,7 @@ describe("CLIProxyAPI hub failures", () => {
156
}),
157
);
158
159
+ // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause
160
it.effect("ignores a transport code that is not a short Node error code", () =>
161
Effect.gen(function* () {
162
const api = yield* unreachableHub(
apps/server/src/usage/usageScanCache.test.ts
-23
@@ -2,7 +2,6 @@ import { describe, expect, it } from "@effect/vitest";
2
3
import {
4
decodeScanCache,
5
- dedupeWithinFile,
5
encodeScanCache,
6
makeScanCacheWriter,
7
type CachedFile,
@@ -253,15 +252,6 @@ describe("scan cache round trip", () => {
252
expect(document.sources).toEqual(sources);
253
});
254
256
- it("interns repeated model and session strings", () => {
257
- const encoded = encodeScanCache(
258
- cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
259
- );
260
-
261
- expect(encoded.models).toEqual(["claude-fable-5"]);
262
- expect(encoded.sessions).toEqual(["session-a"]);
263
- });
264
-
255
it("treats a corrupt or foreign document as an empty cache", () => {
256
expect(decodeScanCache(null, TEST_FORMAT_MAP).size).toBe(0);
257
expect(decodeScanCache("nonsense", TEST_FORMAT_MAP).size).toBe(0);
@@ -300,16 +290,3 @@ describe("scan cache round trip", () => {
290
expect(restored.has("/a.jsonl")).toBe(false);
291
});
292
});
303
-
304
-describe("dedupeWithinFile", () => {
305
- it("keeps the first record per dedupe key", () => {
306
- const kept = dedupeWithinFile([
307
- record({ totals: { ...record().totals, outputTokens: 1 } }),
308
- record({ totals: { ...record().totals, outputTokens: 999 } }),
309
- record({ dedupeKey: "msg_2:" }),
310
- ]);
311
-
312
- expect(kept).toHaveLength(2);
313
- expect(kept[0]?.totals.outputTokens).toBe(1);
314
- });
315
-});
apps/server/src/vcs/GitVcsDriverCore.test.ts
+4
@@ -837,6 +837,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
837
}),
838
);
839
840
+ // regression: #8645 name the cause of a failed git command
841
it.effect("names the branch conflict behind a failed worktree add", () =>
842
Effect.gen(function* () {
843
const parent = yield* makeTmpDir();
@@ -868,6 +869,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
869
}),
870
);
871
872
+ // regression: #8645 name the cause of a failed git command
873
it.effect("names a missing repository behind a failed command", () =>
874
Effect.gen(function* () {
875
const cwd = yield* makeTmpDir();
@@ -3408,6 +3410,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3410
}),
3411
);
3412
3413
+ // regression: #12485 explain fetch failures without exposing remote output
3414
it.effect("explains a real fetch failure for a missing local remote", () =>
3415
Effect.gen(function* () {
3416
const cwd = yield* makeTmpDir();
@@ -4269,6 +4272,7 @@ describe("Windows long path configuration", () => {
4272
}
4273
});
4274
4275
+ // regression: #14917 Windows worktrees with long paths failed or stranded
4276
it("leaves a count Git would reject for Git to report", () => {
4277
for (const count of ["nope", "2x", "-1", "1.5", " ", "1 "]) {
4278
assert.deepStrictEqual(
apps/server/src/vcs/VcsProcess.test.ts
-79
@@ -363,38 +363,6 @@ describe("VcsProcess.run", () => {
363
}).pipe(provideLive),
364
);
365
366
- it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
367
- Effect.gen(function* () {
368
- const secretArgument = "--token=super-secret-token";
369
- const secretStderr = "remote rejected super-secret-token";
370
- const error = yield* run({
371
- operation: "test.exit",
372
- command: "node",
373
- args: [
374
- "-e",
375
- "process.stderr.write(process.argv[1]); process.exit(2)",
376
- secretStderr,
377
- secretArgument,
378
- ],
379
- cwd: process.cwd(),
380
- }).pipe(Effect.flip);
381
-
382
- expect(error).toBeInstanceOf(VcsProcessExitError);
383
- expect(error).toMatchObject({
384
- operation: "test.exit",
385
- command: "node",
386
- argumentCount: 4,
387
- exitCode: 2,
388
- detail: "Process exited with a non-zero status.",
389
- failureKind: "command-failed",
390
- stderrLength: secretStderr.length,
391
- stderrTruncated: false,
392
- });
393
- expect(error.message).not.toContain(secretArgument);
394
- expect(error.message).not.toContain(secretStderr);
395
- }).pipe(provideLive),
396
- );
397
-
366
it.effect("classifies authentication failures without retaining stderr", () =>
367
Effect.gen(function* () {
368
const secretStderr = "authentication failed for token super-secret-token";
@@ -466,53 +434,6 @@ describe("VcsProcess.run", () => {
434
}).pipe(provideLive),
435
);
436
469
- it.effect("preserves real boundary causes without manufacturing structural ones", () =>
470
- Effect.gen(function* () {
471
- const cause = new Error("secret stdin failure");
472
- const error = yield* captureProcessResult(
473
- Effect.fail(
474
- new ProcessRunner.ProcessStdinError({
475
- command: baseInput.command,
476
- argumentCount: baseInput.args.length,
477
- cwd: baseInput.cwd,
478
- stdinBytes: 47,
479
- cause,
480
- }),
481
- ),
482
- );
483
-
484
- expect(error).toMatchObject({
485
- _tag: "VcsProcessStdinWriteError",
486
- operation: baseInput.operation,
487
- stdinBytes: 47,
488
- cause,
489
- });
490
- expect(error.message).not.toContain(cause.message);
491
-
492
- const missingExitCodeError = yield* captureProcessResult(
493
- Effect.succeed({
494
- stdout: "",
495
- stderr: "",
496
- code: null,
497
- timedOut: false,
498
- stdoutTruncated: false,
499
- stderrTruncated: false,
500
- stdoutInvalidUtf8: false,
501
- stderrInvalidUtf8: false,
502
- }),
503
- );
504
-
505
- expect(missingExitCodeError).toMatchObject({
506
- _tag: "VcsProcessMissingExitCodeError",
507
- operation: baseInput.operation,
508
- command: baseInput.command,
509
- cwd: baseInput.cwd,
510
- argumentCount: baseInput.args.length,
511
- });
512
- expect(missingExitCodeError).not.toHaveProperty("cause");
513
- }),
514
- );
515
-
437
it.effect("truncates output and appends the marker when requested", () =>
438
Effect.gen(function* () {
439
const result = yield* run({
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
-22
@@ -1,7 +1,6 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import { assert, it, describe } from "@effect/vitest";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
-import * as Cause from "effect/Cause";
4
import * as Deferred from "effect/Deferred";
5
import * as DateTime from "effect/DateTime";
6
import * as Duration from "effect/Duration";
@@ -506,27 +505,6 @@ describe("VcsStatusBroadcaster", () => {
505
}).pipe(Effect.provide(layerTestFor(state)));
506
});
507
509
- it("summarizes refresh causes without exposing nested failure details", () => {
510
- const nestedCause = new Error("private nested failure detail");
511
- const failure = new GitManagerError({
512
- operation: "VcsStatusBroadcaster.remoteStatus",
513
- cwd: "/private/user/workspace/repo",
514
- detail: "private Git failure detail",
515
- cause: nestedCause,
516
- });
517
- const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
518
-
519
- assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
520
- reasonCount: 2,
521
- failureCount: 1,
522
- failureTags: ["GitManagerError"],
523
- failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
524
- defectCount: 1,
525
- defectTags: ["TypeError"],
526
- interruptionCount: 0,
527
- });
528
- });
529
-
508
it.effect("releases remote demand while passive observers remain", () => {
509
const state = {
510
currentLocalStatus: baseLocalStatus,
apps/server/src/vcs/VcsStatusBroadcaster.ts
+1
-1
@@ -86,7 +86,7 @@ function addUniqueDiagnosticValue(values: Array<string>, value: string | undefin
86
}
87
}
88
89
-export function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
89
+function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
90
const failureTags: Array<string> = [];
91
const failureOperations: Array<string> = [];
92
const defectTags: Array<string> = [];
apps/server/src/workspace/WorkspaceEntries.test.ts
-20
@@ -548,26 +548,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
548
}),
549
);
550
551
- it.effect("preserves invalid regex errors during case-insensitive searches", () =>
552
- Effect.gen(function* () {
553
- const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" });
554
- yield* writeTextFile(cwd, "src/shapes.ts", "foobar\n");
555
-
556
- const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
557
- const result = yield* workspaceEntries.searchContents({
558
- cwd,
559
- query: "foo)bar(",
560
- limit: 100,
561
- caseSensitive: false,
562
- wholeWord: false,
563
- useRegex: true,
564
- });
565
-
566
- expect(result.regexFallbackError).toBeDefined();
567
- expect(result.matches).toEqual([]);
568
- }),
569
- );
570
-
551
it.effect("maps multi-byte lines to string-indexed ranges", () =>
552
Effect.gen(function* () {
553
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
apps/server/src/workspace/WorkspacePaths.test.ts
-34
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
4
import * as FileSystem from "effect/FileSystem";
5
import * as Layer from "effect/Layer";
6
import * as Path from "effect/Path";
7
-import * as PlatformError from "effect/PlatformError";
7
8
import * as WorkspacePaths from "./WorkspacePaths.ts";
9
@@ -39,39 +38,6 @@ it.layer(layerTest)("WorkspacePathsLive", (it) => {
38
expect(stat.type).toBe("Directory");
39
}),
40
);
42
-
43
- it.effect("preserves non-NotFound stat failures while validating the root", () =>
44
- Effect.gen(function* () {
45
- const fileSystem = yield* FileSystem.FileSystem;
46
- const workspacePaths = yield* WorkspacePaths.make.pipe(
47
- Effect.provideService(FileSystem.FileSystem, {
48
- ...fileSystem,
49
- stat: (path) =>
50
- Effect.fail(
51
- PlatformError.systemError({
52
- _tag: "PermissionDenied",
53
- module: "FileSystem",
54
- method: "stat",
55
- pathOrDescriptor: String(path),
56
- description: "Test PermissionDenied stat failure.",
57
- }),
58
- ),
59
- }),
60
- );
61
- const path = yield* Path.Path;
62
- const workspaceRoot = " ./permission-denied ";
63
- const normalizedWorkspaceRoot = path.resolve(workspaceRoot.trim());
64
-
65
- const error = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(Effect.flip);
66
-
67
- expect(error).toBeInstanceOf(WorkspacePaths.WorkspaceRootStatFailedError);
68
- expect(error).toMatchObject({
69
- workspaceRoot,
70
- normalizedWorkspaceRoot,
71
- phase: "validate-existing",
72
- });
73
- }),
74
- );
41
});
42
43
describe("resolveRelativePathWithinRoot", () => {
apps/server/src/workspace/WorkspacePaths.ts
+1
-1
@@ -107,7 +107,7 @@ function toPosixRelativePath(input: string): string {
107
return input.replaceAll("\\", "/");
108
}
109
110
-export const make = Effect.gen(function* () {
110
+const make = Effect.gen(function* () {
111
const fileSystem = yield* FileSystem.FileSystem;
112
const path = yield* Path.Path;
113
apps/server/src/workspace/WorkspaceSearchIndex.test.ts
-65
@@ -63,71 +63,6 @@ it.effect("filters image searches before applying the result limit", () =>
63
),
64
);
65
66
-it.effect("preserves search and refresh failures with operation context", () =>
67
- Effect.scoped(
68
- Effect.gen(function* () {
69
- const searchCause = new Error("native search failed");
70
- const refreshCause = new Error("native scan failed");
71
- const contentSearchCause = new Error("native grep failed");
72
- const finder = {
73
- destroy: vi.fn(),
74
- waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
75
- mixedSearch: vi.fn(() => {
76
- throw searchCause;
77
- }),
78
- grep: vi.fn(() => {
79
- throw contentSearchCause;
80
- }),
81
- scanFiles: vi.fn(() => {
82
- throw refreshCause;
83
- }),
84
- } as unknown as FileFinder;
85
- vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
86
-
87
- const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
88
- const query = "authorization: Bearer secret-token";
89
- const searchError = yield* Effect.flip(searchIndex.search(query, 3));
90
- const contentSearchError = yield* Effect.flip(
91
- searchIndex.searchContents({
92
- query,
93
- limit: 3,
94
- caseSensitive: false,
95
- wholeWord: false,
96
- useRegex: false,
97
- }),
98
- );
99
- const refreshError = yield* Effect.flip(searchIndex.refresh());
100
-
101
- expect(searchError).toMatchObject({
102
- _tag: "WorkspaceSearchIndexSearchFailed",
103
- cwd: "/workspace/project",
104
- queryLength: query.length,
105
- pageSize: 4,
106
- reason: "FileFinder.mixedSearch threw unexpectedly.",
107
- cause: searchCause,
108
- });
109
- expect(searchError).not.toHaveProperty("query");
110
- expect(searchError.message).not.toMatch(/Bearer|secret-token/);
111
- expect(contentSearchError).toMatchObject({
112
- _tag: "WorkspaceSearchIndexSearchFailed",
113
- cwd: "/workspace/project",
114
- queryLength: query.length,
115
- pageSize: 3,
116
- reason: "FileFinder.grep threw unexpectedly.",
117
- cause: contentSearchCause,
118
- });
119
- expect(contentSearchError).not.toHaveProperty("query");
120
- expect(contentSearchError.message).not.toMatch(/Bearer|secret-token/);
121
- expect(refreshError).toMatchObject({
122
- _tag: "WorkspaceSearchIndexRefreshFailed",
123
- cwd: "/workspace/project",
124
- reason: "FileFinder.scanFiles threw unexpectedly.",
125
- cause: refreshCause,
126
- });
127
- }),
128
- ),
129
-);
130
-
66
it.effect("continues whole-word searches after a filtered grep page", () =>
67
Effect.scoped(
68
Effect.gen(function* () {