From 7bfacd55d89524ee2bce68e5ae863222c4609f68 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 8 May 2026 15:20:02 -0700 Subject: [PATCH 1/4] [codex] Handle NuGet provider bootstrap failures (#2608) Co-authored-by: Julius Marminge --- .github/workflows/release.yml | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 382bd6f1eb..e99f852fee 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 From 63859aa072249c64153ef20faeb46018154724b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 8 May 2026 15:49:41 -0700 Subject: [PATCH 2/4] perf: Add archived shell snapshot support (#2593) Co-authored-by: Cursor Agent --- .../Layers/CheckpointDiffQuery.test.ts | 6 + .../Layers/OrchestrationEngine.test.ts | 7 + .../Layers/ProjectionSnapshotQuery.test.ts | 120 ++++++++ .../Layers/ProjectionSnapshotQuery.ts | 278 +++++++++++++++++- .../Services/ProjectionSnapshotQuery.ts | 11 + apps/server/src/persistence/Migrations.ts | 2 + ...030_ProjectionThreadShellArchiveIndexes.ts | 16 + .../Layers/ProjectSetupScriptRunner.test.ts | 1 + .../Layers/ProviderSessionReaper.test.ts | 1 + apps/server/src/server.test.ts | 7 + apps/server/src/serverRuntimeStartup.test.ts | 3 + apps/server/src/ws.ts | 29 ++ apps/web/src/components/ChatView.browser.tsx | 3 + .../settings/ConnectionsSettings.tsx | 28 +- .../settings/ProviderInstanceCard.tsx | 2 +- .../components/settings/SettingsPanels.tsx | 150 ++++++---- .../settings/SourceControlSettings.tsx | 2 +- .../components/settings/settingsLayout.tsx | 6 +- apps/web/src/environmentApi.ts | 1 + apps/web/src/hooks/useThreadActions.ts | 34 ++- apps/web/src/lib/archivedThreadsState.ts | 105 +++++++ apps/web/src/rpc/wsRpcClient.ts | 7 + packages/contracts/src/ipc.ts | 2 + packages/contracts/src/orchestration.ts | 5 + packages/contracts/src/rpc.ts | 10 + 25 files changed, 761 insertions(+), 75 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts create mode 100644 apps/web/src/lib/archivedThreadsState.ts diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts index 7e012312dc..5d4b072c94 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts @@ -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()), diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index d74c2c5ed4..75fd236f9e 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -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 }), diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 7f6f973ed8..01d7c29574 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -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", () => diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 9a539d77ae..cf6cb7beaa 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -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 ?? new Date(0).toISOString(), + }; + + 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, diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 2df890d547..53dfe33bf4 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -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. diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index c0918de849..cc5024d5f5 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -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) => diff --git a/apps/server/src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts b/apps/server/src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts new file mode 100644 index 0000000000..3b7bf51f04 --- /dev/null +++ b/apps/server/src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts @@ -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) + `; +}); diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts index 72e3b5e6d5..1a13229fd8 100644 --- a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -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) => diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 57903e3776..add225e2ee 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -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"), diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 819abb979d..857da7aebe 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -630,6 +630,13 @@ const buildAppUnderTest = (options?: { threads: [], updatedAt: "1970-01-01T00:00:00.000Z", }), + getArchivedShellSnapshot: () => + Effect.succeed({ + snapshotSequence: 0, + projects: [], + threads: [], + updatedAt: new Date(0).toISOString(), + }), getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), getProjectShellById: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index b47c7d0af6..1da9a63070 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -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()), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 80f5b1f8e3..d3c891b2bb 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -308,6 +308,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => }), ); case "thread.deleted": + case "thread.archived": return Effect.succeed( Option.some({ kind: "thread-removed" as const, @@ -315,6 +316,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 +746,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, diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 17cf014c22..f51780abf5 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -218,6 +218,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"], diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index b3dea6c311..17dc177a98 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -2662,14 +2662,26 @@ export function ConnectionsSettings() { } }} > - - - Add environment - - } - /> + + + + Add environment + + } + /> + } + /> + Add environment + Add Environment diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 44ba093615..9a00ccb75a 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -648,7 +648,7 @@ export function ProviderInstanceCard({ ); const authRowNode = ( -

+

{hasAuthenticatedEmail ? ( <> Authenticated as diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 9f0166a9d2..def96b9ba9 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -44,14 +44,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"; @@ -1330,14 +1326,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 +1377,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 +1394,7 @@ export function ArchivedThreadsPanel() { if (clicked === "unarchive") { try { await unarchiveThread(threadRef); + refreshArchivedThreads(); } catch (error) { toastManager.add( stackedThreadToast({ @@ -1376,24 +1409,37 @@ export function ArchivedThreadsPanel() { if (clicked === "delete") { await confirmAndDeleteThread(threadRef); + refreshArchivedThreads(); } }, - [confirmAndDeleteThread, unarchiveThread], + [confirmAndDeleteThread, refreshArchivedThreads, unarchiveThread], ); return ( {archivedGroups.length === 0 ? ( - - - - - - No archived threads - Archived threads will appear here. - - + + {isLoadingArchive ? ( + + ) : ( + + )} + {isLoadingArchive + ? "Loading archived threads" + : archiveError + ? "Could not load archived threads" + : "No archived threads"} + + } + description={ + isLoadingArchive + ? "Checking connected environments." + : (archiveError ?? "Archived threads will appear here.") + } + /> ) : ( archivedGroups.map(({ project, threads: projectThreads }) => ( @@ -1403,9 +1449,8 @@ export function ArchivedThreadsPanel() { icon={} > {projectThreads.map((thread) => ( -

{ event.preventDefault(); void handleArchivedThreadContextMenu( @@ -1416,39 +1461,40 @@ export function ArchivedThreadsPanel() { }, ); }} - > -
-

{thread.title}

-

+ title={thread.title} + description={ + <> Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)} {" \u00b7 Created "} {formatRelativeTimeLabel(thread.createdAt)} -

-
- -
+ + } + control={ + + } + /> ))} )) diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 0518848bc5..59c6e4aa63 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -226,7 +226,7 @@ function DiscoveryItemRow({ ) : null} -

