Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge ce5a9bbd15 Stabilize discovered SSH host row callback
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:12:39 +00:00
Julius MarmingeandJulius Marminge 3c32bc8fd1 [codex] Fix hosted channel bootstrap (#2613)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:57:16 -07:00
Julius MarmingeandJulius Marminge 6efdf67e15 [codex] Fix Vercel Turbo env forwarding (#2612)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:09:40 -07:00
Julius MarmingeandJulius Marminge 39371c6012 [codex] Fix Vercel release web deploy scope (#2611)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:01:57 -07:00
Kainoa NewtonandJulius Marminge 99efaa0faa Collapse long user messages by default (#2180)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 02:00:03 +00:00
Julius Marminge 6b9feb1bd3 Update deployment command in release workflow (#2610) 2026-05-08 18:30:44 -07:00
Ben Vargas e0f3abd1a4 Fix remote pairing CORS responses (#2594) 2026-05-08 23:52:47 +00:00
34ec8a86fb [codex] add configurable automatic git fetch interval (#2605)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-08 16:41:55 -07:00
932df4ed17 fix(ssh): fix reconnect issues and node binary path resolution (#2504)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-08 16:17:29 -07:00
Julius MarmingeandCursor Agent 63859aa072 perf: Add archived shell snapshot support (#2593)
Co-authored-by: Cursor Agent <[email protected]>
2026-05-08 15:49:41 -07:00
Julius MarmingeandJulius Marminge 7bfacd55d8 [codex] Handle NuGet provider bootstrap failures (#2608)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 15:20:02 -07:00
74 changed files with 2499 additions and 479 deletions

No files matched your search

+15 -11
View File
@@ -272,11 +272,16 @@ jobs:
exit 0
}
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser
try {
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser `
-ErrorAction Stop
} catch {
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
}
Install-Module `
-Name TrustedSigning `
@@ -284,7 +289,8 @@ jobs:
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
@@ -628,14 +634,12 @@ jobs:
channel_name="nightly"
fi
vercel_scope_args=()
if [[ -n "${VERCEL_TEAM_SLUG:-}" ]]; then
vercel_scope_args=(--scope "$VERCEL_TEAM_SLUG")
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
vercel_scope_args=(--scope "$vercel_scope")
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
bunx [email protected] deploy apps/web \
bunx [email protected] deploy \
--prod \
--skip-domain \
--yes \
+37
View File
@@ -115,6 +115,43 @@ After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
#### SSH Launch Troubleshooting
The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.
The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:
```text
^22.16 || ^23.11 || >=24.10
```
During SSH launch, T3 Code first checks whether `node` is already available on `PATH`. If it is missing, the launcher tries common non-interactive shell locations and version-manager shims/activation hooks:
- `~/.local/bin`, `~/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/bin`
- Volta via `~/.volta/bin`
- asdf via `~/.asdf/shims`, `~/.asdf/bin`, or `~/.asdf/asdf.sh`
- mise via `~/.local/share/mise/shims`, `~/.mise/shims`, or `mise activate sh`
- fnm via `fnm env --use-on-cd --shell sh` or `fnm env --shell sh`
- nodenv via `~/.nodenv/bin`, `~/.nodenv/shims`, or `nodenv init -`
- nvm via `$NVM_DIR/nvm.sh`, then `nvm use default`, `nvm use node`, or `nvm use --lts`
- installed nvm versions under `$NVM_DIR/versions/node/*/bin`
If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:
```bash
ssh [email protected] 'sh -lc "command -v node && node --version"'
```
If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:
```bash
nvm alias default 24
```
With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and points at a Node version satisfying the range above.
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
## How Pairing Works
The remote device does not need a long-lived secret up front.
+6 -1
View File
@@ -11,6 +11,7 @@ import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
@@ -65,7 +66,10 @@ const resolveDesktopSshCliRunner = (
): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
return { nodeScriptPath: devRemoteEntryPath };
return {
nodeScriptPath: devRemoteEntryPath,
nodeEngineRange: serverPackageJson.engines.node,
};
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
@@ -73,6 +77,7 @@ const resolveDesktopSshCliRunner = (
updateChannel: settings.updateChannel,
isDevelopment: environment.isDevelopment,
}),
nodeEngineRange: serverPackageJson.engines.node,
};
};
+12 -3
View File
@@ -14,6 +14,7 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstab
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
import { deriveAuthClientMetadata } from "./utils.ts";
import { browserApiCorsHeaders } from "../httpCors.ts";
export const respondToAuthError = (error: AuthError) =>
Effect.gen(function* () {
@@ -27,7 +28,7 @@ export const respondToAuthError = (error: AuthError) =>
{
error: error.message,
},
{ status: error.status ?? 500 },
{ status: error.status ?? 500, headers: browserApiCorsHeaders },
);
});
@@ -38,7 +39,10 @@ export const authSessionRouteLayer = HttpRouter.add(
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
const session = yield* serverAuth.getSessionState(request);
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
return HttpServerResponse.jsonUnsafe(session, {
status: 200,
headers: browserApiCorsHeaders,
});
}),
);
@@ -81,7 +85,10 @@ export const authBootstrapRouteLayer = HttpRouter.add(
deriveAuthClientMetadata({ request }),
);
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
return yield* HttpServerResponse.jsonUnsafe(result.response, {
status: 200,
headers: browserApiCorsHeaders,
}).pipe(
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
expires: DateTime.toDate(result.response.expiresAt),
httpOnly: true,
@@ -114,6 +121,7 @@ export const authBearerBootstrapRouteLayer = HttpRouter.add(
);
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -128,6 +136,7 @@ export const authWebSocketTokenRouteLayer = HttpRouter.add(
const result = yield* serverAuth.issueWebSocketToken(session);
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -94,6 +94,8 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -174,6 +176,8 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -222,6 +226,8 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+11 -3
View File
@@ -28,6 +28,11 @@ import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolve
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import { respondToAuthError } from "./auth/http.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import {
browserApiCorsAllowedHeaders,
browserApiCorsAllowedMethods,
browserApiCorsHeaders,
} from "./httpCors.ts";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
@@ -35,8 +40,8 @@ const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
export const browserApiCorsLayer = HttpRouter.cors({
allowedMethods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
allowedMethods: [...browserApiCorsAllowedMethods],
allowedHeaders: [...browserApiCorsAllowedHeaders],
maxAge: 600,
});
@@ -69,7 +74,10 @@ export const serverEnvironmentRouteLayer = HttpRouter.add(
const descriptor = yield* Effect.service(ServerEnvironment).pipe(
Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
);
return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
return HttpServerResponse.jsonUnsafe(descriptor, {
status: 200,
headers: browserApiCorsHeaders,
});
}),
);
+13
View File
@@ -0,0 +1,13 @@
export const browserApiCorsAllowedMethods = ["GET", "POST", "OPTIONS"] as const;
export const browserApiCorsAllowedHeaders = [
"authorization",
"b3",
"traceparent",
"content-type",
] as const;
export const browserApiCorsHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": browserApiCorsAllowedMethods.join(", "),
"access-control-allow-headers": browserApiCorsAllowedHeaders.join(", "),
} as const;
@@ -183,6 +183,13 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: projectionSnapshot.snapshotSequence,
projects: [],
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
@@ -441,6 +441,126 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect("keeps archived threads out of the main shell snapshot", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-archive-test',
'Archive Test',
'/tmp/archive-test',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-06T00:00:00.000Z',
'2026-04-06T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-active',
'project-archive-test',
'Active Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:02.000Z',
'2026-04-06T00:00:03.000Z',
NULL,
NULL
),
(
'thread-archived',
'project-archive-test',
'Archived Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:04.000Z',
'2026-04-06T00:00:05.000Z',
'2026-04-06T00:00:06.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
`;
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(
shellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-active")],
);
const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();
assert.deepEqual(
archivedShellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-archived")],
);
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
@@ -327,6 +327,66 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
ORDER BY project_id ASC, created_at ASC, thread_id ASC
`,
});
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NOT NULL
ORDER BY project_id ASC, archived_at DESC, thread_id DESC
`,
});
const listThreadMessageRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadMessageDbRowSchema,
@@ -411,6 +471,56 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
ORDER BY sessions.thread_id ASC
`,
});
const listArchivedThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
ORDER BY sessions.thread_id ASC
`,
});
const listCheckpointRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionCheckpointDbRowSchema,
@@ -475,6 +585,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
});
const listArchivedLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
turns.thread_id AS "threadId",
turns.turn_id AS "turnId",
turns.state,
turns.requested_at AS "requestedAt",
turns.started_at AS "startedAt",
turns.completed_at AS "completedAt",
turns.assistant_message_id AS "assistantMessageId",
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
turns.source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_threads threads
JOIN projection_turns turns
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
@@ -557,6 +694,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
AND archived_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
@@ -607,6 +745,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE thread_id = ${threadId}
AND deleted_at IS NULL
AND archived_at IS NULL
LIMIT 1
`,
});
@@ -717,6 +856,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
AND turns.turn_id = threads.latest_turn_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
AND threads.archived_at IS NULL
LIMIT 1
`,
});
@@ -1232,7 +1372,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadRows(undefined).pipe(
listActiveThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
@@ -1240,7 +1380,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadSessionRows(undefined).pipe(
listActiveThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
@@ -1350,6 +1490,139 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getArchivedShellSnapshot: ProjectionSnapshotQueryShape["getArchivedShellSnapshot"] = () =>
sql
.withTransaction(
Effect.all([
listProjectRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:decodeRows",
),
),
),
listArchivedThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:decodeRows",
),
),
),
listArchivedThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:decodeRows",
),
),
),
listArchivedLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:decodeRows",
),
),
),
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const activeProjectIds = new Set(threadRows.map((row) => row.projectId));
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => activeProjectIds.has(row.projectId)),
);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: projectRows
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
.map((row) =>
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
),
threads: threadRows.map(
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot",
),
),
);
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
return error;
}
return toPersistenceSqlError("ProjectionSnapshotQuery.getArchivedShellSnapshot:query")(
error,
);
}),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
@@ -1683,6 +1956,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getCommandReadModel,
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
@@ -72,6 +72,17 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read archived thread shell summaries for the archive page.
*
* This query is separate from the main shell snapshot so archived threads
* are never bootstrapped into normal navigation state.
*/
readonly getArchivedShellSnapshot: () => Effect.Effect<
OrchestrationShellSnapshot,
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -42,6 +42,7 @@ import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -83,6 +84,7 @@ export const migrationEntries = [
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_active
ON projection_threads(deleted_at, archived_at, project_id, created_at, thread_id)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_archived
ON projection_threads(deleted_at, archived_at, project_id, thread_id)
`;
});
@@ -25,6 +25,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
@@ -18,6 +18,7 @@ import {
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
@@ -36,7 +37,6 @@ import {
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
@@ -180,7 +180,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
@@ -10,6 +10,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
buildServerProvider,
nonEmptyTrimmed,
@@ -17,7 +18,6 @@ import {
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
@@ -383,7 +383,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
@@ -27,6 +27,7 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import { createModelCapabilities } from "@t3tools/shared/model";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
@@ -48,6 +49,8 @@ import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.t
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
@@ -256,7 +259,8 @@ function makeMutableServerSettingsService(
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = decodeServerSettings(deepMerge(current, patch));
const next = applyServerSettingsPatch(current, patch);
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
@@ -930,7 +934,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const missingBinary = `t3code_codex_missing_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
// Disable every built-in probe that would otherwise spawn
// on the CI host. `enabled: false` short-circuits each
@@ -1029,7 +1033,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const secondMissing = `t3code_codex_second_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
@@ -1124,7 +1128,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: { enabled: false },
claudeAgent: { enabled: false },
@@ -1180,7 +1184,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: {
enabled: false,
@@ -194,6 +194,7 @@ describe("ProviderSessionReaper", () => {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
@@ -1,17 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
describe("cliVersion", () => {
it("normalizes versions with a missing patch segment", () => {
assert.strictEqual(normalizeCliVersion("2.1"), "2.1.0");
});
it("compares prerelease versions before stable versions", () => {
assert.isTrue(compareCliVersions("2.1.111-beta.1", "2.1.111") < 0);
});
it("rejects malformed numeric segments", () => {
assert.isTrue(compareCliVersions("1.2.3abc", "1.2.10") > 0);
});
});
-123
View File
@@ -1,123 +0,0 @@
interface ParsedCliSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
const CLI_VERSION_NUMBER_SEGMENT = /^\d+$/;
export function normalizeCliVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
function parseCliSemver(version: string): ParsedCliSemver | null {
const normalized = normalizeCliVersion(version);
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
if (
!CLI_VERSION_NUMBER_SEGMENT.test(majorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(minorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(patchSegment)
) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = /^\d+$/.test(left);
const rightNumeric = /^\d+$/.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareCliVersions(left: string, right: string): number {
const parsedLeft = parseCliSemver(left);
const parsedRight = parseCliSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
@@ -3,6 +3,7 @@ import {
type ServerProvider,
type ServerProviderVersionAdvisory,
} from "@t3tools/contracts";
import { compareSemverVersions } from "@t3tools/shared/semver";
import { resolveCommandPath } from "@t3tools/shared/shell";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -11,8 +12,6 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { compareCliVersions } from "./cliVersion.ts";
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
const LATEST_VERSION_TIMEOUT_MS = 4_000;
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
@@ -365,7 +364,7 @@ function deriveVersionAdvisory(input: {
if (!input.latestVersion) {
return { status: "unknown", message: null };
}
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
return {
status: "behind_latest",
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
+112 -16
View File
@@ -630,6 +630,13 @@ const buildAppUnderTest = (options?: {
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getProjectShellById: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
@@ -795,7 +802,12 @@ const bootstrapBrowserSession = (
};
});
const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
const bootstrapBearerSession = (
credential = defaultDesktopBootstrapToken,
options?: {
readonly headers?: Record<string, string>;
},
) =>
Effect.gen(function* () {
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
const response = yield* Effect.promise(() =>
@@ -803,6 +815,7 @@ const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
method: "POST",
headers: {
"content-type": "application/json",
...options?.headers,
},
body: JSON.stringify({
credential,
@@ -878,6 +891,22 @@ const splitHeaderTokens = (value: string | null) =>
.filter((token) => token.length > 0)
.toSorted();
const assertBrowserApiCorsHeaders = (headers: Headers) => {
assert.equal(headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
};
const crossOriginClientOrigin = "http://remote-client.test:3773";
const getWsServerUrl = (
pathname = "",
options?: { authenticated?: boolean; credential?: string },
@@ -999,6 +1028,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on public environment descriptor responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
const response = yield* Effect.promise(() =>
fetch(url, {
headers: {
origin: crossOriginClientOrigin,
},
}),
);
const body = (yield* Effect.promise(() =>
response.json(),
)) as typeof testEnvironmentDescriptor;
assert.equal(response.status, 200);
assertBrowserApiCorsHeaders(response.headers);
assert.deepEqual(body, testEnvironmentDescriptor);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("reports unauthenticated session state without requiring auth", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -1122,6 +1173,62 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on remote auth success responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const origin = crossOriginClientOrigin;
const { response: bootstrapResponse, body: bootstrapBody } = yield* bootstrapBearerSession(
defaultDesktopBootstrapToken,
{
headers: { origin },
},
);
assert.equal(bootstrapResponse.status, 200);
assertBrowserApiCorsHeaders(bootstrapResponse.headers);
assert.equal(bootstrapBody.authenticated, true);
assert.equal(typeof bootstrapBody.sessionToken, "string");
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const sessionResponse = yield* Effect.promise(() =>
fetch(sessionUrl, {
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
readonly authenticated: boolean;
readonly sessionMethod?: string;
};
assert.equal(sessionResponse.status, 200);
assertBrowserApiCorsHeaders(sessionResponse.headers);
assert.equal(sessionBody.authenticated, true);
assert.equal(sessionBody.sessionMethod, "bearer-session-token");
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
const wsTokenResponse = yield* Effect.promise(() =>
fetch(wsTokenUrl, {
method: "POST",
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
readonly token: string;
};
assert.equal(wsTokenResponse.status, 200);
assertBrowserApiCorsHeaders(wsTokenResponse.headers);
assert.equal(typeof wsTokenBody.token, "string");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"responds to remote auth websocket-token preflight requests with authorization CORS headers",
() =>
@@ -1133,7 +1240,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "OPTIONS",
headers: {
origin: "http://192.168.86.35:3773",
origin: crossOriginClientOrigin,
"access-control-request-method": "POST",
"access-control-request-headers": "authorization",
},
@@ -1141,18 +1248,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(response.status, 204);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
assertBrowserApiCorsHeaders(response.headers);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -1165,7 +1261,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "POST",
headers: {
origin: "http://192.168.86.35:3773",
origin: crossOriginClientOrigin,
},
}),
);
@@ -1174,7 +1270,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
};
assert.equal(response.status, 401);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assertBrowserApiCorsHeaders(response.headers);
assert.equal(body.error, "Authentication required.");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -85,6 +85,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
@@ -139,6 +140,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () =>
@@ -191,6 +193,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+3
View File
@@ -9,6 +9,7 @@ import {
import { createModelSelection } from "@t3tools/shared/model";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -437,6 +438,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: Duration.seconds(10),
});
assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
@@ -458,6 +460,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: 10_000,
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
+58 -46
View File
@@ -45,15 +45,33 @@ import * as Semaphore from "effect/Semaphore";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { ServerConfig } from "./config.ts";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";
const decodeServerSettings = Schema.decodeEffect(ServerSettings);
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const normalizeServerSettings = (
settings: ServerSettings,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
encodeServerSettings(settings).pipe(
Effect.flatMap(decodeServerSettings),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
function providerEnvironmentSecretName(input: {
readonly instanceId: string;
readonly name: string;
@@ -117,9 +135,15 @@ export class ServerSettingsService extends Context.Service<
Layer.effect(
ServerSettingsService,
Effect.gen(function* () {
const currentSettingsRef = yield* Ref.make<ServerSettings>(
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
);
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
const initialSettings = yield* normalizeServerSettings({
...merged,
...(automaticGitFetchInterval !== undefined
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
return {
start: Effect.void,
@@ -127,18 +151,8 @@ export class ServerSettingsService extends Context.Service<
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.flatMap((currentSettings) =>
decodeServerSettings(applyServerSettingsPatch(currentSettings, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
),
),
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
Effect.flatMap(normalizeServerSettings),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
@@ -200,7 +214,10 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"automaticGitFetchInterval",
"textGenerationModelSelection",
]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
@@ -430,25 +447,29 @@ const makeServerSettings = Effect.gen(function* () {
};
});
const writeSettingsAtomically = (settings: ServerSettings) => {
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
const sparseSettingsJson = yield* encodeServerSettingsJson(
stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
);
return writeFileStringAtomically({
filePath: settingsPath,
contents: `${JSON.stringify(sparseSettings, null, 2)}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
};
return yield* writeFileStringAtomically({
filePath: settingsPath,
contents: `${sparseSettingsJson}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
);
},
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
const revalidateAndEmit = writeSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -533,16 +554,7 @@ const makeServerSettings = Effect.gen(function* () {
current,
applyServerSettingsPatch(current, patch),
);
const next = yield* decodeServerSettings(nextPersisted).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
const next = yield* normalizeServerSettings(nextPersisted);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
@@ -6,6 +6,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "@t3tools/contracts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
@@ -16,7 +17,6 @@ import {
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -13,6 +13,7 @@ import {
} from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { ServerConfig } from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
@@ -24,7 +25,6 @@ import {
} from "./TextGenerationPrompts.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -1,6 +1,6 @@
import { TextGenerationError } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { TextGenerationError } from "@t3tools/contracts";
const isTextGenerationError = Schema.is(TextGenerationError);
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
@@ -19,54 +19,6 @@ export function limitSection(value: string, maxChars: number): string {
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
@@ -130,6 +130,65 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("disables SSH askpass for background upstream status fetches", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const tempDir = yield* makeTmpDir("git-vcs-driver-ssh-env-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const sshLogPath = pathService.join(tempDir, "ssh-env.txt");
const sshWrapperPath = pathService.join(tempDir, "ssh-wrapper.sh");
const previousGitSsh = process.env.GIT_SSH;
const previousAskpassRequire = process.env.SSH_ASKPASS_REQUIRE;
const previousAskpassLog = process.env.T3_TEST_SSH_ASKPASS_LOG;
yield* fileSystem.writeFileString(
sshWrapperPath,
[
"#!/bin/sh",
'printf "%s\\n" "${SSH_ASKPASS_REQUIRE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
"exit 1",
"",
].join("\n"),
);
yield* fileSystem.chmod(sshWrapperPath, 0o755);
yield* git(cwd, ["remote", "add", "origin", "ssh://example.invalid/repo.git"]);
yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]);
yield* git(cwd, ["branch", "--set-upstream-to", `origin/${initialBranch}`]);
yield* Effect.gen(function* () {
process.env.GIT_SSH = sshWrapperPath;
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal((yield* fileSystem.readFileString(sshLogPath)).trim(), "never");
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousGitSsh === undefined) {
delete process.env.GIT_SSH;
} else {
process.env.GIT_SSH = previousGitSsh;
}
if (previousAskpassRequire === undefined) {
delete process.env.SSH_ASKPASS_REQUIRE;
} else {
process.env.SSH_ASKPASS_REQUIRE = previousAskpassRequire;
}
if (previousAskpassLog === undefined) {
delete process.env.T3_TEST_SSH_ASKPASS_LOG;
} else {
process.env.T3_TEST_SSH_ASKPASS_LOG = previousAskpassLog;
}
}),
),
);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+6
View File
@@ -41,6 +41,9 @@ const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
SSH_ASKPASS_REQUIRE: "never",
} satisfies NodeJS.ProcessEnv);
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetails>({
@@ -72,6 +75,7 @@ interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
env?: NodeJS.ProcessEnv | undefined;
maxOutputBytes?: number | undefined;
truncateOutputAtMaxBytes?: boolean | undefined;
progress?: GitVcsDriver.ExecuteGitProgress | undefined;
@@ -738,6 +742,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
cwd,
args,
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options.env !== undefined ? { env: options.env } : {}),
allowNonZeroExit: true,
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
@@ -870,6 +875,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
{
allowNonZeroExit: true,
env: STATUS_UPSTREAM_REFRESH_ENV,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
},
).pipe(Effect.asVoid);
@@ -1,6 +1,7 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -284,6 +285,31 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("does not start automatic remote refreshes when disabled", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const snapshot = yield* Stream.runHead(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
);
assert.isTrue(Option.isSome(snapshot));
assert.equal(state.remoteStatusCalls, 0);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
+32 -9
View File
@@ -22,7 +22,7 @@ import { mergeGitStatusParts } from "@t3tools/shared/git";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface VcsStatusChange {
readonly cwd: string;
@@ -44,6 +44,10 @@ interface ActiveRemotePoller {
readonly subscriberCount: number;
}
interface StreamStatusOptions {
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
}
export interface VcsStatusBroadcasterShape {
readonly getStatus: (
input: VcsStatusInput,
@@ -54,6 +58,7 @@ export interface VcsStatusBroadcasterShape {
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: VcsStatusInput,
options?: StreamStatusOptions,
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
}
@@ -232,19 +237,32 @@ export const layer = Layer.effect(
return mergeGitStatusParts(local, remote);
});
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
const makeRemoteRefreshLoop = (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
) => {
const logRefreshFailure = (error: GitManagerServiceError) =>
Effect.logWarning("VCS remote status refresh failed", {
cwd,
detail: error.message,
});
const refreshRemoteStatusIfEnabled = automaticRemoteRefreshInterval.pipe(
Effect.flatMap((interval) =>
Duration.isZero(interval) ? Effect.void : refreshRemoteStatus(cwd).pipe(Effect.asVoid),
),
);
const sleepForConfiguredInterval = automaticRemoteRefreshInterval.pipe(
Effect.flatMap((interval) =>
Effect.sleep(Duration.isZero(interval) ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL : interval),
),
);
return refreshRemoteStatus(cwd).pipe(
return refreshRemoteStatusIfEnabled.pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(VCS_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
sleepForConfiguredInterval.pipe(
Effect.andThen(refreshRemoteStatusIfEnabled.pipe(Effect.catch(logRefreshFailure))),
),
),
),
@@ -253,6 +271,7 @@ export const layer = Layer.effect(
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
@@ -265,7 +284,7 @@ export const layer = Layer.effect(
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
@@ -307,14 +326,18 @@ export const layer = Layer.effect(
}
});
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input, options) =>
Stream.unwrap(
Effect.gen(function* () {
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
yield* retainRemotePoller(cwd);
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
+41 -1
View File
@@ -9,6 +9,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
type AuthAccessStreamEvent,
AuthSessionId,
CommandId,
@@ -180,6 +181,14 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
const serverEnvironment = yield* ServerEnvironment;
const serverAuth = yield* ServerAuth;
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.automaticGitFetchInterval),
Effect.catch((cause) =>
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
detail: cause.message,
}).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
),
);
const sourceControlRepositories = yield* SourceControlRepositoryService;
const bootstrapCredentials = yield* BootstrapCredentialService;
const sessions = yield* SessionCredentialService;
@@ -308,6 +317,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
);
case "thread.deleted":
case "thread.archived":
return Effect.succeed(
Option.some({
kind: "thread-removed" as const,
@@ -315,6 +325,17 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
threadId: event.payload.threadId,
}),
);
case "thread.unarchived":
return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe(
Effect.map((thread) =>
Option.map(thread, (nextThread) => ({
kind: "thread-upserted" as const,
sequence: event.sequence,
thread: nextThread,
})),
),
Effect.catch(() => Effect.succeed(Option.none())),
);
default:
if (event.aggregateKind !== "thread") {
return Effect.succeed(Option.none());
@@ -734,6 +755,23 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
projectionSnapshotQuery.getArchivedShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration archived shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load archived orchestration shell snapshot",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
@@ -952,7 +990,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
[WS_METHODS.subscribeVcsStatus]: (input) =>
observeRpcStream(
WS_METHODS.subscribeVcsStatus,
vcsStatusBroadcaster.streamStatus(input),
vcsStatusBroadcaster.streamStatus(input, {
automaticRemoteRefreshInterval: automaticGitFetchInterval,
}),
{
"rpc.aggregate": "vcs",
},
+8 -2
View File
@@ -18,11 +18,13 @@ import {
WS_METHODS,
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
ServerConfig as ServerConfigSchema,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
import { page } from "vitest/browser";
@@ -106,6 +108,7 @@ const rpcHarness = new BrowserWsRpcHarness();
const wsRequests = rpcHarness.requests;
let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
const encodeServerConfig = Schema.encodeSync(ServerConfigSchema);
interface ViewportSpec {
name: string;
@@ -218,6 +221,9 @@ function createMockEnvironmentApi(input: {
getFullThreadDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getFullThreadDiff"],
getArchivedShellSnapshot: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getArchivedShellSnapshot"],
subscribeShell: (() => () => undefined) as EnvironmentApi["orchestration"]["subscribeShell"],
subscribeThread: (() => () =>
undefined) as EnvironmentApi["orchestration"]["subscribeThread"],
@@ -952,7 +958,7 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
}
const tag = body._tag;
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
return encodeServerConfig(fixture.serverConfig);
}
if (tag === WS_METHODS.serverDiscoverSourceControl) {
return {
@@ -1659,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{
version: 1,
type: "snapshot",
config: fixture.serverConfig,
config: encodeServerConfig(fixture.serverConfig),
},
];
}
@@ -11,12 +11,15 @@ import {
ProviderInstanceId,
type ServerConfig,
type ServerLifecycleWelcomePayload,
ServerConfig as ServerConfigSchema,
ServerSettings,
type ThreadId,
WS_METHODS,
} from "@t3tools/contracts";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { ws, http, HttpResponse } from "msw";
import { setupWorker } from "msw/browser";
import * as Schema from "effect/Schema";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
@@ -50,6 +53,8 @@ interface TestFixture {
let fixture: TestFixture;
const rpcHarness = new BrowserWsRpcHarness();
const encodeServerConfig = Schema.encodeSync(ServerConfigSchema);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const wsLink = ws.link(/ws(s)?:\/\/.*/);
@@ -254,7 +259,7 @@ function buildFixture(): TestFixture {
function resolveWsRpc(tag: string): unknown {
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
return encodeServerConfig(fixture.serverConfig);
}
if (tag === WS_METHODS.vcsListRefs) {
return {
@@ -394,7 +399,7 @@ async function waitForServerConfigStreamReady(): Promise<void> {
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
version: 1,
type: "settingsUpdated",
payload: { settings: fixture.serverConfig.settings },
payload: { settings: encodeServerSettings(fixture.serverConfig.settings) },
});
try {
@@ -485,7 +490,7 @@ describe("Keybindings update toast", () => {
{
version: 1,
type: "snapshot",
config: fixture.serverConfig,
config: encodeServerConfig(fixture.serverConfig),
},
];
}
@@ -48,6 +48,8 @@ vi.mock("@legendapp/list/react", async () => {
import { MessagesTimeline } from "./MessagesTimeline";
const MESSAGE_CREATED_AT = "2026-04-13T12:00:00.000Z";
function buildProps() {
return {
isWorking: false,
@@ -73,6 +75,27 @@ function buildProps() {
};
}
function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
return Array.from({ length: 9 }, (_, index) =>
index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
).join("\n");
}
function buildUserTimelineEntry(text: string) {
return {
id: "entry-1",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: "message-1" as never,
role: "user" as const,
text,
createdAt: MESSAGE_CREATED_AT,
streaming: false,
},
};
}
describe("MessagesTimeline", () => {
afterEach(() => {
scrollToEndSpy.mockReset();
@@ -157,4 +180,87 @@ describe("MessagesTimeline", () => {
await screen.unmount();
}
});
it("starts long user messages collapsed by default", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
try {
const toggle = page.getByRole("button", { name: "Show full message" });
await expect.element(toggle).toBeVisible();
await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
const messageBody = document.querySelector(
"[data-user-message-body='true']",
) as HTMLDivElement | null;
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
expect(messageBody?.className).toContain("max-h-44");
expect(messageBody?.className).toContain("overflow-hidden");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true");
expect(messageBody?.style.maskImage).toContain("linear-gradient");
} finally {
await screen.unmount();
}
});
it("expands and re-collapses long user messages from the toggle", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
try {
const expandButton = page.getByRole("button", { name: "Show full message" });
await expect.element(expandButton).toBeVisible();
expect(document.body.textContent ?? "").toContain("deep hidden detail only after expand");
await expandButton.click();
const collapseButton = page.getByRole("button", { name: "Show less" });
await expect.element(collapseButton).toBeVisible();
await expect.element(collapseButton).toHaveAttribute("aria-expanded", "true");
let messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("false");
expect(messageBody?.className).not.toContain("max-h-44");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("false");
expect((messageBody as HTMLDivElement | null)?.style.maskImage ?? "").toBe("");
await collapseButton.click();
await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible();
messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
expect(messageBody?.className).toContain("max-h-44");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true");
expect((messageBody as HTMLDivElement | null)?.style.maskImage).toContain("linear-gradient");
} finally {
await screen.unmount();
}
});
it("starts the newest long user prompt collapsed", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText("latest long prompt"))]}
/>,
);
try {
await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible();
const messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
} finally {
await screen.unmount();
}
});
});
@@ -73,6 +73,7 @@ beforeAll(() => {
});
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
function buildProps() {
return {
@@ -99,33 +100,73 @@ function buildProps() {
};
}
function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
return Array.from({ length: 9 }, (_, index) =>
index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
).join("\n");
}
function buildUserTimelineEntry(text: string) {
return {
id: "entry-1",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: MessageId.make("message-1"),
role: "user" as const,
text,
createdAt: MESSAGE_CREATED_AT,
streaming: false,
},
};
}
describe("MessagesTimeline", () => {
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
expect(markup).toContain("Show full message");
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
});
it("does not render collapse controls for short user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
/>,
);
expect(markup).not.toContain("Show full message");
expect(markup).toContain('data-user-message-collapsible="false"');
});
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-2"),
role: "user",
text: [
"yoo what's @terminal-1:1-5 mean",
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
buildUserTimelineEntry(
[
buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
),
]}
/>,
);
@@ -133,8 +174,23 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
expect(markup).toContain("Show full message");
}, 20_000);
it("keeps the copy button for collapsed long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
expect(markup).toContain('aria-label="Copy link"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-footer="true"');
});
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
+100 -18
View File
@@ -365,24 +365,24 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
{(displayedUserMessage.visibleText.trim().length > 0 || terminalContexts.length > 0) && (
<UserMessageBody
text={displayedUserMessage.visibleText}
terminalContexts={terminalContexts}
skills={ctx.skills}
/>
)}
<div className="mt-1.5 flex items-center justify-end gap-2">
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} />
)}
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</div>
<CollapsibleUserMessageBody
text={displayedUserMessage.visibleText}
terminalContexts={terminalContexts}
skills={ctx.skills}
footer={
<>
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} />
)}
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</>
}
/>
</div>
</div>
);
@@ -755,6 +755,88 @@ const UserMessageTerminalContextInlineLabel = memo(
},
);
const MAX_COLLAPSED_USER_MESSAGE_LINES = 8;
const MAX_COLLAPSED_USER_MESSAGE_LENGTH = 600;
const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
function shouldCollapseUserMessage(text: string): boolean {
if (text.trim().length === 0) {
return false;
}
return (
text.length > MAX_COLLAPSED_USER_MESSAGE_LENGTH ||
text.split("\n").length > MAX_COLLAPSED_USER_MESSAGE_LINES
);
}
const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
text: string;
terminalContexts: ParsedTerminalContextEntry[];
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
footer?: ReactNode;
}) {
const [expanded, setExpanded] = useState(false);
const hasVisibleBody = props.text.trim().length > 0 || props.terminalContexts.length > 0;
const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
const isCollapsed = canCollapse && !expanded;
return (
<div>
{hasVisibleBody ? (
<div
className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
data-user-message-body="true"
data-user-message-collapsed={isCollapsed ? "true" : "false"}
data-user-message-collapsible={canCollapse ? "true" : "false"}
data-user-message-fade={isCollapsed ? "true" : "false"}
style={
isCollapsed
? {
WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
}
: undefined
}
>
<UserMessageBody
text={props.text}
terminalContexts={props.terminalContexts}
skills={props.skills}
/>
</div>
) : null}
{canCollapse || props.footer ? (
<div
className={cn(
"mt-1.5 flex items-center gap-2",
canCollapse && props.footer ? "justify-between" : "justify-end",
)}
data-user-message-footer="true"
>
{canCollapse ? (
<Button
type="button"
size="xs"
variant="ghost"
aria-expanded={expanded}
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
className="-ml-1 h-6 rounded-md px-1.5 text-xs text-muted-foreground/72 hover:bg-muted/55 hover:text-foreground/85"
>
{expanded ? "Show less" : "Show full message"}
</Button>
) : null}
{props.footer ? (
<div className="ml-auto flex items-center gap-2">{props.footer}</div>
) : null}
</div>
) : null}
</div>
);
});
const UserMessageBody = memo(function UserMessageBody(props: {
text: string;
terminalContexts: ParsedTerminalContextEntry[];
@@ -1905,6 +1905,12 @@ export function ConnectionsSettings() {
},
[savedBackendMode, savedDesktopSshEnvironmentsByAlias],
);
const connectDiscoveredSshHost = useCallback(
(target: DesktopDiscoveredSshHost) => {
void handleConnectSshHost(target);
},
[handleConnectSshHost],
);
useEffect(() => {
if (!desktopBridge || !addBackendDialogOpen || savedBackendMode !== "ssh") {
@@ -2284,7 +2290,7 @@ export function ConnectionsSettings() {
key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
target={target}
connectingHostAlias={connectingSshHostAlias}
onConnect={(nextTarget) => void handleConnectSshHost(nextTarget)}
onConnect={connectDiscoveredSshHost}
/>
))}
{hasLoadedDiscoveredSshHosts &&
@@ -2662,14 +2668,26 @@ export function ConnectionsSettings() {
}
}}
>
<DialogTrigger
render={
<Button size="xs" variant="outline">
<PlusIcon className="size-3" />
Add environment
</Button>
}
/>
<Tooltip>
<TooltipTrigger
render={
<DialogTrigger
render={
<Button
size="xs"
variant="ghost"
className="h-5 gap-1 rounded-sm px-1 text-[11px] font-normal text-muted-foreground/60 hover:text-muted-foreground"
aria-label="Add environment"
>
<PlusIcon className="size-3" />
<span>Add environment</span>
</Button>
}
/>
}
/>
<TooltipPopup side="top">Add environment</TooltipPopup>
</Tooltip>
<DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Add Environment</DialogTitle>
@@ -648,7 +648,7 @@ export function ProviderInstanceCard({
);
const authRowNode = (
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
{hasAuthenticatedEmail ? (
<>
<span>Authenticated as</span>
@@ -1256,10 +1256,47 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument();
});
it("shows Git fetch interval settings inside the Git details dropdown", async () => {
setSourceControlDiscoveryStub(async () => ({
versionControlSystems: [
{
kind: "git",
label: "Git",
executable: "git",
implemented: true,
status: "available",
version: Option.some("git version 2.50.0"),
installHint: "Install Git.",
detail: Option.none(),
},
],
sourceControlProviders: [],
}));
mounted = await render(
<AppAtomRegistryProvider>
<SourceControlSettingsPanel />
</AppAtomRegistryProvider>,
);
const toggle = page.getByRole("button", { name: "Toggle Git details" });
await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
await toggle.click();
await expect.element(toggle).toHaveAttribute("aria-expanded", "true");
await expect
.element(page.getByLabelText("Automatic Git fetch interval in seconds"))
.toBeVisible();
await expect
.element(page.getByText("Automatic Git fetches run every 30 seconds"))
.not.toBeInTheDocument();
});
it("does not rescan on remount while the discovery atom is fresh", async () => {
let calls = 0;
setSourceControlDiscoveryStub(async () => {
@@ -1287,7 +1324,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
expect(calls).toBe(1);
const teardown = mounted.cleanup ?? mounted.unmount;
@@ -1301,7 +1338,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
expect(calls).toBe(1);
});
});
@@ -14,6 +14,7 @@ import {
import { scopeThreadRef } from "@t3tools/client-runtime";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { createModelSelection } from "@t3tools/shared/model";
import * as Duration from "effect/Duration";
import * as Equal from "effect/Equal";
import { APP_VERSION, HOSTED_APP_CHANNEL, HOSTED_APP_CHANNEL_LABEL } from "../../branding";
import {
@@ -44,14 +45,10 @@ import {
} from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import { useShallow } from "zustand/react/shallow";
import {
selectProjectsAcrossEnvironments,
selectThreadShellsAcrossEnvironments,
useStore,
} from "../../store";
import { selectProjectsAcrossEnvironments, useStore } from "../../store";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { DraftInput } from "../ui/draft-input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
@@ -411,6 +408,10 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
? ["Assistant output"]
: []),
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
? ["Automatic Git fetch interval"]
: []),
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
: []),
@@ -434,6 +435,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.defaultThreadEnvMode,
settings.diffIgnoreWhitespace,
settings.diffWordWrap,
settings.automaticGitFetchInterval,
settings.enableAssistantStreaming,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -459,6 +461,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
@@ -1330,14 +1333,50 @@ export function ProviderSettingsPanel() {
export function ArchivedThreadsPanel() {
const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
const threads = useStore(useShallow(selectThreadShellsAcrossEnvironments));
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const environmentIds = useMemo(
() => [...new Set(projects.map((project) => project.environmentId))],
[projects],
);
const {
snapshots: archivedSnapshots,
error: archiveError,
isLoading: isLoadingArchive,
refresh: refreshArchivedThreads,
} = useArchivedThreadSnapshots(environmentIds);
const archivedGroups = useMemo(() => {
return projects
const projectsByEnvironmentAndId = new Map(
archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
snapshot.projects.map(
(project) =>
[
`${environmentId}:${project.id}`,
{
id: project.id,
environmentId,
name: project.title,
cwd: project.workspaceRoot,
},
] as const,
),
),
);
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
snapshot.threads.map((thread) => ({
...thread,
environmentId,
})),
);
return [...projectsByEnvironmentAndId.values()]
.map((project) => ({
project,
threads: threads
.filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)
.filter(
(thread) =>
thread.projectId === project.id && thread.environmentId === project.environmentId,
)
.toSorted((left, right) => {
const leftKey = left.archivedAt ?? left.createdAt;
const rightKey = right.archivedAt ?? right.createdAt;
@@ -1345,7 +1384,7 @@ export function ArchivedThreadsPanel() {
}),
}))
.filter((group) => group.threads.length > 0);
}, [projects, threads]);
}, [archivedSnapshots]);
const handleArchivedThreadContextMenu = useCallback(
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
@@ -1362,6 +1401,7 @@ export function ArchivedThreadsPanel() {
if (clicked === "unarchive") {
try {
await unarchiveThread(threadRef);
refreshArchivedThreads();
} catch (error) {
toastManager.add(
stackedThreadToast({
@@ -1376,24 +1416,37 @@ export function ArchivedThreadsPanel() {
if (clicked === "delete") {
await confirmAndDeleteThread(threadRef);
refreshArchivedThreads();
}
},
[confirmAndDeleteThread, unarchiveThread],
[confirmAndDeleteThread, refreshArchivedThreads, unarchiveThread],
);
return (
<SettingsPageContainer>
{archivedGroups.length === 0 ? (
<SettingsSection title="Archived threads">
<Empty className="min-h-88">
<EmptyMedia variant="icon">
<ArchiveIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No archived threads</EmptyTitle>
<EmptyDescription>Archived threads will appear here.</EmptyDescription>
</EmptyHeader>
</Empty>
<SettingsRow
title={
<span className="inline-flex items-center gap-2">
{isLoadingArchive ? (
<LoaderIcon className="size-3.5 animate-spin text-muted-foreground" />
) : (
<ArchiveIcon className="size-3.5 text-muted-foreground" />
)}
{isLoadingArchive
? "Loading archived threads"
: archiveError
? "Could not load archived threads"
: "No archived threads"}
</span>
}
description={
isLoadingArchive
? "Checking connected environments."
: (archiveError ?? "Archived threads will appear here.")
}
/>
</SettingsSection>
) : (
archivedGroups.map(({ project, threads: projectThreads }) => (
@@ -1403,9 +1456,8 @@ export function ArchivedThreadsPanel() {
icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
>
{projectThreads.map((thread) => (
<div
<SettingsRow
key={thread.id}
className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(
@@ -1416,39 +1468,40 @@ export function ArchivedThreadsPanel() {
},
);
}}
>
<div className="min-w-0 flex-1">
<h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>
<p className="text-xs text-muted-foreground">
title={thread.title}
description={
<>
Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}
{" \u00b7 Created "}
{formatRelativeTimeLabel(thread.createdAt)}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id)).catch(
(error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
}),
);
},
)
}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
</div>
</>
}
control={
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id))
.then(() => refreshArchivedThreads())
.catch((error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
}),
);
})
}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
}
/>
))}
</SettingsSection>
))
@@ -1,6 +1,7 @@
import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import * as Duration from "effect/Duration";
import * as Option from "effect/Option";
import { type ReactNode } from "react";
import { useState, type ReactNode } from "react";
import type {
SourceControlProviderKind,
SourceControlDiscoveryResult,
@@ -9,7 +10,9 @@ import type {
VcsDriverKind,
VcsDiscoveryItem,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
import {
refreshSourceControlDiscovery,
@@ -17,6 +20,7 @@ import {
} from "../../lib/sourceControlDiscoveryState";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
import {
Empty,
EmptyContent,
@@ -26,6 +30,13 @@ import {
EmptyTitle,
} from "../ui/empty";
import { Skeleton } from "../ui/skeleton";
import {
NumberField,
NumberFieldDecrement,
NumberFieldGroup,
NumberFieldIncrement,
NumberFieldInput,
} from "../ui/number-field";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
@@ -38,7 +49,7 @@ import {
type Icon,
} from "../Icons";
import { RedactedSensitiveText } from "./RedactedSensitiveText";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
versionControlSystems: [],
@@ -58,6 +69,18 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
};
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
function durationToSeconds(duration: Duration.Duration): number {
return Math.round(Duration.toMillis(duration) / 1_000);
}
function normalizeFetchIntervalSeconds(value: number | null): number {
if (value === null || !Number.isFinite(value)) {
return 0;
}
return Math.max(0, Math.round(value));
}
function optionLabel(value: Option.Option<string>): string | null {
return Option.getOrNull(value);
@@ -146,7 +169,7 @@ function itemSummary({
}
if (item.status !== "available") {
return <span>Not available on this server — {item.installHint}</span>;
return <span>Not available on this server: {item.installHint}</span>;
}
if (auth) {
@@ -189,8 +212,10 @@ function itemSummary({
function DiscoveryItemRow({
item,
children,
}: {
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
readonly children?: ReactNode;
}) {
const version = optionLabel(item.version);
const enabled =
@@ -198,6 +223,8 @@ function DiscoveryItemRow({
const auth = isProviderDiscoveryItem(item) ? item.auth : null;
const authStatus = auth ? authPresentation(auth) : null;
const authAccount = auth ? optionLabel(auth.account) : null;
const [isExpanded, setIsExpanded] = useState(false);
const hasDetails = children !== undefined;
return (
<div
@@ -211,9 +238,9 @@ function DiscoveryItemRow({
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<SourceControlItemMark item={item} />
<h3 className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
<span className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
{item.label}
</h3>
</span>
{version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
{isVcsNotReady(item) ? (
<Badge variant="warning" size="sm">
@@ -226,17 +253,105 @@ function DiscoveryItemRow({
</Badge>
) : null}
</div>
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
{itemSummary({ item, auth, authAccount })}
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{hasDetails ? (
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={() => setIsExpanded((open) => !open)}
aria-expanded={isExpanded}
aria-label={`Toggle ${item.label} details`}
>
<ChevronDownIcon
className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
/>
</Button>
) : null}
{!isVcsNotReady(item) ? (
<Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
) : null}
</div>
</div>
</div>
{hasDetails ? (
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
<CollapsibleContent>
<div className="border-t border-border/60 px-4 py-3 sm:px-5">{children}</div>
</CollapsibleContent>
</Collapsible>
) : null}
</div>
);
}
function GitFetchIntervalSettings() {
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
const { updateSettings } = useUpdateSettings();
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
);
const canResetFetchInterval =
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
return (
<div className="grid gap-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 items-center gap-1">
<span className="text-xs font-medium text-foreground">Fetch interval</span>
<span
className={cn(
"inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
)}
aria-hidden={!canResetFetchInterval}
>
{canResetFetchInterval ? (
<SettingResetButton
label="fetch interval"
onClick={() =>
updateSettings({
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
})
}
/>
) : null}
</span>
</div>
<p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
or security keys should only be prompted by explicit Git actions.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={automaticGitFetchIntervalSeconds}
min={0}
step={GIT_FETCH_INTERVAL_STEP_SECONDS}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings({
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
})
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease fetch interval" />
<NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
<NumberFieldIncrement aria-label="Increase fetch interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
</div>
);
}
@@ -324,7 +439,6 @@ function EmptySourceControlDiscovery({
export function SourceControlSettingsPanel() {
const discovery = useSourceControlDiscovery();
const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
const hasDiscoveryItems =
result.versionControlSystems.length > 0 || result.sourceControlProviders.length > 0;
@@ -364,7 +478,9 @@ export function SourceControlSettingsPanel() {
{result.versionControlSystems.length > 0 ? (
<SettingsSection title="Version Control" headerAction={scanButton}>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item} />
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
</DiscoveryItemRow>
))}
</SettingsSection>
) : null}
@@ -52,7 +52,9 @@ export function SettingsRow({
resetAction,
control,
children,
}: {
className,
...rowProps
}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
title: ReactNode;
description: ReactNode;
status?: ReactNode;
@@ -62,9 +64,11 @@ export function SettingsRow({
}) {
return (
<div
{...rowProps}
className={cn(
"border-t border-border/60 px-4 first:border-t-0 sm:px-5",
children ? "pt-3.5 pb-0" : "py-3.5",
className,
)}
>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+1
View File
@@ -47,6 +47,7 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
dispatchCommand: rpcClient.orchestration.dispatchCommand,
getTurnDiff: rpcClient.orchestration.getTurnDiff,
getFullThreadDiff: rpcClient.orchestration.getFullThreadDiff,
getArchivedShellSnapshot: rpcClient.orchestration.getArchivedShellSnapshot,
subscribeShell: (callback, options) =>
rpcClient.orchestration.subscribeShell(callback, options),
subscribeThread: (input, callback, options) =>
+24 -10
View File
@@ -9,6 +9,7 @@ import { useComposerDraftStore } from "../composerDraftStore";
import { useNewThreadHandler } from "./useHandleNewThread";
import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
import { newCommandId } from "../lib/utils";
import { readLocalApi } from "../localApi";
import {
@@ -68,19 +69,22 @@ export function useThreadActions() {
throw new Error("Cannot archive a running thread.");
}
await api.orchestration.dispatchCommand({
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToDraft =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const archiveCommand = api.orchestration.dispatchCommand({
type: "thread.archive",
commandId: newCommandId(),
threadId: threadRef.threadId,
});
const currentRouteThreadRef = getCurrentRouteThreadRef();
if (
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId
) {
if (shouldNavigateToDraft) {
await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId));
}
await archiveCommand;
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
},
[getCurrentRouteThreadRef, resolveThreadTarget],
);
@@ -93,6 +97,7 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId: target.threadId,
});
refreshArchivedThreadsForEnvironment(target.environmentId);
}, []);
const deleteThread = useCallback(
@@ -100,7 +105,16 @@ export function useThreadActions() {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
const resolved = resolveThreadTarget(target);
if (!resolved) return;
if (!resolved) {
// Thread not in main store (e.g. archived thread) — dispatch delete directly.
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: target.threadId,
});
refreshArchivedThreadsForEnvironment(target.environmentId);
return;
}
const { thread, threadRef } = resolved;
const state = useStore.getState();
const threads = selectThreadsForEnvironment(state, threadRef.environmentId);
@@ -175,6 +189,7 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId: threadRef.threadId,
});
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(
scopeProjectRef(threadRef.environmentId, thread.projectId),
@@ -252,13 +267,12 @@ export function useThreadActions() {
if (!api) return;
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
if (!resolved) return;
const { thread } = resolved;
if (confirmThreadDelete && localApi) {
const title = resolved?.thread.title ?? "this thread";
const confirmed = await localApi.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
`Delete thread "${title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
+12
View File
@@ -79,4 +79,16 @@ describe("hostedPairing", () => {
vi.stubEnv("VITE_HTTP_URL", "https://backend.example.com");
expect(isHostedStaticApp(new URL("https://preview.t3.codes/"))).toBe(false);
});
it("detects hosted channel aliases as static apps", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://app.t3.codes");
vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "nightly");
vi.stubEnv("VITE_HTTP_URL", "");
vi.stubEnv("VITE_WS_URL", "");
expect(isHostedStaticApp(new URL("https://nightly.app.t3.codes/"))).toBe(true);
vi.stubEnv("VITE_HTTP_URL", "https://backend.example.com");
expect(isHostedStaticApp(new URL("https://nightly.app.t3.codes/"))).toBe(false);
});
});
+9
View File
@@ -18,6 +18,11 @@ function configuredBackendUrl(): string {
return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
}
function configuredHostedAppChannel(): HostedAppChannel | null {
const channel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
return channel === "latest" || channel === "nightly" ? channel : null;
}
function originFromUrl(value: string): string | null {
try {
return new URL(value).origin;
@@ -31,6 +36,10 @@ export function isHostedStaticApp(url: URL = new URL(window.location.href)): boo
return false;
}
if (configuredHostedAppChannel()) {
return true;
}
const hostedOrigin = originFromUrl(configuredHostedAppUrl());
return hostedOrigin !== null && url.origin === hostedOrigin;
}
+106
View File
@@ -0,0 +1,106 @@
import { useAtomValue } from "@effect/atom-react";
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { readEnvironmentApi } from "../environmentApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
const ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
const ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
export type ArchivedSnapshotEntry = {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
};
const knownArchivedThreadEnvironmentKeys = new Set<string>();
function makeArchivedThreadsEnvironmentKey(environmentIds: ReadonlyArray<EnvironmentId>): string {
return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
}
function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
if (key.length === 0) {
return [];
}
return key
.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
.map((environmentId) => EnvironmentId.make(environmentId));
}
const archivedThreadSnapshotsAtom = Atom.family((environmentKey: string) => {
knownArchivedThreadEnvironmentKeys.add(environmentKey);
return Atom.make(
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
const environmentIds = parseArchivedThreadsEnvironmentKey(environmentKey);
const snapshots = await Promise.all(
environmentIds.map(async (environmentId) => {
const api = readEnvironmentApi(environmentId);
if (!api) {
return null;
}
return {
environmentId,
snapshot: await api.orchestration.getArchivedShellSnapshot(),
};
}),
);
return snapshots.filter((snapshot) => snapshot !== null);
}),
).pipe(
Atom.swr({
staleTime: ARCHIVED_THREADS_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(ARCHIVED_THREADS_IDLE_TTL_MS),
Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
);
});
function readArchivedThreadsError(
result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
): string | null {
if (result._tag !== "Failure") {
return null;
}
const error = Cause.squash(result.cause);
return error instanceof Error ? error.message : "Failed to load archived threads.";
}
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
for (const key of knownArchivedThreadEnvironmentKeys) {
if (parseArchivedThreadsEnvironmentKey(key).includes(environmentId)) {
appAtomRegistry.refresh(archivedThreadSnapshotsAtom(key));
}
}
}
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly error: string | null;
readonly isLoading: boolean;
readonly refresh: () => void;
} {
const environmentKey = useMemo(
() => makeArchivedThreadsEnvironmentKey(environmentIds),
[environmentIds],
);
const atom = archivedThreadSnapshotsAtom(environmentKey);
const result = useAtomValue(atom);
const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
const refresh = useCallback(() => {
appAtomRegistry.refresh(atom);
}, [atom]);
return {
snapshots,
error: readArchivedThreadsError(result),
isLoading: result.waiting,
refresh,
};
}
+7
View File
@@ -143,6 +143,9 @@ export interface WsRpcClient {
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
readonly getArchivedShellSnapshot: RpcUnaryNoArgMethod<
typeof ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot
>;
readonly subscribeShell: RpcStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeShell>;
readonly subscribeThread: RpcInputStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeThread>;
};
@@ -288,6 +291,10 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)),
getFullThreadDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)),
getArchivedShellSnapshot: () =>
transport.request((client) =>
client[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]({}),
),
subscribeShell: (listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}),
+5 -2
View File
@@ -1,4 +1,5 @@
import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS, ServerSettings, WS_METHODS } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -18,6 +19,8 @@ import {
} from "../rpc/wsConnectionState";
import { WsTransport } from "./wsTransport";
const encodeServerSettings = Schema.encodeSync(ServerSettings);
type WsEventType = "open" | "message" | "close" | "error";
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
type WsListener = (event?: WsEvent) => void;
@@ -1222,7 +1225,7 @@ describe("WsTransport", () => {
requestId: requestMessage.id,
exit: {
_tag: "Success",
value: DEFAULT_SERVER_SETTINGS,
value: encodeServerSettings(DEFAULT_SERVER_SETTINGS),
},
}),
);
+1 -1
View File
@@ -18,7 +18,7 @@ function channelCookie(channel: "latest" | "nightly"): string {
export const config: VercelConfig = {
buildCommand:
"turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts production",
'turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts --channel "${VITE_HOSTED_APP_CHANNEL:-latest}"',
git: {
deploymentEnabled: false,
},
+1 -1
View File
@@ -44,7 +44,7 @@ Required GitHub Actions secrets:
Optional GitHub Actions variables:
- `VERCEL_TEAM_SLUG`: required only if the token needs an explicit Vercel team scope.
- `VERCEL_TEAM_SLUG`: overrides the Vercel CLI scope when the team slug is preferred over the `VERCEL_ORG_ID` secret.
- `T3CODE_WEB_ROUTER_URL`: defaults to `https://app.t3.codes`.
- `T3CODE_WEB_LATEST_DOMAIN`: defaults to `latest.app.t3.codes`.
- `T3CODE_WEB_NIGHTLY_DOMAIN`: defaults to `nightly.app.t3.codes`.
+11 -1
View File
@@ -1,6 +1,16 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
export const TrimmedString = Schema.Trim;
export const TrimmedString = Schema.String.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
decode: (value) => Effect.succeed(value.trim()),
encode: (value) => Effect.succeed(value.trim()),
}),
),
);
export const TrimmedNonEmptyString = TrimmedString.check(Schema.isNonEmpty());
export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
+2
View File
@@ -55,6 +55,7 @@ import type {
OrchestrationGetFullThreadDiffResult,
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
OrchestrationShellSnapshot,
OrchestrationShellStreamItem,
OrchestrationSubscribeThreadInput,
OrchestrationThreadStreamItem,
@@ -544,6 +545,7 @@ export interface EnvironmentApi {
getFullThreadDiff: (
input: OrchestrationGetFullThreadDiffInput,
) => Promise<OrchestrationGetFullThreadDiffResult>;
getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;
subscribeShell: (
callback: (event: OrchestrationShellStreamItem) => void,
options?: {
+5
View File
@@ -27,6 +27,7 @@ export const ORCHESTRATION_WS_METHODS = {
getTurnDiff: "orchestration.getTurnDiff",
getFullThreadDiff: "orchestration.getFullThreadDiff",
replayEvents: "orchestration.replayEvents",
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
subscribeShell: "orchestration.subscribeShell",
subscribeThread: "orchestration.subscribeThread",
} as const;
@@ -1222,6 +1223,10 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationReplayEventsInput,
output: OrchestrationReplayEventsResult,
},
getArchivedShellSnapshot: {
input: Schema.Struct({}),
output: OrchestrationShellSnapshot,
},
subscribeThread: {
input: OrchestrationSubscribeThreadInput,
output: OrchestrationThreadStreamItem,
@@ -109,6 +109,22 @@ describe("ProviderInstanceConfig", () => {
expect(decoded.config).toEqual(opaqueConfig);
});
it("trims provider instance envelope fields", () => {
const decoded = decodeProviderInstanceConfig({
driver: " codex ",
displayName: " Codex Personal ",
accentColor: " #dc2626 ",
environment: [{ name: " OPENROUTER_API_KEY ", value: " sk-or-test " }],
});
expect(decoded).toMatchObject({
driver: "codex",
displayName: "Codex Personal",
accentColor: "#dc2626",
environment: [{ name: "OPENROUTER_API_KEY", value: " sk-or-test " }],
});
});
it("decodes generic environment variables on the instance envelope", () => {
const decoded = decodeProviderInstanceConfig({
driver: "claudeAgent",
+10
View File
@@ -410,6 +410,15 @@ export const WsOrchestrationReplayEventsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.
error: OrchestrationReplayEventsError,
});
export const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
{
payload: OrchestrationRpcSchemas.getArchivedShellSnapshot.input,
success: OrchestrationRpcSchemas.getArchivedShellSnapshot.output,
error: OrchestrationGetSnapshotError,
},
);
export const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {
payload: OrchestrationRpcSchemas.subscribeShell.input,
success: OrchestrationRpcSchemas.subscribeShell.output,
@@ -497,6 +506,7 @@ export const WsRpcGroup = RpcGroup.make(
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationReplayEventsRpc,
WsOrchestrationGetArchivedShellSnapshotRpc,
WsOrchestrationSubscribeShellRpc,
WsOrchestrationSubscribeThreadRpc,
);
+59
View File
@@ -6,6 +6,7 @@ import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "./
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
it("defaults to an empty record so legacy configs without the key still decode", () => {
@@ -92,3 +93,61 @@ describe("ServerSettingsPatch.providerInstances", () => {
expect(patch.providerInstances?.[ollamaId]?.driver).toBe("ollama");
});
});
describe("ServerSettingsPatch string normalization", () => {
it("trims string settings while decoding patches", () => {
const patch = decodeServerSettingsPatch({
addProjectBaseDirectory: " ~/Development ",
textGenerationModelSelection: { model: " gpt-5.4-mini " },
observability: {
otlpTracesUrl: " http://localhost:4318/v1/traces ",
},
providers: {
codex: {
binaryPath: " /opt/homebrew/bin/codex ",
homePath: " ~/.codex ",
},
},
providerInstances: {
codex_personal: {
driver: " codex ",
displayName: " Codex Personal ",
config: { homePath: " ~/.codex-personal " },
},
},
});
expect(patch.addProjectBaseDirectory).toBe("~/Development");
expect(patch.textGenerationModelSelection?.model).toBe("gpt-5.4-mini");
expect(patch.observability?.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
expect(patch.providers?.codex?.binaryPath).toBe("/opt/homebrew/bin/codex");
expect(patch.providers?.codex?.homePath).toBe("~/.codex");
expect(patch.providerInstances?.[ProviderInstanceId.make("codex_personal")]?.driver).toBe(
"codex",
);
expect(patch.providerInstances?.[ProviderInstanceId.make("codex_personal")]?.displayName).toBe(
"Codex Personal",
);
expect(patch.providerInstances?.[ProviderInstanceId.make("codex_personal")]?.config).toEqual({
homePath: " ~/.codex-personal ",
});
});
it("trims encoded server settings values before validation", () => {
const defaultSettings = decodeServerSettings({});
const encoded = encodeServerSettings({
...defaultSettings,
addProjectBaseDirectory: " ~/Development ",
providers: {
...defaultSettings.providers,
codex: {
...defaultSettings.providers.codex,
binaryPath: " /opt/homebrew/bin/codex ",
},
},
});
expect(encoded.addProjectBaseDirectory).toBe("~/Development");
expect(encoded.providers?.codex?.binaryPath).toBe("/opt/homebrew/bin/codex");
});
});
+23 -14
View File
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
@@ -336,8 +337,15 @@ export const ObservabilitySettings = Schema.Struct({
});
export type ObservabilitySettings = typeof ObservabilitySettings.Type;
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
Schema.withDecodingDefault(
Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
),
),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
@@ -408,45 +416,46 @@ const ModelSelectionPatch = Schema.Struct({
const CodexSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
homePath: Schema.optionalKey(Schema.String),
shadowHomePath: Schema.optionalKey(Schema.String),
binaryPath: Schema.optionalKey(TrimmedString),
homePath: Schema.optionalKey(TrimmedString),
shadowHomePath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const ClaudeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
homePath: Schema.optionalKey(Schema.String),
binaryPath: Schema.optionalKey(TrimmedString),
homePath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
launchArgs: Schema.optionalKey(Schema.String),
launchArgs: Schema.optionalKey(TrimmedString),
});
const CursorSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
apiEndpoint: Schema.optionalKey(Schema.String),
binaryPath: Schema.optionalKey(TrimmedString),
apiEndpoint: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const OpenCodeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
serverUrl: Schema.optionalKey(Schema.String),
serverPassword: Schema.optionalKey(Schema.String),
binaryPath: Schema.optionalKey(TrimmedString),
serverUrl: Schema.optionalKey(TrimmedString),
serverPassword: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
export const ServerSettingsPatch = Schema.Struct({
// Server settings
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
addProjectBaseDirectory: Schema.optionalKey(Schema.String),
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
observability: Schema.optionalKey(
Schema.Struct({
otlpTracesUrl: Schema.optionalKey(Schema.String),
otlpMetricsUrl: Schema.optionalKey(Schema.String),
otlpTracesUrl: Schema.optionalKey(TrimmedString),
otlpMetricsUrl: Schema.optionalKey(TrimmedString),
}),
),
providers: Schema.optionalKey(
+4
View File
@@ -28,6 +28,10 @@
"types": "./src/shell.ts",
"import": "./src/shell.ts"
},
"./semver": {
"types": "./src/semver.ts",
"import": "./src/semver.ts"
},
"./Net": {
"types": "./src/Net.ts",
"import": "./src/Net.ts"
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { extractJsonObject } from "./schemaJson.ts";
describe("schemaJson helpers", () => {
it("extracts a balanced JSON object from surrounding text", () => {
expect(
extractJsonObject(`Sure, here is the JSON:
\`\`\`json
{
"subject": "Update README",
"body": ""
}
\`\`\`
Done.`),
).toBe(`{
"subject": "Update README",
"body": ""
}`);
});
it("ignores braces inside strings while finding the object boundary", () => {
expect(
extractJsonObject('prefix {"message":"literal } brace","nested":{"ok":true}} suffix'),
).toBe('{"message":"literal } brace","nested":{"ok":true}}');
});
it("returns trimmed input when no JSON object starts", () => {
expect(extractJsonObject(" no structured output ")).toBe("no structured output");
});
});
+48
View File
@@ -97,6 +97,54 @@ export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/**
* Build a JSON string schema that encodes with stable 2-space formatting.
*
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import { compareSemverVersions, normalizeSemverVersion, satisfiesSemverRange } from "./semver.ts";
describe("semver helpers", () => {
it("matches supported range groups", () => {
const range = "^22.16 || ^23.11 || >=24.10";
expect(satisfiesSemverRange("22.16.0", range)).toBe(true);
expect(satisfiesSemverRange("23.11.1", range)).toBe(true);
expect(satisfiesSemverRange("24.10.0", range)).toBe(true);
expect(satisfiesSemverRange("22.15.9", range)).toBe(false);
expect(satisfiesSemverRange("23.10.9", range)).toBe(false);
expect(satisfiesSemverRange("24.9.9", range)).toBe(false);
});
it("normalizes versions with a missing patch segment", () => {
expect(normalizeSemverVersion("2.1")).toBe("2.1.0");
});
it("compares prerelease versions before stable versions", () => {
expect(compareSemverVersions("2.1.111-beta.1", "2.1.111")).toBeLessThan(0);
});
it("falls back to lexical comparison for malformed numeric segments", () => {
expect(compareSemverVersions("1.2.3abc", "1.2.10")).toBeGreaterThan(0);
});
it("supports comparison comparators", () => {
expect(satisfiesSemverRange("24.9.0", ">=24.0 <24.10")).toBe(true);
expect(satisfiesSemverRange("24.10.0", ">=24.0 <24.10")).toBe(false);
});
it("honors caret range upper bounds for zero-major versions", () => {
expect(satisfiesSemverRange("0.2.3", "^0.2.3")).toBe(true);
expect(satisfiesSemverRange("0.2.9", "^0.2.3")).toBe(true);
expect(satisfiesSemverRange("0.3.0", "^0.2.3")).toBe(false);
expect(satisfiesSemverRange("0.5.0", "^0.2.3")).toBe(false);
expect(satisfiesSemverRange("0.0.3", "^0.0.3")).toBe(true);
expect(satisfiesSemverRange("0.0.4", "^0.0.3")).toBe(false);
});
it("rejects invalid versions and unsupported range syntax", () => {
expect(satisfiesSemverRange("not-a-version", ">=24.0")).toBe(false);
expect(satisfiesSemverRange("24.10.0", "~24.10")).toBe(false);
});
it("keeps the range checker stringifiable and executable as plain JavaScript", () => {
const source = satisfiesSemverRange.toString();
const recreated = Function(`return (${source});`)() as typeof satisfiesSemverRange;
expect(source).toContain("function satisfiesSemverRange");
expect(source).not.toContain(": string");
expect(source).not.toContain(": boolean");
expect(recreated("24.10.0", ">=24.10")).toBe(true);
expect(recreated("24.9.9", ">=24.10")).toBe(false);
});
});
+216
View File
@@ -0,0 +1,216 @@
interface ParsedSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
const SEMVER_NUMBER_SEGMENT = /^\d+$/;
export function normalizeSemverVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
export function parseSemver(value: string): ParsedSemver | null {
const normalized = normalizeSemverVersion(value).replace(/^v/, "");
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
if (
!SEMVER_NUMBER_SEGMENT.test(majorSegment) ||
!SEMVER_NUMBER_SEGMENT.test(minorSegment) ||
!SEMVER_NUMBER_SEGMENT.test(patchSegment)
) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = SEMVER_NUMBER_SEGMENT.test(left);
const rightNumeric = SEMVER_NUMBER_SEGMENT.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareSemverVersions(left: string, right: string): number {
const parsedLeft = parseSemver(left);
const parsedRight = parseSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
/**
* Small semver range checker for CLI/runtime gates.
*
* Keep the function body valid plain JavaScript: SSH startup stringifies this
* function and runs it on remote Node versions before TypeScript support is known.
*
* @param rawVersion Version string, with or without a leading `v`.
* @param range Space-separated comparators, with `||` range groups.
* @returns Whether `rawVersion` satisfies the supported range syntax.
*/
export const satisfiesSemverRange: (rawVersion: string, range: string) => boolean =
function satisfiesSemverRange(rawVersion, range) {
const normalizedVersion = String(rawVersion).trim().replace(/^v/, "");
const versionMatch = normalizedVersion.match(
/^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/,
);
if (!versionMatch) {
return false;
}
const version = {
major: Number(versionMatch[1]),
minor: Number(versionMatch[2] || 0),
patch: Number(versionMatch[3] || 0),
};
return range.split("||").some((group) => {
const comparators = group.trim().split(/\s+/).filter(Boolean);
if (comparators.length === 0) {
return false;
}
return comparators.every((comparator) => {
const match = comparator.trim().match(/^(\^|>=|>|<=|<|=)?\s*v?(\d+(?:\.\d+){0,2})$/);
if (!match) {
return false;
}
const targetVersion = match[2];
if (targetVersion === undefined) {
return false;
}
const targetMatch = targetVersion.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);
if (!targetMatch) {
return false;
}
const target = {
major: Number(targetMatch[1]),
minor: Number(targetMatch[2] || 0),
patch: Number(targetMatch[3] || 0),
};
const compared =
version.major !== target.major
? version.major > target.major
? 1
: -1
: version.minor !== target.minor
? version.minor > target.minor
? 1
: -1
: version.patch !== target.patch
? version.patch > target.patch
? 1
: -1
: 0;
const operator = match[1] || "=";
switch (operator) {
case "^":
if (compared < 0) {
return false;
}
if (target.major > 0) {
return version.major === target.major;
}
if (target.minor > 0) {
return version.major === 0 && version.minor === target.minor;
}
return version.major === 0 && version.minor === 0 && version.patch === target.patch;
case ">=":
return compared >= 0;
case ">":
return compared > 0;
case "<=":
return compared <= 0;
case "<":
return compared < 0;
case "=":
return compared === 0;
default:
return false;
}
});
});
};
+9 -8
View File
@@ -76,14 +76,15 @@ export function applyServerSettingsPatch(
patch: ServerSettingsPatch,
): ServerSettings {
const selectionPatch = patch.textGenerationModelSelection;
const next = deepMerge(current, patch);
const nextWithReplacements =
patch.providerInstances !== undefined
? {
...next,
providerInstances: patch.providerInstances,
}
: next;
const { automaticGitFetchInterval, ...patchForMerge } = patch;
const next = deepMerge(current, patchForMerge);
const nextWithReplacements = {
...next,
...(patch.providerInstances !== undefined
? { providerInstances: patch.providerInstances }
: {}),
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
};
if (!selectionPatch) {
return nextWithReplacements;
}
+96 -3
View File
@@ -20,11 +20,14 @@ import {
buildRemoteT3RunnerScript,
describeReadinessCause,
issueRemotePairingToken,
launchOrReuseRemoteServer,
REMOTE_PICK_PORT_SCRIPT,
SshEnvironmentManager,
waitForHttpReady,
} from "./tunnel.ts";
const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
const makeSuccessfulProcess = (stdout: string) => {
const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
return ChildProcessSpawner.makeHandle({
@@ -87,13 +90,34 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
describe("ssh tunnel scripts", () => {
it("builds the remote t3 runner with npx and npm fallbacks", () => {
const script = buildRemoteT3RunnerScript();
const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
assert.include(script, "T3_NODE_SCRIPT_PATH=''");
assert.include(script, 'exec t3 "$@"');
assert.include(script, "exec npx --yes 't3@latest' \"$@\"");
assert.include(script, "exec npm exec --yes 't3@latest' -- \"$@\"");
assert.include(script, "could not install 't3@latest'");
assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
assert.include(script, "remote_node_satisfies_engine()");
assert.include(script, "function satisfiesSemverRange");
assert.include(script, "satisfiesSemverRange(rawVersion, range)");
assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
assert.include(script, 'eval "$(fnm env --use-on-cd --shell sh)"');
assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
assert.include(script, 'NVM_DIR="$HOME/.nvm"');
assert.include(script, "nvm use --silent default");
assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
});
it("does not hard-code a remote node engine range", () => {
const script = buildRemoteT3RunnerScript();
assert.include(script, "T3_NODE_ENGINE_RANGE=''");
assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
});
it("shell-quotes package specs in the remote t3 runner", () => {
@@ -127,10 +151,20 @@ describe("ssh tunnel scripts", () => {
} as const;
assert.include(
buildRemoteLaunchScript(),
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
'[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
);
assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
assert.include(
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
`T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
);
assert.include(
buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
"does not satisfy required range ",
);
assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(buildRemoteLaunchScript(), "wait_ready");
assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
@@ -156,17 +190,48 @@ describe("ssh tunnel scripts", () => {
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
);
assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
assert.include(
buildRemoteLaunchScript(),
'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
);
assert.include(
buildRemoteLaunchScript(),
"if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
);
assert.include(buildRemoteLaunchScript(), 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
assert.isBelow(
buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
);
assert.isBelow(
buildRemoteLaunchScript().indexOf('DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port'),
buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
);
});
it.effect("accepts launch JSON after remote shell startup noise", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
const spawner = ChildProcessSpawner.make(() =>
Effect.succeed(makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n')),
);
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const result = yield* launchOrReuseRemoteServer(target);
assert.equal(result.remotePort, 3774);
}).pipe(Effect.provide(processLayer));
});
it("allows the remote port picker to run without a state file path", () => {
assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
});
@@ -232,6 +297,34 @@ describe("ssh tunnel scripts", () => {
"expiresAt": "2026-04-29T01:01:20.994Z"
}
`),
),
);
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const result = yield* issueRemotePairingToken(target);
assert.equal(result.credential, "LCL4R2TPHDKQ");
}).pipe(Effect.provide(processLayer));
});
it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
const spawner = ChildProcessSpawner.make(() =>
Effect.succeed(
makeSuccessfulProcess(`loaded nvm default
{
"id": "88941235-6ed5-4184-a2ff-5339e2075958",
"credential": "LCL4R2TPHDKQ",
"role": "client",
"expiresAt": "2026-04-29T01:01:20.994Z"
}
`),
),
);
+196 -20
View File
@@ -3,7 +3,8 @@ import type {
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -58,6 +59,7 @@ const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
readonly nodeScriptPath?: string | null;
readonly nodeEngineRange?: string | null;
}
export interface SshEnvironmentManagerOptions {
@@ -166,6 +168,50 @@ const decodeRemoteLaunchResult = Schema.decodeEffect(fromLenientJson(RemoteLaunc
const decodeRemotePairingResult = Schema.decodeEffect(fromLenientJson(RemotePairingResult));
const decodeRemoteHttpError = Schema.decodeEffect(Schema.fromJsonString(RemoteHttpError));
const decodeRemoteJsonOutput = <A, E>(
stdout: string,
decode: (input: string) => Effect.Effect<A, E>,
): Effect.Effect<A, E> =>
decode(stdout).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
const jsonObject = extractJsonObject(stdout);
if (jsonObject === stdout.trim()) {
return yield* Effect.fail(error);
}
const exit = yield* Effect.exit(decode(jsonObject));
if (Exit.isSuccess(exit)) {
return exit.value;
}
return yield* Effect.fail(error);
}),
),
);
const decodeRemoteLaunchOutput = (stdout: string) =>
decodeRemoteJsonOutput(stdout, decodeRemoteLaunchResult);
const decodeRemotePairingOutput = (stdout: string) =>
decodeRemoteJsonOutput(stdout, decodeRemotePairingResult);
const remoteNodeEngineCheckMain = function remoteNodeEngineCheckMain() {
const range = process.argv[2] || "";
const rawVersion =
process.versions && process.versions.node ? process.versions.node : process.version;
if (!satisfiesSemverRange(rawVersion, range)) {
process.stderr.write(
"Remote node " + rawVersion + " does not satisfy required range " + range + ".\n",
);
process.exit(1);
}
};
function buildRemoteNodeEngineCheckScript(): string {
return `${satisfiesSemverRange.toString()}
(${remoteNodeEngineCheckMain.toString()})();`;
}
export function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
const cleaned = stderr.trim();
return cleaned.length > 0 ? cleaned : fallbackMessage;
@@ -299,10 +345,108 @@ function probe() {
})().catch(() => process.exit(1));
`;
export const REMOTE_NODE_ENV_SCRIPT = `prepend_path_if_dir() {
if [ -d "$1" ]; then
case ":$PATH:" in
*":$1:"*) ;;
*) PATH="$1:$PATH" ;;
esac
fi
}
remote_node_satisfies_engine() {
T3_NODE_ENGINE_RANGE=@@T3_NODE_ENGINE_RANGE@@
if [ -z "$T3_NODE_ENGINE_RANGE" ]; then
return 0
fi
node - "$T3_NODE_ENGINE_RANGE" <<'NODE'
@@T3_NODE_ENGINE_CHECK_SCRIPT@@
NODE
}
ensure_remote_node_path() {
if command -v node >/dev/null 2>&1 && remote_node_satisfies_engine >/dev/null 2>&1; then
return 0
fi
prepend_path_if_dir "$HOME/.local/bin"
prepend_path_if_dir "$HOME/bin"
prepend_path_if_dir "/opt/homebrew/bin"
prepend_path_if_dir "/usr/local/bin"
prepend_path_if_dir "/usr/bin"
prepend_path_if_dir "/bin"
if [ -z "\${VOLTA_HOME:-}" ]; then
VOLTA_HOME="$HOME/.volta"
fi
export VOLTA_HOME
prepend_path_if_dir "$VOLTA_HOME/bin"
prepend_path_if_dir "$HOME/.asdf/shims"
prepend_path_if_dir "$HOME/.asdf/bin"
if [ ! -x "$HOME/.asdf/shims/node" ] && [ -s "$HOME/.asdf/asdf.sh" ]; then
# shellcheck disable=SC1090
. "$HOME/.asdf/asdf.sh"
fi
prepend_path_if_dir "$HOME/.local/share/mise/shims"
prepend_path_if_dir "$HOME/.mise/shims"
if ! command -v node >/dev/null 2>&1 && command -v mise >/dev/null 2>&1; then
eval "$(mise activate sh)" >/dev/null 2>&1 || true
fi
if [ -z "\${FNM_DIR:-}" ]; then
FNM_DIR="$HOME/.local/share/fnm"
fi
export FNM_DIR
prepend_path_if_dir "$FNM_DIR"
prepend_path_if_dir "$HOME/.fnm"
if ! command -v node >/dev/null 2>&1 && command -v fnm >/dev/null 2>&1; then
eval "$(fnm env --use-on-cd --shell sh)" >/dev/null 2>&1 || eval "$(fnm env --shell sh)" >/dev/null 2>&1 || true
fi
prepend_path_if_dir "$HOME/.nodenv/bin"
prepend_path_if_dir "$HOME/.nodenv/shims"
if ! command -v node >/dev/null 2>&1 && command -v nodenv >/dev/null 2>&1; then
eval "$(nodenv init -)" >/dev/null 2>&1 || true
fi
if [ -z "\${NVM_DIR:-}" ]; then
NVM_DIR="$HOME/.nvm"
fi
export NVM_DIR
if [ -s "$NVM_DIR/nvm.sh" ]; then
# shellcheck disable=SC1090
. "$NVM_DIR/nvm.sh"
if ! command -v node >/dev/null 2>&1 && command -v nvm >/dev/null 2>&1; then
nvm use --silent default >/dev/null 2>&1 || nvm use --silent node >/dev/null 2>&1 || nvm use --silent --lts >/dev/null 2>&1 || true
fi
fi
if ! command -v node >/dev/null 2>&1 && [ -d "$NVM_DIR/versions/node" ]; then
for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin; do
if [ -x "$T3_NODE_BIN/node" ]; then
PATH="$T3_NODE_BIN:$PATH"
export PATH
fi
done
fi
command -v node >/dev/null 2>&1 && remote_node_satisfies_engine
}
`;
export const REMOTE_RUNNER_SCRIPT = `#!/bin/sh
set -eu
@@T3_NODE_ENV_SCRIPT@@
ensure_remote_node_path || true
T3_NODE_SCRIPT_PATH=@@T3_NODE_SCRIPT_PATH@@
if [ -n "$T3_NODE_SCRIPT_PATH" ]; then
if ! command -v node >/dev/null 2>&1; then
printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
fi
exec node "$T3_NODE_SCRIPT_PATH" "$@"
fi
if command -v t3 >/dev/null 2>&1; then
@@ -314,11 +458,12 @@ fi
if command -v npm >/dev/null 2>&1; then
exec npm exec --yes @@T3_PACKAGE_SPEC@@ -- "$@"
fi
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because npx and npm are unavailable on PATH.\\n' >&2
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because node/npm/npx are unavailable on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
`;
export const REMOTE_LAUNCH_SCRIPT = `set -eu
@@T3_NODE_ENV_SCRIPT@@
STATE_KEY="$1"
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
DEFAULT_SERVER_HOME="$HOME/.t3"
@@ -343,6 +488,10 @@ if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then
fi
mv "$RUNNER_NEXT" "$RUNNER_FILE"
chmod 700 "$RUNNER_FILE"
if ! ensure_remote_node_path; then
printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
fi
pick_port() {
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
@@T3_PICK_PORT_SCRIPT@@
@@ -366,18 +515,18 @@ resolve_default_runtime_port() {
const fs = require("node:fs");
const runtimePath = process.argv[2] ?? "";
try {
const runtime = JSON.parse(fs.readFileSync(runtimePath, "utf8"));
const pid = Number(runtime.pid);
const port = Number(runtime.port);
if (!Number.isInteger(pid) || !Number.isInteger(port)) {
process.exit(1);
}
const runtime = JSON.parse(fs.readFileSync(runtimePath, "utf8"));
const pid = Number(runtime.pid);
const port = Number(runtime.port);
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port)) {
process.exit(1);
}
const origin = new URL(String(runtime.origin ?? ""));
if (origin.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(origin.hostname)) {
process.exit(1);
}
process.kill(pid, 0);
process.stdout.write(String(port));
process.stdout.write(\`\${pid} \${port}\`);
} catch {
process.exit(1);
}
@@ -386,18 +535,34 @@ NODE
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port 2>/dev/null || true)"
DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port 2>/dev/null || true)"
DEFAULT_RUNTIME_PID=""
DEFAULT_REMOTE_PORT=""
if [ -n "$DEFAULT_RUNTIME_INFO" ]; then
DEFAULT_RUNTIME_PID="\${DEFAULT_RUNTIME_INFO%% *}"
DEFAULT_REMOTE_PORT="\${DEFAULT_RUNTIME_INFO#* }"
fi
if [ -n "$DEFAULT_REMOTE_PORT" ]; then
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
if [ "$REMOTE_MANAGED" = "managed" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
kill "$REMOTE_PID" 2>/dev/null || true
wait_for_pid_exit "$REMOTE_PID"
if [ "$REMOTE_MANAGED" = "managed" ]; then
PID_TO_STOP="\${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"
if [ -n "$PID_TO_STOP" ] && kill -0 "$PID_TO_STOP" 2>/dev/null; then
kill "$PID_TO_STOP" 2>/dev/null || true
wait_for_pid_exit "$PID_TO_STOP"
fi
REMOTE_PID=""
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
REMOTE_MANAGED="external"
rm -f "$PID_FILE"
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'external\\n' >"$MANAGED_FILE"
else
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'external\\n' >"$MANAGED_FILE"
REMOTE_PID=""
REMOTE_MANAGED="external"
fi
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'external\\n' >"$MANAGED_FILE"
REMOTE_PID=""
REMOTE_MANAGED="external"
else
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
@@ -429,7 +594,7 @@ else
REMOTE_PORT=""
REMOTE_MANAGED=""
fi
if [ -z "$REMOTE_PID" ] || [ -z "$REMOTE_PORT" ]; then
if [ -z "$REMOTE_PORT" ]; then
REMOTE_PORT="$(pick_port)" || true
if [ -z "$REMOTE_PORT" ]; then
printf 'Failed to find an available port on the remote host. Ensure node is available on PATH.\\n' >&2
@@ -499,12 +664,23 @@ export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string
applyScriptPlaceholders(REMOTE_RUNNER_SCRIPT, {
T3_PACKAGE_SPEC: packageSpec,
T3_NODE_SCRIPT_PATH: shellSingleQuote(nodeScriptPath),
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
}),
);
}
function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string {
return stripTrailingNewlines(
applyScriptPlaceholders(REMOTE_NODE_ENV_SCRIPT, {
T3_NODE_ENGINE_RANGE: shellSingleQuote(input?.nodeEngineRange?.trim() || ""),
T3_NODE_ENGINE_CHECK_SCRIPT: stripTrailingNewlines(buildRemoteNodeEngineCheckScript()),
}),
);
}
export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
return applyScriptPlaceholders(REMOTE_LAUNCH_SCRIPT, {
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
T3_RUNNER_SCRIPT: stripTrailingNewlines(buildRemoteT3RunnerScript(input)),
T3_PICK_PORT_SCRIPT: stripTrailingNewlines(REMOTE_PICK_PORT_SCRIPT),
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
@@ -566,7 +742,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
stdout: result.stdout,
});
}
const parsed = yield* decodeRemoteLaunchResult(result.stdout).pipe(
const parsed = yield* decodeRemoteLaunchOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshLaunchError({
@@ -623,7 +799,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
stdout: result.stdout,
});
}
const parsed = yield* decodeRemotePairingResult(result.stdout).pipe(
const parsed = yield* decodeRemotePairingOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshPairingError({
+20 -4
View File
@@ -6,11 +6,17 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { Argument, Command } from "effect/unstable/cli";
import { resolveWebIconOverrides, type WebAssetBrand } from "./lib/brand-assets.ts";
import { Argument, Command, Flag } from "effect/unstable/cli";
import {
resolveWebAssetBrandForChannel,
resolveWebIconOverrides,
WEB_ASSET_CHANNELS,
type WebAssetBrand,
} from "./lib/brand-assets.ts";
const WEB_ASSET_BRANDS = [
"development",
"nightly",
"production",
] as const satisfies ReadonlyArray<WebAssetBrand>;
@@ -38,15 +44,25 @@ export const applyWebBrandAssetsCommand = Command.make(
{
brand: Argument.choice("brand", WEB_ASSET_BRANDS).pipe(
Argument.withDescription("Asset brand to copy into the hosted web output directory."),
Argument.optional,
),
channel: Flag.choice("channel", WEB_ASSET_CHANNELS).pipe(
Flag.withDescription("Hosted release channel to map to a web asset brand."),
Flag.optional,
),
targetDirectory: Argument.string("target-directory").pipe(
Argument.withDescription("Output directory that contains the hosted web build assets."),
Argument.optional,
),
},
({ brand, targetDirectory }) =>
({ brand, channel, targetDirectory }) =>
applyWebBrandAssets(
brand,
Option.getOrElse(brand, () =>
Option.match(channel, {
onNone: () => "production" as const,
onSome: resolveWebAssetBrandForChannel,
}),
),
Option.getOrElse(targetDirectory, () => "apps/web/dist"),
),
).pipe(Command.withDescription("Copy web brand assets into a built hosted web app."));
+13
View File
@@ -4,6 +4,7 @@ import {
BRAND_ASSET_PATHS,
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
resolveWebAssetBrandForChannel,
resolveWebIconOverrides,
} from "./brand-assets.ts";
@@ -42,4 +43,16 @@ describe("brand-assets", () => {
targetRelativePath: "apps/web/dist/apple-touch-icon.png",
});
});
it("maps hosted nightly web assets to nightly icons", () => {
expect(resolveWebIconOverrides("nightly", "apps/web/dist")).toContainEqual({
sourceRelativePath: BRAND_ASSET_PATHS.nightlyWebFaviconIco,
targetRelativePath: "apps/web/dist/favicon.ico",
});
});
it("maps hosted release channels to web asset brands", () => {
expect(resolveWebAssetBrandForChannel("latest")).toBe("production");
expect(resolveWebAssetBrandForChannel("nightly")).toBe("nightly");
});
});
+19 -1
View File
@@ -10,6 +10,10 @@ export const BRAND_ASSET_PATHS = {
nightlyMacIconPng: "assets/nightly/blueprint-macos-1024.png",
nightlyLinuxIconPng: "assets/nightly/blueprint-universal-1024.png",
nightlyWindowsIconIco: "assets/nightly/blueprint-windows.ico",
nightlyWebFaviconIco: "assets/nightly/blueprint-web-favicon.ico",
nightlyWebFavicon16Png: "assets/nightly/blueprint-web-favicon-16x16.png",
nightlyWebFavicon32Png: "assets/nightly/blueprint-web-favicon-32x32.png",
nightlyWebAppleTouchIconPng: "assets/nightly/blueprint-web-apple-touch-180.png",
developmentDesktopIconPng: "assets/dev/blueprint-macos-1024.png",
developmentWindowsIconIco: "assets/dev/blueprint-windows.ico",
@@ -19,7 +23,15 @@ export const BRAND_ASSET_PATHS = {
developmentWebAppleTouchIconPng: "assets/dev/blueprint-web-apple-touch-180.png",
} as const;
export type WebAssetBrand = "development" | "production";
export type WebAssetBrand = "development" | "nightly" | "production";
export const WEB_ASSET_CHANNELS = ["latest", "nightly"] as const;
export type WebAssetChannel = (typeof WEB_ASSET_CHANNELS)[number];
export function resolveWebAssetBrandForChannel(channel: WebAssetChannel): WebAssetBrand {
return channel === "nightly" ? "nightly" : "production";
}
export interface IconOverride {
readonly sourceRelativePath: string;
@@ -40,6 +52,12 @@ const WEB_ICON_SOURCE_PATHS_BY_BRAND = {
favicon32Png: BRAND_ASSET_PATHS.developmentWebFavicon32Png,
appleTouchIconPng: BRAND_ASSET_PATHS.developmentWebAppleTouchIconPng,
},
nightly: {
faviconIco: BRAND_ASSET_PATHS.nightlyWebFaviconIco,
favicon16Png: BRAND_ASSET_PATHS.nightlyWebFavicon16Png,
favicon32Png: BRAND_ASSET_PATHS.nightlyWebFavicon32Png,
appleTouchIconPng: BRAND_ASSET_PATHS.nightlyWebAppleTouchIconPng,
},
production: {
faviconIco: BRAND_ASSET_PATHS.productionWebFaviconIco,
favicon16Png: BRAND_ASSET_PATHS.productionWebFavicon16Png,
+4 -1
View File
@@ -23,7 +23,10 @@
"T3CODE_OTLP_TRACES_URL",
"T3CODE_OTLP_METRICS_URL",
"T3CODE_OTLP_EXPORT_INTERVAL_MS",
"T3CODE_OTLP_SERVICE_NAME"
"T3CODE_OTLP_SERVICE_NAME",
"APP_VERSION",
"VITE_HOSTED_APP_URL",
"VITE_HOSTED_APP_CHANNEL"
],
"globalPassThroughEnv": ["PATHEXT"],
"tasks": {