+

{itemSummary({ item, auth, authAccount })}

diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index 54c2c99b86..391898b111 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -52,7 +52,9 @@ export function SettingsRow({ resetAction, control, children, -}: { + className, + ...rowProps +}: Omit, "title"> & { title: ReactNode; description: ReactNode; status?: ReactNode; @@ -62,9 +64,11 @@ export function SettingsRow({ }) { return (
diff --git a/apps/web/src/environmentApi.ts b/apps/web/src/environmentApi.ts index 335d68d372..9e7b0c939a 100644 --- a/apps/web/src/environmentApi.ts +++ b/apps/web/src/environmentApi.ts @@ -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) => diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 46a1955cc4..7fc4bb2efd 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -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"), ); diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts new file mode 100644 index 0000000000..c978e7690e --- /dev/null +++ b/apps/web/src/lib/archivedThreadsState.ts @@ -0,0 +1,105 @@ +import { useAtomValue } from "@effect/atom-react"; +import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts"; +import { Cause, Effect, Option } from "effect"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { useCallback, useMemo } from "react"; + +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(); + +function makeArchivedThreadsEnvironmentKey(environmentIds: ReadonlyArray): string { + return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR); +} + +function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray { + 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> => { + 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, 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): { + readonly snapshots: ReadonlyArray; + 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, + }; +} diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index b36ffb0ab2..2f1ca624d9 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -143,6 +143,9 @@ export interface WsRpcClient { readonly dispatchCommand: RpcUnaryMethod; readonly getTurnDiff: RpcUnaryMethod; readonly getFullThreadDiff: RpcUnaryMethod; + readonly getArchivedShellSnapshot: RpcUnaryNoArgMethod< + typeof ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot + >; readonly subscribeShell: RpcStreamMethod; readonly subscribeThread: RpcInputStreamMethod; }; @@ -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]({}), diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index abe8af5022..58894adac1 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -55,6 +55,7 @@ import type { OrchestrationGetFullThreadDiffResult, OrchestrationGetTurnDiffInput, OrchestrationGetTurnDiffResult, + OrchestrationShellSnapshot, OrchestrationShellStreamItem, OrchestrationSubscribeThreadInput, OrchestrationThreadStreamItem, @@ -544,6 +545,7 @@ export interface EnvironmentApi { getFullThreadDiff: ( input: OrchestrationGetFullThreadDiffInput, ) => Promise; + getArchivedShellSnapshot: () => Promise; subscribeShell: ( callback: (event: OrchestrationShellStreamItem) => void, options?: { diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 44d840d149..401928171c 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -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, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index eb72b14f9e..705621b5da 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -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, ); From 932df4ed17ff9465053e3a1bbfdd6d2ba23500f0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 8 May 2026 16:17:29 -0700 Subject: [PATCH 3/4] fix(ssh): fix reconnect issues and node binary path resolution (#2504) Co-authored-by: Julius Marminge Co-authored-by: codex --- REMOTE.md | 37 +++ apps/desktop/src/main.ts | 7 +- .../src/provider/Layers/ClaudeProvider.ts | 4 +- .../src/provider/Layers/OpenCodeProvider.ts | 4 +- apps/server/src/provider/cliVersion.test.ts | 17 -- apps/server/src/provider/cliVersion.ts | 123 ---------- .../src/provider/providerMaintenance.ts | 5 +- .../textGeneration/CursorTextGeneration.ts | 2 +- .../textGeneration/OpenCodeTextGeneration.ts | 2 +- .../src/textGeneration/TextGenerationUtils.ts | 50 +--- packages/shared/package.json | 4 + packages/shared/src/schemaJson.test.ts | 31 +++ packages/shared/src/schemaJson.ts | 48 ++++ packages/shared/src/semver.test.ts | 58 +++++ packages/shared/src/semver.ts | 216 ++++++++++++++++++ packages/ssh/src/tunnel.test.ts | 99 +++++++- packages/ssh/src/tunnel.ts | 216 ++++++++++++++++-- 17 files changed, 701 insertions(+), 222 deletions(-) delete mode 100644 apps/server/src/provider/cliVersion.test.ts delete mode 100644 apps/server/src/provider/cliVersion.ts create mode 100644 packages/shared/src/schemaJson.test.ts create mode 100644 packages/shared/src/semver.test.ts create mode 100644 packages/shared/src/semver.ts diff --git a/REMOTE.md b/REMOTE.md index 61a1cc3b5c..56510e6289 100644 --- a/REMOTE.md +++ b/REMOTE.md @@ -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//`, 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 user@example.com '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. diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f71ff1fbe6..0bc1badff2 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -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, }; }; diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 27bff1b0b6..f787129af8 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -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 = [ ]; 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( diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index b247e8586c..dea95c990d 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -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, diff --git a/apps/server/src/provider/cliVersion.test.ts b/apps/server/src/provider/cliVersion.test.ts deleted file mode 100644 index ffb42cf5cc..0000000000 --- a/apps/server/src/provider/cliVersion.test.ts +++ /dev/null @@ -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); - }); -}); diff --git a/apps/server/src/provider/cliVersion.ts b/apps/server/src/provider/cliVersion.ts deleted file mode 100644 index 6308a2ff52..0000000000 --- a/apps/server/src/provider/cliVersion.ts +++ /dev/null @@ -1,123 +0,0 @@ -interface ParsedCliSemver { - readonly major: number; - readonly minor: number; - readonly patch: number; - readonly prerelease: ReadonlyArray; -} - -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; -} diff --git a/apps/server/src/provider/providerMaintenance.ts b/apps/server/src/provider/providerMaintenance.ts index a733506766..7f5e9d94dc 100644 --- a/apps/server/src/provider/providerMaintenance.ts +++ b/apps/server/src/provider/providerMaintenance.ts @@ -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, diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts index 22b4924a19..c4ef1af21d 100644 --- a/apps/server/src/textGeneration/CursorTextGeneration.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.ts @@ -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, diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts index df68ca3fee..b865b2e5ef 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts @@ -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, diff --git a/apps/server/src/textGeneration/TextGenerationUtils.ts b/apps/server/src/textGeneration/TextGenerationUtils.ts index f1bc0cb9dd..a786f81b2c 100644 --- a/apps/server/src/textGeneration/TextGenerationUtils.ts +++ b/apps/server/src/textGeneration/TextGenerationUtils.ts @@ -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() ?? ""; diff --git a/packages/shared/package.json b/packages/shared/package.json index f410a98b38..c499bf3c6e 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -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" diff --git a/packages/shared/src/schemaJson.test.ts b/packages/shared/src/schemaJson.test.ts new file mode 100644 index 0000000000..7f3db7034b --- /dev/null +++ b/packages/shared/src/schemaJson.test.ts @@ -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"); + }); +}); diff --git a/packages/shared/src/schemaJson.ts b/packages/shared/src/schemaJson.ts index 32abdcd723..0d879913eb 100644 --- a/packages/shared/src/schemaJson.ts +++ b/packages/shared/src/schemaJson.ts @@ -97,6 +97,54 @@ export const prettyJsonString = SchemaGetter.parseJson().compose( export const fromLenientJson = (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. * diff --git a/packages/shared/src/semver.test.ts b/packages/shared/src/semver.test.ts new file mode 100644 index 0000000000..b3c629740a --- /dev/null +++ b/packages/shared/src/semver.test.ts @@ -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); + }); +}); diff --git a/packages/shared/src/semver.ts b/packages/shared/src/semver.ts new file mode 100644 index 0000000000..de21376450 --- /dev/null +++ b/packages/shared/src/semver.ts @@ -0,0 +1,216 @@ +interface ParsedSemver { + readonly major: number; + readonly minor: number; + readonly patch: number; + readonly prerelease: ReadonlyArray; +} + +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; + } + }); + }); + }; diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 0219396e7d..80e684d861 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -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 { 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" +} + `), ), ); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index f0e189efae..5ee5c68477 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -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 = ( + stdout: string, + decode: (input: string) => Effect.Effect, +): Effect.Effect => + 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({ From 34ec8a86fb3a76f5d65e6805dcf98d785536b6f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 8 May 2026 16:41:55 -0700 Subject: [PATCH 4/4] [codex] add configurable automatic git fetch interval (#2605) Co-authored-by: Julius Marminge Co-authored-by: Cursor Agent Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com> --- .../Layers/ProjectionSnapshotQuery.ts | 2 +- .../provider/Layers/ProviderRegistry.test.ts | 14 +- apps/server/src/server.test.ts | 2 +- apps/server/src/serverSettings.test.ts | 3 + apps/server/src/serverSettings.ts | 104 ++++++++------ apps/server/src/vcs/GitVcsDriverCore.test.ts | 59 ++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 6 + .../src/vcs/VcsStatusBroadcaster.test.ts | 26 ++++ apps/server/src/vcs/VcsStatusBroadcaster.ts | 41 ++++-- apps/server/src/ws.ts | 13 +- apps/web/src/components/ChatView.browser.tsx | 7 +- .../components/KeybindingsToast.browser.tsx | 11 +- .../settings/SettingsPanels.browser.tsx | 43 +++++- .../components/settings/SettingsPanels.tsx | 7 + .../settings/SourceControlSettings.tsx | 132 ++++++++++++++++-- apps/web/src/lib/archivedThreadsState.ts | 5 +- apps/web/src/rpc/wsTransport.test.ts | 7 +- packages/contracts/src/baseSchemas.ts | 12 +- .../contracts/src/providerInstance.test.ts | 16 +++ packages/contracts/src/settings.test.ts | 59 ++++++++ packages/contracts/src/settings.ts | 37 +++-- packages/shared/src/serverSettings.ts | 17 +-- 22 files changed, 517 insertions(+), 106 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index cf6cb7beaa..f326a524f9 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -1601,7 +1601,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { hasActionableProposedPlan: row.hasActionableProposedPlan > 0, }), ), - updatedAt: updatedAt ?? new Date(0).toISOString(), + updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z", }; return yield* decodeShellSnapshot(snapshot).pipe( diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index b0d6ef8973..455cac1eb0 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -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, diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 857da7aebe..95a2e4e91a 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -635,7 +635,7 @@ const buildAppUnderTest = (options?: { snapshotSequence: 0, projects: [], threads: [], - updatedAt: new Date(0).toISOString(), + updatedAt: "1970-01-01T00:00:00.000Z", }), getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), getProjectShellById: () => Effect.succeed(Option.none()), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 93243b21c6..7af27f0b7c 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -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())), ); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 46d5615f11..5ea2e03813 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -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 => + encodeServerSettings(settings).pipe( + Effect.flatMap(decodeServerSettings), + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath: "", + 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( - 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(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: "", - 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 = new Set(["textGenerationModelSelection"]); +const ATOMIC_SETTINGS_KEYS: ReadonlySet = 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: "", - 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); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 558d6ef296..00f40a69aa 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -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(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index b8199c33b4..3a05dea633 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -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({ @@ -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); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 90567d437d..ccadf9a921 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -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, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 4c431fd007..c93b729173 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -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; +} + export interface VcsStatusBroadcasterShape { readonly getStatus: ( input: VcsStatusInput, @@ -54,6 +58,7 @@ export interface VcsStatusBroadcasterShape { readonly refreshStatus: (cwd: string) => Effect.Effect; readonly streamStatus: ( input: VcsStatusInput, + options?: StreamStatusOptions, ) => Stream.Stream; } @@ -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, + ) => { + 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, ) { 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); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d3c891b2bb..001c9baff9 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -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; @@ -981,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", }, diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index f51780abf5..bb62d8edbc 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -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; @@ -955,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 { @@ -1662,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => { { version: 1, type: "snapshot", - config: fixture.serverConfig, + config: encodeServerConfig(fixture.serverConfig), }, ]; } diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 6bb8be2c25..611eaf572d 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -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 { 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), }, ]; } diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 5dfc1bac04..4abefc5425 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -1256,10 +1256,47 @@ describe("SourceControlSettingsPanel discovery states", () => { , ); - 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( + + + , + ); + + 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", () => { , ); - 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", () => { , ); - await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument(); + await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled(); expect(calls).toBe(1); }); }); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index def96b9ba9..505be5c73f 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -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 { @@ -407,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"] : []), @@ -430,6 +435,7 @@ export function useSettingsRestore(onRestored?: () => void) { settings.defaultThreadEnvMode, settings.diffIgnoreWhitespace, settings.diffWordWrap, + settings.automaticGitFetchInterval, settings.enableAssistantStreaming, settings.sidebarThreadPreviewCount, settings.timestampFormat, @@ -455,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, diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 59c6e4aa63..0cda0c1b86 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -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> = { }; 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 | null { return Option.getOrNull(value); @@ -146,7 +169,7 @@ function itemSummary({ } if (item.status !== "available") { - return Not available on this server — {item.installHint}; + return Not available on this server: {item.installHint}; } 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 (
-

+ {item.label} -

+ {version ? {version} : null} {isVcsNotReady(item) ? ( @@ -231,12 +258,100 @@ function DiscoveryItemRow({

+ {hasDetails ? ( + + ) : null} {!isVcsNotReady(item) ? ( ) : null}
+ + {hasDetails ? ( + + +
{children}
+
+
+ ) : null} +
+ ); +} + +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 ( +
+
+
+
+ Fetch interval + + {canResetFetchInterval ? ( + + updateSettings({ + automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval, + }) + } + /> + ) : null} + +
+

+ 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. +

+
+
+ + updateSettings({ + automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)), + }) + } + > + + + + + + + seconds +
+
); } @@ -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 ? ( {result.versionControlSystems.map((item) => ( - + + {item.kind === "git" ? : undefined} + ))} ) : null} diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts index c978e7690e..1fe91455fc 100644 --- a/apps/web/src/lib/archivedThreadsState.ts +++ b/apps/web/src/lib/archivedThreadsState.ts @@ -1,9 +1,10 @@ import { useAtomValue } from "@effect/atom-react"; import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts"; -import { Cause, Effect, Option } from "effect"; 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"; diff --git a/apps/web/src/rpc/wsTransport.test.ts b/apps/web/src/rpc/wsTransport.test.ts index 6e69acbb55..aeb5496f51 100644 --- a/apps/web/src/rpc/wsTransport.test.ts +++ b/apps/web/src/rpc/wsTransport.test.ts @@ -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), }, }), ); diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 5baf426a8c..614ea5131f 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -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)); diff --git a/packages/contracts/src/providerInstance.test.ts b/packages/contracts/src/providerInstance.test.ts index 1a2ffbb995..272e4a70ef 100644 --- a/packages/contracts/src/providerInstance.test.ts +++ b/packages/contracts/src/providerInstance.test.ts @@ -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", diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 8c29282792..39695fe3b0 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -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"); + }); +}); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 26a1a171cf..2d115eed98 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -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( diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 6427129b3c..1bbf466f60 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -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; }