From 89017c15a0af177645fee044226d9d794b028051 Mon Sep 17 00:00:00 2001 From: viktorce Date: Thu, 19 Nov 2026 22:47:56 +0000 Subject: [PATCH 1/5] fix(client-runtime): an unexpected failure no longer stops the reconnect loop for good The connection supervisor's reconnect loop ran as one forked fiber with nothing around it. A defect or a stray interruption in it ended the fiber silently. The state stayed where it was and Retry did nothing. One route real code takes: a session's `closed` can fail with a cause that mixes a failure with an interruption, and `exitUnlessInterrupted` turned any cause holding an interruption into an interruption of the loop. The loop now survives all of that: - `runAttempt` uses `Effect.exit` where it used `exitUnlessInterrupted`, so a stray interruption becomes a failed attempt that keeps whether the session was live and stable. - A defect elsewhere in an attempt is caught around the attempt, logged, and retried on the normal backoff ladder. - A defect from closing an attempt's scope is logged as a failed release, and the attempt's outcome stands. - The generation number advances where the session is published as connected, so no lost outcome or restart gives two sessions the same number. - A defect in the loop outside an attempt is logged, and the loop restarts after the longest retry delay or the next signal. - The shutdown finalizer is registered before the fibers, so closing a supervisor does not look like a failure to the loop. A failure inside the restart handler itself still ends the loop, after one log line. The supervisor's other background fibers are unchanged. --- .../src/connection/supervisor.test.ts | 397 +++++++++++++++++- .../src/connection/supervisor.ts | 213 ++++++---- ...ig-stream-failing-while-interrupted.e2e.ts | 85 ++++ 3 files changed, 589 insertions(+), 106 deletions(-) create mode 100644 scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 46b9757d0cd83..b2d67a38865c6 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -6,14 +6,19 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import { RelayClientTracer } from "@t3tools/shared/relayTracing"; +import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; +import * as References from "effect/References"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Clock from "effect/Clock"; @@ -167,6 +172,18 @@ function awaitState( ); } +function recordLogs(logs: Array, annotations?: Array) { + return Logger.layer( + [ + Logger.make(({ message, fiber }) => { + logs.push(message); + annotations?.push(fiber.getRef(References.CurrentLogAnnotations)); + }), + ], + { mergeWithExisting: false }, + ); +} + const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: { readonly networkStatus?: NetworkStatus; readonly prepare?: ( @@ -174,6 +191,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: target: ConnectionTarget, ) => Effect.Effect; readonly ready?: (attempt: number) => Effect.Effect; + readonly release?: (attempt: number) => Effect.Effect; readonly probe?: (attempt: number) => Effect.Effect; readonly configEvents?: Stream.Stream | undefined; readonly initialConfig?: (attempt: number) => Effect.Effect; @@ -245,7 +263,10 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: inboundFrames: options?.inboundFrames ?? Effect.succeed(0), closed: Deferred.await(closed), } satisfies RpcSession.RpcSession), - () => Ref.update(releaseCount, (count) => count + 1), + () => + Ref.update(releaseCount, (count) => count + 1).pipe( + Effect.andThen(options?.release?.(attempt) ?? Effect.void), + ), ); yield* reportProgress({ stage: "synchronizing", prepared }); @@ -308,12 +329,12 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: reason, })), closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* ( - error = transient("Session closed."), + exit: Exit.Exit = Exit.fail(transient("Session closed.")), ) { const sessions = yield* Ref.get(closedSessions); const latest = sessions.at(-1); if (latest) { - yield* Deferred.fail(latest, error); + yield* Deferred.done(latest, exit); } }), }; @@ -581,9 +602,11 @@ describe("EnvironmentSupervisor", () => { ? Effect.die(new Error("Native transport defect.")) : Effect.succeed(PREPARED_CONNECTION), }); + const logs: unknown[] = []; + const annotations: unknown[] = []; const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, { initiallyDesired: true, - }).pipe(Effect.provide(harness.dependencies)); + }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs, annotations)))); const failed = yield* awaitState( supervisor.state, @@ -596,6 +619,10 @@ describe("EnvironmentSupervisor", () => { message: "Test environment connection failed unexpectedly.", }, }); + expect(logs).toEqual([["Connection attempt failed with an unexpected defect."]]); + expect(annotations).toMatchObject([ + { "environment.id": RELAY_TARGET.environmentId, errorName: "Error" }, + ]); yield* TestClock.adjust("3 seconds"); yield* awaitState(supervisor.state, (state) => state.phase === "connected"); @@ -603,42 +630,380 @@ describe("EnvironmentSupervisor", () => { }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("explicit retry interrupts the current backoff", () => + it.effect.each([ + { + label: "the attempt's network-status read dies", + firstPrepare: Effect.never, + statusDefect: true, + log: "Connection attempt failed with an unexpected defect.", + }, + { + label: "an attempt interrupts itself", + firstPrepare: Effect.interrupt, + statusDefect: false, + log: "Connection attempt failed with an unexpected interruption.", + }, + ])("retries after $label", ({ firstPrepare, statusDefect, log }) => + Effect.gen(function* () { + const harness = yield* makeHarness({ + prepare: (attempt) => (attempt === 1 ? firstPrepare : Effect.succeed(PREPARED_CONNECTION)), + }); + const statusReads = yield* Ref.make(0); + const logs: unknown[] = []; + const annotations: Array> = []; + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService( + Connectivity.Connectivity, + Connectivity.Connectivity.of({ + // The supervisor reads once at startup; the second read belongs to the first attempt. + status: Ref.updateAndGet(statusReads, (count) => count + 1).pipe( + Effect.flatMap((count) => + statusDefect && count === 2 + ? Effect.die(new Error("Platform connectivity defect.")) + : Effect.succeed("online" as const), + ), + ), + changes: Stream.never, + }), + ), + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs, annotations))), + ); + + const failed = yield* awaitState( + supervisor.state, + (state) => state.phase === "backoff" && state.attempt === 1, + ); + expect(failed).toMatchObject({ + generation: 0, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + }); + expect(logs).toEqual([[log]]); + expect(Object.hasOwn(annotations[0]!, "errorType")).toBe(statusDefect); + + yield* TestClock.adjust("999 millis"); + expect(yield* Ref.get(harness.prepareCount)).toBe(1); + yield* TestClock.adjust("2 seconds"); + yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(harness.prepareCount)).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each([ + { + label: "is interrupted", + closed: Exit.interrupt(), + releaseDefect: false, + log: "Connection attempt failed with an unexpected interruption.", + }, + { + label: "fails and dies while interrupted", + closed: Exit.failCause( + Cause.combine( + Cause.combine( + Cause.fail(transient("Session closed.")), + Cause.die(new Error("Session closed defect.")), + ), + Cause.interrupt(), + ), + ), + releaseDefect: false, + log: "Connection attempt failed with an unexpected defect.", + }, + { + label: "fails while interrupted", + closed: Exit.failCause( + Cause.combine(Cause.fail(transient("Session closed.")), Cause.interrupt()), + ), + releaseDefect: false, + log: null, + }, + { + label: "closes while its release defects", + closed: Exit.fail(transient("Session closed.")), + releaseDefect: true, + log: "Connection release failed with an unexpected defect.", + }, + ])("reconnects soon after a stable session $label", ({ closed, releaseDefect, log }) => Effect.gen(function* () { const harness = yield* makeHarness({ prepare: (attempt) => attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), + release: (session) => + releaseDefect && session === 1 + ? Effect.die(new Error("Session release defect.")) + : Effect.void, }); + const logs: unknown[] = []; const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { initiallyDesired: true, - }).pipe(Effect.provide(harness.dependencies)); + }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs)))); yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); - yield* supervisor.retryNow; + yield* TestClock.adjust("2 seconds"); + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* TestClock.adjust("1 minute"); + yield* harness.closeLatestSession(closed); + const lost = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); + expect(logs).toEqual(log === null ? [] : [[log]]); + expect(lost).toMatchObject({ phase: "backoff", generation: 1 }); + expect(lost.retryAt).toBeLessThanOrEqual((yield* Clock.currentTimeMillis) + 250); + + yield* TestClock.adjust("250 millis"); + const replaced = yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(replaced.generation).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each([ + { + label: "its attempt defects after its session went live", + closed: Exit.interrupt(), + releaseDefect: false, + lost: { phase: "backoff", generation: 1, lastFailure: null }, + // The earlier failed attempt still counts, so this is the ladder's second step. + soonestMs: 2000, + latestMs: 4000, + }, + { + label: "logging its release defect dies", + closed: Exit.fail(transient("Session closed.")), + releaseDefect: true, + lost: { phase: "backoff", generation: 1 }, + soonestMs: 300_000, + latestMs: 300_000, + }, + ])( + "does not reuse a live session's generation when $label", + ({ closed, releaseDefect, lost, soonestMs, latestMs }) => + Effect.gen(function* () { + const harness = yield* makeHarness({ + prepare: (attempt) => + attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), + release: (session) => + releaseDefect && session === 1 + ? Effect.die(new Error("Session release defect.")) + : Effect.void, + }); + let logCalls = 0; + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provide( + Layer.merge( + harness.dependencies, + Logger.layer( + [ + // The first log line throws, which is how each row injects its defect. + Logger.make(() => { + logCalls += 1; + if (logCalls === 1) throw new Error("Logger defect."); + }), + ], + { mergeWithExisting: false }, + ), + ), + ), + ); + + yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + yield* TestClock.adjust("2 seconds"); + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* harness.closeLatestSession(closed); + const backoff = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(logCalls).toBe(2); + expect(backoff).toMatchObject(lost); + const retryInMs = (backoff.retryAt ?? 0) - (yield* Clock.currentTimeMillis); + expect(retryInMs).toBeGreaterThanOrEqual(soonestMs); + expect(retryInMs).toBeLessThanOrEqual(latestMs); + + yield* TestClock.adjust(`${latestMs} millis`); + const replaced = yield* awaitState( + supervisor.state, + (state) => state.phase === "connected", + ); + expect(replaced.generation).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("keeps a released session's outcome", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + release: () => Effect.die(new Error("Session release defect.")), + }); + const logs: unknown[] = []; + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs)))); + yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + yield* supervisor.disconnect; + const released = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); + expect(released.phase).toBe("available"); + expect(logs).toEqual([["Connection release failed with an unexpected defect."]]); + }).pipe(Effect.provide(TestClock.layer())), + ); - expect(yield* Ref.get(harness.prepareCount)).toBe(2); - }), + it.effect("restarts the loop after a defect outside an attempt", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const logs: unknown[] = []; + let randomReads = 0; + const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService(Random.Random, { + // Both session losses below die here, so the second reaches the restart handler again. + nextDoubleUnsafe: () => { + randomReads += 1; + if (randomReads <= 2) throw new Error("Random defect."); + return 1 - Number.EPSILON; + }, + nextIntUnsafe: () => 0, + }), + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs))), + ); + + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* harness.closeLatestSession(); + const restarted = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(logs).toEqual([["Connection loop failed with an unexpected defect."]]); + expect(restarted).toMatchObject({ + attempt: 1, + generation: 1, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + retryAt: (yield* Clock.currentTimeMillis) + 300_000, + }); + + yield* TestClock.adjust("299999 millis"); + expect(yield* Ref.get(harness.sessionCount)).toBe(1); + yield* TestClock.adjust("1 millis"); + const reconnected = yield* awaitState( + supervisor.state, + (state) => state.phase === "connected", + ); + expect(reconnected.generation).toBe(2); + + yield* harness.setNetworkStatus("offline"); + yield* harness.closeLatestSession(); + const offline = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); + expect(offline).toMatchObject({ + phase: "offline", + attempt: 1, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + }); + + yield* supervisor.retryNow; + const retried = yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(retried.generation).toBe(3); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each(["connecting", "connected"] as const)( + "stops attempting when its scope closes while %s", + (phase) => + Effect.gen(function* () { + const preparing = yield* Deferred.make(); + const harness = yield* makeHarness({ + prepare: () => + Deferred.succeed(preparing, undefined).pipe( + Effect.andThen( + phase === "connected" ? Effect.succeed(PREPARED_CONNECTION) : Effect.never, + ), + ), + }); + const logs: unknown[] = []; + const scope = yield* Scope.make(); + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs))), + Scope.provide(scope), + ); + + yield* Deferred.await(preparing); + yield* awaitState(supervisor.state, (state) => state.phase === phase); + // Yielding between finalizers lets the loop run if the queue shuts down before its interrupt. + yield* Scope.close(scope, Exit.void).pipe( + Effect.provideService(References.MaxOpsBeforeYield, 1), + ); + yield* TestClock.adjust("10 minutes"); + expect(logs).toEqual([]); + expect(yield* Ref.get(harness.prepareCount)).toBe(1); + }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("keeps blocked failures idle until an external signal requests another attempt", () => + it.effect("explicit retry interrupts the current backoff", () => Effect.gen(function* () { const harness = yield* makeHarness({ prepare: (attempt) => - attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION), + attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), }); const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { initiallyDesired: true, }).pipe(Effect.provide(harness.dependencies)); - yield* awaitState(supervisor.state, (state) => state.phase === "blocked"); - yield* TestClock.adjust("1 hour"); - expect(yield* Ref.get(harness.prepareCount)).toBe(1); - + yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); yield* supervisor.retryNow; yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(harness.prepareCount)).toBe(2); - }).pipe(Effect.provide(TestClock.layer())), + }), + ); + + it.effect.each([ + { label: "fails", cause: Cause.fail(blocked()) }, + { + label: "fails while interrupted", + cause: Cause.combine(Cause.fail(blocked()), Cause.interrupt()), + }, + ])( + "keeps a blocked host that $label idle until an external signal requests another attempt", + ({ cause }) => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const driver = yield* ConnectionDriver.ConnectionDriver.pipe( + Effect.provide(harness.dependencies), + ); + const connects = yield* Ref.make(0); + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + // The driver keeps only the typed error of a failed route, so the cause is mixed here. + Effect.provideService(ConnectionDriver.ConnectionDriver, { + ...driver, + connect: (entry, reportProgress) => + Ref.updateAndGet(connects, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 ? Effect.failCause(cause) : driver.connect(entry, reportProgress), + ), + ), + }), + Effect.provide(harness.dependencies), + ); + + const failed = yield* awaitState(supervisor.state, (state) => state.lastFailure !== null); + expect(failed).toMatchObject({ + phase: "blocked", + lastFailure: { _tag: "ConnectionBlockedError", detail: "Authentication required." }, + }); + yield* TestClock.adjust("1 hour"); + expect(yield* Ref.get(connects)).toBe(1); + + yield* supervisor.retryNow; + yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(connects)).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("retries a blocked connection when platform credentials change", () => diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 58411d795b7fc..79e6802805205 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -149,16 +149,6 @@ type EstablishmentEvent = | { readonly _tag: "Interrupted"; readonly resetRetry: boolean } | { readonly _tag: "TimedOut" }; -function exitUnlessInterrupted( - effect: Effect.Effect, -): Effect.Effect, never, R> { - return Effect.matchCauseEffect(effect, { - onFailure: (cause) => - Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)), - onSuccess: (value) => Effect.succeed(Exit.succeed(value)), - }); -} - export interface EnvironmentSupervisorOptions { readonly initiallyDesired?: boolean; readonly learnRoutes?: (input: { @@ -247,37 +237,27 @@ function connectingState( }; } -function failureFromExit( +function failureFromCause( target: ConnectionTarget, - exit: Exit.Exit, + cause: Cause.Cause, established: boolean, stable: boolean, -): AttemptOutcome { - if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) { - return { _tag: "Interrupted", established, stable, resetRetry: false }; - } - const typedFailure = exit.cause.reasons.find(Cause.isFailReason); - if (typedFailure) { - return { - _tag: "Failure", - established, - stable, - failure: typedFailure.error, - }; - } +) { return { _tag: "Failure", established, stable, - failure: { - error: new ConnectionTransientError({ - reason: "transport", - ...translatableDetail( - msg("{host} connection failed unexpectedly.", { host: target.label }), - ), - }), - attemptSpan: Option.none(), - }, + failure: cause.reasons.find(Cause.isFailReason)?.error ?? unexpectedFailure(target), + } satisfies AttemptOutcome; +} + +function unexpectedFailure(target: ConnectionTarget): TracedAttemptFailure { + return { + error: new ConnectionTransientError({ + reason: "transport", + ...translatableDetail(msg("{host} connection failed unexpectedly.", { host: target.label })), + }), + attemptSpan: Option.none(), }; } @@ -496,9 +476,27 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( }), ); + const logUnexpectedFailure = ( + failed: "attempt" | "release" | "loop", + cause: Cause.Cause, + ) => { + const died = cause.reasons.find(Cause.isDieReason); + if (!died && cause.reasons.some(Cause.isFailReason)) return Effect.void; + return Effect.logError( + `Connection ${failed} failed with an unexpected ${died ? "defect" : "interruption"}.`, + ).pipe( + Effect.annotateLogs({ + "environment.id": target.environmentId, + "environment.label": target.label, + "cause.reason_count": cause.reasons.length, + ...(died ? safeErrorLogAttributes(died.defect) : {}), + }), + ); + }; + const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, progress: ConnectionDriver.ConnectionDriverProgress, ) { @@ -506,13 +504,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( yield* SubscriptionRef.set(prepared, Option.some(progress.prepared)); } yield* setState( - connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage), + connectingState(yield* Ref.get(intent), nextGeneration, attempt, lastFailure, progress.stage), ); }); const establishConnection = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, synchronizedRoutes: Ref.Ref, ) { @@ -520,7 +518,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( (progress.stage === "synchronizing" ? Ref.update(synchronizedRoutes, (count) => count + 1) : Effect.void - ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))), + ).pipe(Effect.andThen(reportProgress(attempt, nextGeneration, lastFailure, progress))), ); }); @@ -559,7 +557,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Scope.Scope >, attempt: number, - generation: number, + nextGeneration: number, pendingRetry: Option.Option, ) => { // The span must end with the ConnectionAttemptError itself: the exporter @@ -572,7 +570,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( "environment.id": target.environmentId, "environment.target.kind": target._tag, "connection.attempt": attempt, - "connection.generation": generation, + "connection.generation": nextGeneration, "connection.retry.failure_count": Option.match(pendingRetry, { onNone: () => 0, onSome: (retry) => retry.failureCount, @@ -599,20 +597,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const establishTracedConnection = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, pendingRetry: Option.Option, synchronizedRoutes: Ref.Ref, ) { if (usesRelay) { return yield* traceRelayEstablishment( - establishConnection(attempt, generation, lastFailure, synchronizedRoutes), + establishConnection(attempt, nextGeneration, lastFailure, synchronizedRoutes), attempt, - generation, + nextGeneration, pendingRetry, ); } - return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe( + return yield* establishConnection( + attempt, + nextGeneration, + lastFailure, + synchronizedRoutes, + ).pipe( Effect.map((lease) => ({ attemptSpan: Option.none(), lease, @@ -946,9 +949,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } }); + // Advanced as a session goes live and kept across loop restarts, so no two sessions share one. + let generation = 0; const runAttempt = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, pendingRetry: Option.Option, ignoreOffline: boolean, @@ -957,10 +962,10 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( yield* SubscriptionRef.set(prepared, Option.none()); const synchronizedRoutes = yield* Ref.make(0); const establishment = yield* Effect.raceAllFirst([ - exitUnlessInterrupted( + Effect.exit( establishTracedConnection( attempt, - generation, + nextGeneration, lastFailure, pendingRetry, synchronizedRoutes, @@ -1031,22 +1036,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } satisfies AttemptOutcome; } if (Exit.isFailure(establishment.exit)) { - const isUnexpectedDefect = - !Cause.hasInterruptsOnly(establishment.exit.cause) && - !establishment.exit.cause.reasons.some(Cause.isFailReason); - const outcome = failureFromExit(target, establishment.exit, false, false); - if (isUnexpectedDefect) { - const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect; - yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe( - Effect.annotateLogs({ - "environment.id": target.environmentId, - "environment.label": target.label, - "cause.reason_count": establishment.exit.cause.reasons.length, - ...safeErrorLogAttributes(defect), - }), - ); - } - return outcome; + yield* logUnexpectedFailure("attempt", establishment.exit.cause); + return failureFromCause(target, establishment.exit.cause, false, false); } const active = establishment.exit.value; @@ -1075,7 +1066,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const connectedLease: ConnectedLease = { ...active.lease, activeRoute: routes.find((route) => connectionRouteId(route.target) === activeRouteId), - generation, + generation: nextGeneration, }; const refusedRouteIds = yield* Ref.updateAndGet(refusedRoutes, (known) => mergeRefusedRoutes( @@ -1086,6 +1077,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( ), ); const connectedAt = yield* Clock.currentTimeMillis; + generation = nextGeneration; yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared)); yield* SubscriptionRef.set(session, Option.some(connectedLease.session)); if (options?.learnRoutes !== undefined) { @@ -1097,7 +1089,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( phase: "connected", stage: null, attempt, - generation, + generation: nextGeneration, lastFailure: null, retryAt: null, refusedRouteIds, @@ -1116,7 +1108,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( attemptSpan: active.attemptSpan, })), ), - ).pipe(exitUnlessInterrupted); + ).pipe(Effect.exit); const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt; if (Exit.isSuccess(connectedExit)) { return { @@ -1126,27 +1118,26 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( resetRetry: connectedExit.value, } satisfies AttemptOutcome; } - const outcome = failureFromExit( + yield* logUnexpectedFailure("attempt", connectedExit.cause); + const outcome = failureFromCause( target, - connectedExit, + connectedExit.cause, true, connectedForMs >= BACKOFF_RESET_AFTER_MS, ); - if (outcome._tag === "Failure") { - yield* Effect.void.pipe( - Effect.withSpan("EnvironmentSupervisor.connectionLost", { - root: true, - attributes: { - "environment.id": target.environmentId, - "environment.label": target.label, - "environment.target.kind": target._tag, - "connection.connected_ms": connectedForMs, - "connection.failure.reason": outcome.failure.error.reason, - "connection.failure.detail": outcome.failure.error.detail, - }, - }), - ); - } + yield* Effect.void.pipe( + Effect.withSpan("EnvironmentSupervisor.connectionLost", { + root: true, + attributes: { + "environment.id": target.environmentId, + "environment.label": target.label, + "environment.target.kind": target._tag, + "connection.connected_ms": connectedForMs, + "connection.failure.reason": outcome.failure.error.reason, + "connection.failure.detail": outcome.failure.error.detail, + }, + }), + ); return outcome; }, Effect.ensuring(clearLease)); @@ -1185,7 +1176,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( // Approval waits count as attempts but not toward backoff, so a later outage starts low. let backoffFailures = 0; let approvalWaits = 0; - let generation = 0; let latestFailure: ConnectionAttemptError | null = null; let pendingRetry = Option.none(); const resetRetryLadder = () => { @@ -1229,13 +1219,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const attempt = failureCount + 1; const nextGeneration = generation + 1; - const outcome: AttemptOutcome = yield* Effect.scoped( - runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, ignoreOffline), + const outcome: AttemptOutcome = yield* Effect.acquireUseRelease( + Scope.make(), + (scope) => + runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, ignoreOffline).pipe( + Scope.provide(scope), + Effect.catchCause((cause) => + logUnexpectedFailure("attempt", cause).pipe( + Effect.as(failureFromCause(target, cause, generation === nextGeneration, false)), + ), + ), + ), + (scope, exit) => + Scope.close(scope, exit).pipe( + Effect.catchCause((cause) => logUnexpectedFailure("release", cause)), + ), ); replacing = false; const failedProbe = yield* Ref.getAndSet(probeUnanswered, false); if (outcome.established) { - generation = nextGeneration; // A session came up, so no earlier failure describes the connection. // Losing a live session is not a failed connection either, for example // a socket the OS killed while the app was suspended: its replacement @@ -1327,6 +1329,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } }); + // Registered before the fibers below so closing the scope interrupts them first. + // A loop still running when the queue shuts down would report that as a failure. + yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease))); yield* connectivity.changes.pipe( Stream.runForEach((network) => Ref.modify(intent, (current) => { @@ -1362,7 +1367,37 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Effect.forever, Effect.forkScoped, ); - yield* run().pipe(Effect.forkScoped); + // A restarted loop has forgotten its retry ladder, so it waits out the + // ladder's ceiling unless a signal cuts the wait short. + yield* run().pipe( + Effect.catchCause((cause) => + Effect.gen(function* () { + yield* logUnexpectedFailure("loop", cause); + const currentIntent = yield* Ref.get(intent); + const lastFailure = unexpectedFailure(target).error; + yield* setState( + !currentIntent.desired + ? availableState(currentIntent, generation) + : currentIntent.network === "offline" + ? offlineState(currentIntent, generation, 1, lastFailure) + : { + desired: true, + network: currentIntent.network, + phase: "backoff", + stage: null, + attempt: 1, + generation, + lastFailure, + retryAt: (yield* Clock.currentTimeMillis) + RETRY_MAX_DELAY_MS, + refusedRouteIds: NO_REFUSED_ROUTES, + }, + ); + yield* waitForRetrySignal(RETRY_MAX_DELAY_MS); + }), + ), + Effect.forever, + Effect.forkScoped, + ); const connect = Ref.update(intent, (current) => ({ ...current, @@ -1385,8 +1420,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Effect.withSpan("EnvironmentSupervisor.retryNow"), ); - yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease))); - return EnvironmentSupervisor.of({ target, state, diff --git a/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts b/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts new file mode 100644 index 0000000000000..8e6a2606c1ba9 --- /dev/null +++ b/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts @@ -0,0 +1,85 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { runPromise, test, WEB } from "./t3.ts"; + +interface Fault { + readonly failConfigStreamWhileInterrupted: () => boolean; +} + +test( + "The app reconnects after its config stream fails while interrupted", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Earlier work", + messages: ["Print the JSON"], + model: "command-output", + }); + // Injected fault: the page hands the app one server frame that ends the config + // subscription with a typed failure and an interruption in the same cause. + await browser.addInitScript(() => { + let deliver: (() => void) | null = null; + const NativeWebSocket = window.WebSocket; + window.WebSocket = class extends NativeWebSocket { + override send(data: Parameters[0]) { + if (typeof data === "string" && data.includes('"tag":"subscribeServerConfig"')) { + const requestId = (JSON.parse(data) as { id: number | string }).id; + deliver = () => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "KeybindingsConfigParseError", + configPath: "/demo/keybindings.json", + detail: "Injected failure.", + }, + }, + { _tag: "Interrupt", fiberId: 1 }, + ], + }, + }), + }), + ); + } + super.send(data); + } + }; + (window as unknown as { __fault: Fault }).__fault = { + failConfigStreamWhileInterrupted: () => { + deliver?.(); + return deliver !== null; + }, + }; + }); + await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" }); + await t3.open(thread); + + const reply = screen.getByText("The command printed one JSON line."); + await expect(reply.first()).toBeVisible(); + await app.screenshot("1-connected"); + + const delivered = await browser.evaluate(() => + (window as unknown as { __fault: Fault }).__fault.failConfigStreamWhileInterrupted(), + ); + expect(delivered).toBe(true); + // A live loop reconnects well within each wait; a dead one never does. + await runPromise(Effect.sleep("5 seconds")); + await app.screenshot("2-five-seconds-after-the-failure"); + + await screen.getByRole("textbox").fill("Are you still there?"); + await screen.getByRole("textbox").press("Enter"); + await runPromise(Effect.sleep("3 seconds")); + await app.screenshot("3-after-pressing-enter"); + await expect(reply.nth(1)).toBeVisible(); + }, +); From cb391b5b5741553ef136d93486a3f6cf89d0c026 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 14:54:21 -0800 Subject: [PATCH 2/5] fix(server): agent activity publish keeps retrying after a network drop (#39402) --- .../src/relay/AgentAwarenessRelay.test.ts | 47 +++++++++++++++++-- apps/server/src/relay/AgentAwarenessRelay.ts | 16 +++++-- 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 5cde458a1cd30..da3b0f30a99cb 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -291,9 +291,13 @@ const makeTestRelay = Effect.fnUntraced(function* ( authorization: new Headers(init?.headers).get("authorization"), state: payload.state, }); - return Promise.resolve( - options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }), - ); + try { + return Promise.resolve( + options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }), + ); + } catch (error) { + return Promise.reject(error); + } }, { preconnect: () => {} }, ); @@ -972,6 +976,43 @@ describe("AgentAwarenessRelay", () => { }), ); + it.effect("delivers a completion once the network returns after the retry budget runs out", () => + Effect.gen(function* () { + let networkUp = true; + const delivered: Array = []; + const { relay, currentShell, publications } = yield* makeTestRelay({ + respond: (attempt) => { + if (!networkUp) throw new TypeError("fetch failed: getaddrinfo EAI_AGAIN"); + delivered.push(publications[attempt - 1]?.state?.phase ?? null); + return Response.json({ ok: true, deliveries: [] }); + }, + }); + yield* relay.publishThread(THREAD_ID); + networkUp = false; + yield* Ref.set(currentShell, shell({ status: "completed" })); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + for (const delay of [ + "1 second", + "2 seconds", + "4 seconds", + "8 seconds", + "16 seconds", + ] as const) { + yield* TestClock.adjust(delay); + yield* relay.drain; + } + assert.equal(publications.length, 7); + assert.deepEqual(delivered, ["running"]); + + networkUp = true; + yield* TestClock.adjust("10 minutes"); + yield* relay.drain; + assert.deepEqual(delivered, ["running", "completed"]); + }), + ); + it.effect("keeps settled live work until its awaited monitor finishes", () => Effect.gen(function* () { const { relay, currentShell, publications } = yield* makeTestRelay(); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 75e84e7bb8c96..c9f38ed345ae9 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -205,6 +205,8 @@ function resolveAgentActivityPublishingStartupState(input: { const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160; const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed."; const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const; +// Nothing else re-queues a thread when the network returns, so a lost terminal state is retried until it lands. +const RELAY_AGENT_ACTIVITY_STEADY_RETRY_DELAY_MS = 60_000; function sanitizeRelayAgentActivityState( state: RelayAgentActivityState | null, @@ -820,11 +822,15 @@ export const make = Effect.gen(function* () { schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) { const attempts = publishRetries.get(threadId)?.attempts ?? 0; - const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts]; - if (delayMs === undefined) { - // Retain exhausted budgets until activity or success resets them; old timers must not restart retries. - yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId }); - return; + const delayMs = + RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts] ?? RELAY_AGENT_ACTIVITY_STEADY_RETRY_DELAY_MS; + if (attempts === RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS.length) { + yield* Effect.logWarning( + "agent activity publish retry budget exhausted; retrying every minute", + { + threadId, + }, + ); } const retry = { attempts: attempts + 1, From 2bba2564cafd651a1ca36de1b2b8492ad9124498 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:03:47 -0800 Subject: [PATCH 3/5] perf(server): thread shell item counts no longer sum every run the thread has had (#39391) --- .../orchestration-v2/ProjectionStore.test.ts | 4 + .../src/orchestration-v2/ProjectionStore.ts | 50 ++++---- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/102_ThreadItemCounts.test.ts | 89 ++++++++++++++ .../Migrations/102_ThreadItemCounts.ts | 112 ++++++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 6 files changed, 235 insertions(+), 24 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts create mode 100644 apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index dabe53aeae46f..79478def6dfd1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -7178,6 +7178,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { if (/^SEARCH (r|run) /.test(detail)) { assert.include(detail, "COVERING INDEX", detail); } + // A thread's item count reads one count row per hidden run, not one per run it had. + if (detail.startsWith("SEARCH counts ")) { + assert.include(detail, "run_key=?", detail); + } if (detail.includes("orchestration_v2_projection_turn_items")) { // Only held input is read from the sparse index; transcript history stays unread. assert.include( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 930639b5d6bbe..a8d06679c801a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8565,30 +8565,32 @@ export const layer: Layer.Layer = const selectShellItemCounts = (threadIds: ReadonlyArray) => sql` - SELECT counts.thread_id, - SUM(CASE WHEN counts.run_key = '' OR r.status <> 'rolled_back' - THEN counts.item_count - CASE - WHEN r.status IN ('queued', 'cancelled') THEN ( - SELECT COUNT(*) - FROM orchestration_v2_projection_turn_items held - INDEXED BY orchestration_v2_projection_turn_items_queued_input_idx - WHERE held.run_id = counts.run_key - AND held.type = 'user_message' - AND json_valid(held.payload_json) - AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' - ) - ELSE 0 - END - ELSE 0 END) AS item_count, - SUM(CASE WHEN counts.run_key = '' THEN counts.item_count ELSE 0 END) - AS runless_item_count - FROM orchestration_v2_projection_turn_item_counts counts - -- The primary key would load each run's whole row just for its status. - LEFT JOIN orchestration_v2_projection_runs r - INDEXED BY orchestration_v2_projection_runs_run_status_idx - ON r.run_id = counts.run_key - WHERE counts.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) - GROUP BY counts.thread_id + -- Only the thread's hidden runs are visited, so settled history costs nothing here. + SELECT totals.thread_id, + totals.item_count - COALESCE(( + SELECT SUM(CASE WHEN r.status = 'rolled_back' THEN counts.item_count ELSE ( + SELECT COUNT(*) + FROM orchestration_v2_projection_turn_items held + INDEXED BY orchestration_v2_projection_turn_items_queued_input_idx + WHERE held.run_id = counts.run_key + AND held.type = 'user_message' + AND json_valid(held.payload_json) + AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + ) END) + FROM orchestration_v2_projection_runs r + INDEXED BY orchestration_v2_projection_runs_hidden_items_idx + JOIN orchestration_v2_projection_turn_item_counts counts + ON counts.thread_id = r.thread_id AND counts.run_key = r.run_id + WHERE r.thread_id = totals.thread_id + AND r.status IN ('rolled_back', 'queued', 'cancelled') + ), 0) AS item_count, + COALESCE(( + SELECT runless.item_count + FROM orchestration_v2_projection_turn_item_counts runless + WHERE runless.thread_id = totals.thread_id AND runless.run_key = '' + ), 0) AS runless_item_count + FROM orchestration_v2_projection_thread_item_counts totals + WHERE totals.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) `; const selectShellProviderThreadRows = (threadIds?: ReadonlyArray) => diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index c3fc7aacef055..6f0b74e029606 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -109,6 +109,7 @@ import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts"; import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts"; import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts"; +import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -213,6 +214,7 @@ const migrationEntries = [ [99, "BackgroundRecoveryIndexes", Migration0099], [100, "TurnStartReadIndexes", Migration0100], [101, "DelegatedTaskReadIndexes", Migration0101], + [102, "ThreadItemCounts", Migration0102], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts new file mode 100644 index 0000000000000..678186e55b81c --- /dev/null +++ b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts @@ -0,0 +1,89 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); + +layer("102_ThreadItemCounts", (it) => { + it.effect("matches a recount of items without a run or with an existing run", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 101 }); + const upsertItem = (id: string, threadId: string, runId: string | null) => sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json + ) + VALUES ( + ${id}, ${threadId}, ${runId}, 1, 'assistant_message', 'completed', + '2026-11-19T00:00:00.000Z', '{}' + ) + ON CONFLICT(turn_item_id) DO UPDATE SET thread_id = excluded.thread_id, run_id = excluded.run_id + `; + const insertRun = (runId: string, threadId: string) => sql` + INSERT INTO orchestration_v2_projection_runs ( + run_id, thread_id, ordinal, provider, status, requested_at, payload_json + ) + VALUES ( + ${runId}, ${threadId}, + (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId}), + 'codex', 'completed', '2026-11-19T00:00:00.000Z', '{}' + ) + `; + const totals = () => sql<{ readonly thread_id: string; readonly item_count: number }>` + SELECT thread_id, item_count FROM orchestration_v2_projection_thread_item_counts + ORDER BY thread_id + `; + const recount = () => sql<{ readonly thread_id: string; readonly item_count: number }>` + SELECT item.thread_id, COUNT(*) AS item_count + FROM orchestration_v2_projection_turn_items item + WHERE item.run_id IS NULL + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs run WHERE run.run_id = item.run_id) + GROUP BY item.thread_id + ORDER BY item.thread_id + `; + const assertTotals = (expected: ReadonlyArray) => + Effect.gen(function* () { + const actual = yield* totals(); + assert.deepEqual(actual, yield* recount()); + assert.deepEqual( + actual.map((row) => [row.thread_id, row.item_count]), + expected.map(([threadId, count]) => [threadId, count]), + ); + }); + + yield* insertRun("run-1", "thread-1"); + yield* upsertItem("runless", "thread-1", null); + yield* upsertItem("run-1:a", "thread-1", "run-1"); + yield* upsertItem("late:a", "thread-1", "run-late"); + yield* runMigrations(); + yield* assertTotals([["thread-1", 2]]); + + yield* upsertItem("run-1:b", "thread-1", "run-1"); + yield* upsertItem("late:b", "thread-2", "run-late"); + yield* assertTotals([["thread-1", 3]]); + + yield* insertRun("run-late", "thread-1"); + yield* assertTotals([ + ["thread-1", 4], + ["thread-2", 1], + ]); + + yield* upsertItem("run-1:b", "thread-2", null); + yield* upsertItem("late:a", "thread-1", "run-missing"); + yield* assertTotals([ + ["thread-1", 2], + ["thread-2", 2], + ]); + + yield* sql`DELETE FROM orchestration_v2_projection_runs WHERE run_id = 'run-late'`; + yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id = 'run-1:b'`; + yield* assertTotals([["thread-1", 2]]); + + yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE thread_id = 'thread-1'`; + yield* assertTotals([]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts new file mode 100644 index 0000000000000..5cbfee859cd45 --- /dev/null +++ b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts @@ -0,0 +1,112 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * One total per thread beside 085's per-run counts, so a shell read does not sum every run the + * thread has had. It holds the items without a run or with an existing run, the rows the shell + * read used to sum; the read still applies the run status rules. Triggers keep it exact. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE orchestration_v2_projection_thread_item_counts ( + thread_id TEXT PRIMARY KEY, + item_count INTEGER NOT NULL + ) WITHOUT ROWID + `; + yield* sql` + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT counts.thread_id, SUM(counts.item_count) + FROM orchestration_v2_projection_turn_item_counts counts + WHERE counts.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = counts.run_key) + GROUP BY counts.thread_id + `; + + // The shell read subtracts only these runs. ProjectionStore.selectShellItemCounts must spell + // the same predicate for SQLite to use this partial index. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_hidden_items_idx + ON orchestration_v2_projection_runs(thread_id, status, run_id) + WHERE status IN ('rolled_back', 'queued', 'cancelled') + `; + + // 085's triggers upsert per-run counts, so an item write fires the insert or the update here. + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_insert + AFTER INSERT ON orchestration_v2_projection_turn_item_counts + WHEN new.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = new.run_key) + BEGIN + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + VALUES (new.thread_id, new.item_count) + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_update + AFTER UPDATE ON orchestration_v2_projection_turn_item_counts + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - old.item_count + WHERE thread_id = old.thread_id + AND (old.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = old.run_key)); + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT new.thread_id, new.item_count + WHERE new.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = new.run_key) + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE thread_id = old.thread_id AND item_count <= 0; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_delete + AFTER DELETE ON orchestration_v2_projection_turn_item_counts + WHEN old.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = old.run_key) + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - old.item_count + WHERE thread_id = old.thread_id; + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE thread_id = old.thread_id AND item_count <= 0; + END + `; + + // Items can be written before their run; they count from when it exists. + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_run_insert + AFTER INSERT ON orchestration_v2_projection_runs + BEGIN + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT thread_id, COUNT(*) + FROM orchestration_v2_projection_turn_items + WHERE run_id = new.run_id + GROUP BY thread_id + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_run_delete + AFTER DELETE ON orchestration_v2_projection_runs + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - ( + SELECT COUNT(*) + FROM orchestration_v2_projection_turn_items item + WHERE item.run_id = old.run_id + AND item.thread_id = orchestration_v2_projection_thread_item_counts.thread_id + ) + WHERE thread_id IN ( + SELECT thread_id FROM orchestration_v2_projection_turn_items WHERE run_id = old.run_id + ); + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE item_count <= 0 AND thread_id IN ( + SELECT thread_id FROM orchestration_v2_projection_turn_items WHERE run_id = old.run_id + ); + END + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index b9feabbf89b88..1703789b6b479 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -81,6 +81,7 @@ describe("V2 preview upgrade", () => { [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], [101, "DelegatedTaskReadIndexes"], + [102, "ThreadItemCounts"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -205,6 +206,7 @@ describe("V2 preview upgrade", () => { [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], [101, "DelegatedTaskReadIndexes"], + [102, "ThreadItemCounts"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 420d1b59003f5340624786e5e3c9e06d57db55b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:09:06 -0800 Subject: [PATCH 4/5] feat(desktop): forward another environment's ports to this machine (#39393) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/ipc/channels.ts | 5 + apps/desktop/src/ipc/methods/preview.ts | 51 ++++ apps/desktop/src/preload.ts | 16 ++ .../src/preview/LoopbackTunnel.test.ts | 239 +++++++++++++++- apps/desktop/src/preview/LoopbackTunnel.ts | 254 +++++++++++++++++- apps/web/src/components/CommandPalette.tsx | 22 +- .../CommandPalettePortForwardItems.tsx | 215 +++++++++++++++ .../components/chat/ThreadServersPanel.tsx | 172 +++++++++--- apps/web/src/i18n/translations/de.json | 51 +++- apps/web/src/i18n/translations/en.json | 53 +++- apps/web/src/i18n/translations/es.json | 53 +++- apps/web/src/i18n/translations/fr.json | 53 +++- apps/web/src/i18n/translations/ja.json | 53 +++- apps/web/src/i18n/translations/ko.json | 51 +++- apps/web/src/i18n/translations/pt-BR.json | 51 +++- apps/web/src/i18n/translations/ru.json | 51 +++- apps/web/src/i18n/translations/sv.json | 53 +++- apps/web/src/i18n/translations/zh.json | 53 +++- apps/web/src/state/portForwards.ts | 152 +++++++++++ docs/user/remote-access.md | 17 ++ packages/client-runtime/src/state/session.ts | 1 + packages/contracts/src/ipc.ts | 25 +- 22 files changed, 1527 insertions(+), 164 deletions(-) create mode 100644 apps/web/src/components/CommandPalettePortForwardItems.tsx create mode 100644 apps/web/src/state/portForwards.ts diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index bb708a6ab7c88..4a99d52b0e79d 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -128,6 +128,11 @@ export const PREVIEW_OPEN_LINK_CHANNEL = "desktop:preview-open-link"; export const PREVIEW_FIND_RESULT_CHANNEL = "desktop:preview-find-result"; export const PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL = "desktop:preview-tunnel-access-request"; export const PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL = "desktop:preview-tunnel-access-resolve"; +export const PORT_FORWARD_START_CHANNEL = "desktop:port-forward-start"; +export const PORT_FORWARD_STOP_CHANNEL = "desktop:port-forward-stop"; +export const PORT_FORWARD_LIST_CHANNEL = "desktop:port-forward-list"; +export const PORT_FORWARD_CHANGE_CHANNEL = "desktop:port-forward-change"; +export const PORT_FORWARD_SHARES_LOOPBACK_CHANNEL = "desktop:port-forward-shares-loopback"; export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index f06c26014f40e..9dc0465c1e55a 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -23,6 +23,9 @@ import { DesktopPreviewCreateTabInputSchema, DesktopPreviewTabInputSchema, DesktopPreviewTunnelAccessResolutionInputSchema, + DesktopPortForwardInputSchema, + DesktopPortForwardSchema, + DesktopSharesLoopbackInputSchema, DesktopPreviewWebviewConfigSchema, PreviewAnnotationSubmissionResultSchema, PreviewCaptureFailure, @@ -66,6 +69,10 @@ export const installPreviewEventForwarding = Effect.fn( yield* manager.subscribeFindResults((event) => electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), ); + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.subscribeForwards((forwards) => + electronWindow.sendAll(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, forwards), + ); }); const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ @@ -379,6 +386,46 @@ const resolveTunnelAccess = DesktopIpc.makeIpcMethod({ }), }); +const forwardPort = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_START_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: DesktopPortForwardSchema, + handler: Effect.fn("desktop.ipc.preview.forwardPort")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forward(input); + }), +}); + +const stopPortForward = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_STOP_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.stopPortForward")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.stopForward(input); + }), +}); + +const listPortForwards = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_LIST_CHANNEL, + payload: Schema.Void, + result: Schema.Array(DesktopPortForwardSchema), + handler: Effect.fn("desktop.ipc.preview.listPortForwards")(function* () { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forwards; + }), +}); + +const sharesLoopback = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, + payload: DesktopSharesLoopbackInputSchema, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.preview.sharesLoopback")(function* ({ environmentId }) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.sharesLoopback(environmentId); + }), +}); + export const listBrowserImportSources = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL, payload: Schema.Void, @@ -523,6 +570,10 @@ export const methods = [ clearCache, getPreviewConfig, resolveTunnelAccess, + forwardPort, + stopPortForward, + listPortForwards, + sharesLoopback, setAnnotationTheme, setAnnotationSendEnabled, pickElement, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index b413656a15241..280c5ad6c6716 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -449,6 +449,22 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, resolveTunnelAccess: (requestId, url) => ipcRenderer.invoke(IpcChannels.PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL, { requestId, url }), + forwardPort: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_START_CHANNEL, { environmentId, remotePort }), + stopPortForward: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_STOP_CHANNEL, { environmentId, remotePort }), + listPortForwards: () => ipcRenderer.invoke(IpcChannels.PORT_FORWARD_LIST_CHANNEL), + sharesLoopback: (environmentId) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, { environmentId }), + onPortForwards: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, forwards: unknown) => { + if (!Array.isArray(forwards)) return; + listener(forwards); + }; + ipcRenderer.on(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + return () => + ipcRenderer.removeListener(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + }, setAnnotationTheme: (theme) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }), setAnnotationSendEnabled: (tabId, enabled) => diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fb193e768e8d2..fe83817c0d5e8 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -1,5 +1,6 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; +import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { expect, it } from "@effect/vitest"; import * as NodeNet from "node:net"; @@ -8,6 +9,8 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as LoopbackTunnel from "./LoopbackTunnel.ts"; @@ -74,9 +77,10 @@ const unusedPort = Effect.promise( }), ); -/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ -const routeThroughTunnel = ( - tunnelUrl: string | null, +/** The tunnel service, with every access request answered with `tunnelUrl`. */ +const makeTunnel = ( + /** A function answers each access request with its current value. */ + tunnelUrl: string | null | (() => string | null), host?: Layer.Layer | Layer.Layer, ) => Effect.gen(function* () { @@ -96,6 +100,7 @@ const routeThroughTunnel = ( currentMainOrFirst: Effect.succeedSome(window as unknown as Electron.BrowserWindow), }), NodeFileSystem.layer, + SecureRandom.layerWebCrypto, host ?? Layer.empty, ), ), @@ -103,10 +108,25 @@ const routeThroughTunnel = ( ); const tunnel = Context.get(services, LoopbackTunnel.LoopbackTunnel); yield* Queue.take(accessRequests).pipe( - Effect.flatMap((requestId) => tunnel.resolveAccess({ requestId, url: tunnelUrl })), + Effect.flatMap((requestId) => + tunnel.resolveAccess({ + requestId, + url: typeof tunnelUrl === "function" ? tunnelUrl() : tunnelUrl, + }), + ), Effect.forever, Effect.forkScoped, ); + return tunnel; + }); + +/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ +const routeThroughTunnel = ( + tunnelUrl: string | null, + host?: Layer.Layer | Layer.Layer, +) => + Effect.gen(function* () { + const tunnel = yield* makeTunnel(tunnelUrl, host); let proxyRules = ""; const session = { setProxy: async (config: Electron.ProxyConfig) => { @@ -284,3 +304,214 @@ it.effect("connects straight to the environment's own forwarded origin port", () expect(received).toEqual([7, 8]); }), ); + +/** Connects to a local port, sends `bytes`, and resolves with the first chunk back. */ +const exchange = (port: number, bytes: Uint8Array) => + Effect.promise( + () => + new Promise((resolve, reject) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => socket.write(bytes)); + socket.once("data", (chunk) => { + resolve([...chunk]); + socket.destroy(); + }); + socket.on("error", reject); + }), + ); + +const refusesConnections = (port: number) => + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => { + socket.destroy(); + resolve(false); + }); + socket.on("error", () => resolve(true)); + }), + ); + +it.effect("forwards a port over the tunnel on the same local port until stopped", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel?wsTicket=t`, + ); + const announced: number[][] = []; + yield* tunnel.subscribeForwards((forwards) => + Effect.sync(() => announced.push(forwards.map((forward) => forward.localPort))), + ); + const environmentId = EnvironmentId.make("remote"); + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(forward).toEqual({ environmentId, remotePort, localPort: remotePort }); + + expect(yield* exchange(remotePort, Uint8Array.of(4, 5))).toEqual([0xee, 4, 5]); + // The first request is the same-machine probe. + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?wsTicket=t&port=${remotePort}`); + + yield* tunnel.stopForward({ environmentId, remotePort }); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + expect(announced).toEqual([[remotePort], []]); + }), +); + +it.effect("moves a forward to a free port when its own is taken here", () => + Effect.gen(function* () { + const decoy = yield* listenDecoy; + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), +); + +/** An environment on this machine: each tunnel connection dials the requested local port. */ +const listenSameMachineEndpoint = Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { port: 0, host: "127.0.0.1" }, + () => resolve(server), + ); + server.on("connection", (socket: NodeWS.WebSocket, request: { url?: string }) => { + const port = Number(new URL(request.url ?? "", "ws://x").searchParams.get("port")); + const local = NodeNet.connect(port, "127.0.0.1"); + local.on("data", (chunk) => socket.send(chunk)); + local.on("error", () => socket.close()); + socket.on("message", (data: Buffer) => local.write(data)); + socket.on("close", () => local.destroy()); + }); + }), + ), + closeServer, +); + +it.effect("refuses to forward from an environment that shares this machine's loopback", () => + Effect.gen(function* () { + const endpoint = yield* listenSameMachineEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const error = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.flip); + expect(error._tag).toBe("LoopbackTunnelSameMachineError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + }), +); + +it.effect( + "forwards nothing while the environment is out of reach, then forwards once it is back", + () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + let access: string | null = null; + const tunnel = yield* makeTunnel(() => access); + const environmentId = EnvironmentId.make("remote"); + + const unavailable = yield* tunnel.forward({ environmentId, remotePort }).pipe(Effect.flip); + expect(unavailable._tag).toBe("LoopbackTunnelUnavailableError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + + access = `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`; + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(yield* exchange(forward.localPort, Uint8Array.of(9))).toEqual([0xee, 9]); + }), +); + +/** The environment's tunnel route refusing every port with a 502, as for a port nothing listens on. */ +const listenRefusingEndpoint = (headers: Record) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { + port: 0, + host: "127.0.0.1", + verifyClient: (_info, done) => done(false, 502, "Bad Gateway", headers), + }, + () => resolve(server), + ); + }), + ), + closeServer, + ); + +it.effect.each([ + { case: "the environment reports nothing on the probe port", refused: true }, + { case: "the tunnel fails for another reason", refused: false }, +])("decides a forward's machine only on proof: $case", ({ refused }) => + Effect.gen(function* () { + const endpoint = yield* listenRefusingEndpoint( + refused ? { "x-t3-tunnel-port-refused": "1" } : {}, + ); + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const result = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.result); + if (refused) { + expect(Result.isSuccess(result)).toBe(true); + } else { + expect(Result.isFailure(result) && result.failure._tag).toBe( + "LoopbackTunnelUnavailableError", + ); + expect(yield* refusesConnections(remotePort)).toBe(true); + } + }), +); + +it.effect("closes connections beyond a forward's limit without tunnelling them", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort: yield* unusedPort, + }); + const open = () => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1", () => { + socket.once("data", () => resolve(socket)); + socket.write(Uint8Array.of(1)); + }); + }), + ), + (socket) => Effect.sync(() => socket.destroy()), + ); + yield* Effect.forEach(Array.from({ length: 64 }), open, { concurrency: "unbounded" }); + const tunnelled = endpoint.requests.length; + const closed = yield* Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1"); + socket.on("close", () => resolve(true)); + socket.on("data", () => resolve(false)); + socket.write(Uint8Array.of(2)); + }), + ); + expect(closed).toBe(true); + expect(endpoint.requests.length).toBe(tunnelled); + }), +); diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 6eff2dd70b345..1e06993fa54f0 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -1,21 +1,28 @@ // Renders another environment's localhost pages in a local webview: the partition's loopback // traffic goes to a SOCKS5 listener here, and each connection rides one WebSocket to the -// environment's /api/preview/tunnel. The page keeps its localhost origin. +// environment's /api/preview/tunnel. The page keeps its localhost origin. Forwarded ports take +// the same route from a plain listener, for any client on this machine. import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer"; import * as NodeWS from "@effect/platform-node/NodeWS"; -import type { DesktopPreviewTunnelAccessRequest } from "@t3tools/contracts"; +import type { + DesktopPortForward, + DesktopPreviewTunnelAccessRequest, + EnvironmentId, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as NetAddress from "effect/net/NetAddress"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Socket from "effect/socket/Socket"; @@ -24,6 +31,8 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts"; const ACCESS_TIMEOUT = "15 seconds"; +const PROBE_TIMEOUT = "3 seconds"; +const MAX_FORWARD_CONNECTIONS = 64; const CONNECT_TIMEOUT = "10 seconds"; const REPLY_SUCCEEDED = 0; @@ -127,9 +136,13 @@ const isTunnelEndpoint = (tunnelUrl: string, port: number) => { }; /** Opens a connection to the destination; `ws` pauses its socket, so a slow page slows the tunnel. */ +/** Set by the environment's /api/preview/tunnel when it reached the port and nothing listens. */ +const PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused"; + const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( tunnelUrl: string, port: number, + onPortRefused?: () => void, ) { if (isTunnelEndpoint(tunnelUrl, port)) { const endpoint = yield* NodeSocket.makeNet({ @@ -141,10 +154,18 @@ const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( const url = new URL(tunnelUrl); url.searchParams.set("port", String(port)); const tunnel = yield* Effect.acquireRelease( - Effect.sync(() => + Effect.sync(() => { // Closing before the handshake finishes emits an error after Socket's listeners are gone. - new NodeWS.WebSocket(url).on("error", () => undefined), - ), + const tunnel = new NodeWS.WebSocket(url).on("error", () => undefined); + if (onPortRefused) { + tunnel.on("unexpected-response", (_request, response) => { + if (response.headers[PORT_REFUSED_HEADER] !== undefined) onPortRefused(); + // Handled here, so `ws` leaves aborting the handshake to us. + tunnel.terminate(); + }); + } + return tunnel; + }), (tunnel) => Effect.sync(() => tunnel.close()), ); const socket = yield* Socket.fromWebSocket(Effect.succeed(tunnel), { @@ -224,6 +245,33 @@ export class LoopbackTunnelRouteError extends Schema.TaggedError()( + "LoopbackTunnelForwardError", + { environmentId: Schema.String, port: Schema.Number, cause: Schema.Defect() }, +) { + override get message(): string { + return `Failed to forward port ${this.port} of environment "${this.environmentId}".`; + } +} + +export class LoopbackTunnelUnavailableError extends Schema.TaggedError()( + "LoopbackTunnelUnavailableError", + { environmentId: Schema.String }, +) { + override get message(): string { + return `Environment "${this.environmentId}" can't be reached through the tunnel right now.`; + } +} + +export class LoopbackTunnelSameMachineError extends Schema.TaggedError()( + "LoopbackTunnelSameMachineError", + { environmentId: Schema.String, port: Schema.Number }, +) { + override get message(): string { + return `This environment runs on this computer, so localhost:${this.port} already reaches it.`; + } +} + export class LoopbackTunnel extends Context.Service< LoopbackTunnel, { @@ -237,6 +285,26 @@ export class LoopbackTunnel extends Context.Service< readonly requestId: string; readonly url: string | null; }) => Effect.Effect; + /** Listens on this machine's loopback, on the same port when it is free. */ + readonly forward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect< + DesktopPortForward, + LoopbackTunnelForwardError | LoopbackTunnelSameMachineError | LoopbackTunnelUnavailableError + >; + readonly stopForward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect; + readonly forwards: Effect.Effect>; + /** Whether the environment's loopback is this machine's, so forwarding would only loop. */ + readonly sharesLoopback: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + readonly subscribeForwards: ( + listener: (forwards: ReadonlyArray) => Effect.Effect, + ) => Effect.Effect; } >()("@t3tools/desktop/preview/LoopbackTunnel") {} @@ -245,8 +313,17 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; + const random = yield* SecureRandom.SecureRandom; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); + const forwarding = yield* Semaphore.make(1); + const forwarded = new Map< + string, + { readonly forward: DesktopPortForward; readonly scope: Scope.Closeable } + >(); + const forwardListeners = new Set< + (forwards: ReadonlyArray) => Effect.Effect + >(); const pending = new Map>(); const listenerPorts = new Map(); const routed = new WeakSet(); @@ -318,6 +395,163 @@ const make = Effect.gen(function* () { (effect) => Effect.ignoreCause(effect), ); + /** Serves one connection to a forwarded port; closes it when the environment is out of reach. */ + const serveForward = (environmentId: string, port: number) => { + let active = 0; + return Effect.fn("LoopbackTunnel.serveForward")( + function* (socket: Socket.Socket) { + // Acquiring the socket ties it to this scope, so returning early closes it. + const pull = yield* Socket.readerBytes(socket); + const writer = yield* socket.writer; + // Closed at once, so a page hammering the port can't queue tunnels and access requests. + if (active >= MAX_FORWARD_CONNECTIONS) return; + active++; + yield* Effect.addFinalizer(() => Effect.sync(() => active--)); + if (!(yield* isOwnConnection())) return; + const tunnelUrl = yield* requestAccess(environmentId); + if (tunnelUrl === null) return; + const destination = yield* dialDestination(tunnelUrl, port); + return yield* Effect.raceFirst( + pump(pull, destination.writer.writeAll), + pump(destination.pull, writer.writeAll), + ); + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ); + }; + + /** + * Whether the environment's loopback is this machine's, by tunnelling a nonce to a local probe. + * A forward there would accept the environment's own dials and loop through the tunnel. + */ + const sharesLoopback = Effect.fn("LoopbackTunnel.sharesLoopback")(function* ( + environmentId: string, + ) { + const tunnelUrl = yield* requestAccess(environmentId); + // Without access the answer is unknown, not "another machine": a forward could loop later. + if (tunnelUrl === null) return yield* new LoopbackTunnelUnavailableError({ environmentId }); + return yield* probeLoopback(environmentId, tunnelUrl); + }); + + /** + * True only when the nonce reaches this machine's probe; false only on proof the environment + * was reached and nothing listens on the probe port there. Anything else is unknown. + */ + const probeLoopback = Effect.fn("LoopbackTunnel.probeLoopback")( + function* (environmentId: string, tunnelUrl: string) { + const unavailable = new LoopbackTunnelUnavailableError({ environmentId }); + const nonce = new TextEncoder().encode(yield* random.uuidV4()); + const arrived = yield* Deferred.make(); + const probe = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" }); + yield* probe + .run( + Effect.fnUntraced( + function* (socket: Socket.Socket) { + const pull = yield* Socket.readerBytes(socket); + let received = Buffer.alloc(0); + while (received.length < nonce.length) { + received = Buffer.concat([received, ...(yield* pull)]); + } + if (received.subarray(0, nonce.length).equals(nonce)) { + yield* Deferred.succeed(arrived, undefined); + } + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ), + ) + .pipe(Effect.forkScoped); + let portRefused = false; + const destination = yield* dialDestination( + tunnelUrl, + (probe.address as NetAddress.InetAddress).port, + () => { + portRefused = true; + }, + ).pipe(Effect.option); + if (Option.isNone(destination)) { + if (portRefused) return false; + return yield* unavailable; + } + yield* destination.value.writer.write(nonce); + // An answer or a close means a service on another machine took the connection. + const answer = yield* Effect.raceFirst( + Deferred.await(arrived).pipe(Effect.as(true)), + destination.value.pull.pipe(Effect.as(false)), + ).pipe(Effect.timeoutOption(PROBE_TIMEOUT)); + if (Option.isNone(answer)) return yield* unavailable; + return answer.value; + }, + Effect.scoped, + (effect, environmentId) => + effect.pipe( + Effect.mapError((error) => + error._tag === "LoopbackTunnelUnavailableError" + ? error + : new LoopbackTunnelUnavailableError({ environmentId }), + ), + ), + ); + + const forwardKey = (environmentId: string, port: number) => `${environmentId}:${port}`; + const currentForwards = () => [...forwarded.values()].map(({ forward }) => forward); + const announceForwards = Effect.suspend(() => { + const forwards = currentForwards(); + return Effect.forEach([...forwardListeners], (listener) => listener(forwards), { + discard: true, + }); + }); + + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( + function* ({ environmentId, remotePort }) { + const existing = forwarded.get(forwardKey(environmentId, remotePort)); + if (existing) return existing.forward; + if (yield* sharesLoopback(environmentId)) { + return yield* new LoopbackTunnelSameMachineError({ environmentId, port: remotePort }); + } + const scope = yield* Scope.fork(listenerScope); + const bind = (port: number) => + NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); + const server = yield* bind(remotePort).pipe( + // Taken here, or privileged: any free port still reaches the environment's. + Effect.catch(() => bind(0)), + Effect.onError(() => Scope.close(scope, Exit.void)), + Effect.mapError( + (cause) => new LoopbackTunnelForwardError({ environmentId, port: remotePort, cause }), + ), + ); + yield* server.run(serveForward(environmentId, remotePort)).pipe(Effect.forkIn(scope)); + const forward = { + environmentId, + remotePort, + localPort: (server.address as NetAddress.InetAddress).port, + }; + forwarded.set(forwardKey(environmentId, remotePort), { forward, scope }); + yield* announceForwards; + return forward; + }, + forwarding.withPermits(1), + ); + + const stopForward: LoopbackTunnel["Service"]["stopForward"] = Effect.fn( + "LoopbackTunnel.stopForward", + )(function* ({ environmentId, remotePort }) { + const key = forwardKey(environmentId, remotePort); + const existing = forwarded.get(key); + if (!existing) return; + forwarded.delete(key); + // Closing the scope also ends the connections it carries. + yield* Scope.close(existing.scope, Exit.void); + yield* announceForwards; + }, forwarding.withPermits(1)); + + const subscribeForwards: LoopbackTunnel["Service"]["subscribeForwards"] = (listener) => + Effect.acquireRelease( + Effect.sync(() => forwardListeners.add(listener)), + () => Effect.sync(() => forwardListeners.delete(listener)), + ).pipe(Effect.asVoid); + const listen = Effect.fn("LoopbackTunnel.listen")(function* (environmentId: string) { const existing = listenerPorts.get(environmentId); if (existing !== undefined) return existing; @@ -375,7 +609,15 @@ const make = Effect.gen(function* () { return answer ? Deferred.succeed(answer, url).pipe(Effect.asVoid) : Effect.void; }; - return LoopbackTunnel.of({ route, resolveAccess }); + return LoopbackTunnel.of({ + route, + resolveAccess, + forward, + stopForward, + forwards: Effect.sync(currentForwards), + sharesLoopback, + subscribeForwards, + }); }); export const layer = Layer.effect(LoopbackTunnel, make); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 1eb1a9bcba599..3349902aeea05 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -255,6 +255,10 @@ import { } from "./CommandPaletteAddProject"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; +import { + PORT_FORWARD_GROUP_PREFIX, + useCommandPalettePortForwardItem, +} from "./CommandPalettePortForwardItems"; import { CommandPaletteVirtualizedResults, scrollCommandPaletteRowIntoView, @@ -547,6 +551,10 @@ function OpenCommandPaletteDialog(props: { const keybindings = useAtomValue(primaryServerKeybindingsAtom); const providersByEnvironment = useEnvironmentProviders(); const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems(); + const portForwardItem = useCommandPalettePortForwardItem({ + activeThread: activeThread ?? null, + query: deferredQuery, + }); const currentView = viewStack.at(-1)?.view ?? null; const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : ""; const [browseGeneration, setBrowseGeneration] = useState(0); @@ -1425,6 +1433,8 @@ function OpenCommandPaletteDialog(props: { }); } + if (portForwardItem) actionItems.push(portForwardItem); + const promptLinkTarget = paletteRouteTarget ? paletteRouteTarget.kind === "server" ? paletteRouteTarget.threadRef @@ -1884,11 +1894,13 @@ function OpenCommandPaletteDialog(props: { items: projectThreadItems.length > 0 ? projectThreadItems : [addProjectAction], }, ] - : currentView?.groups[0]?.value === "themes" - ? changeThemeItem.groups - : currentView?.groups[0]?.value === "appearance" - ? changeAppearanceItem.groups - : (currentView?.groups ?? rootGroups); + : currentView?.groups[0]?.value.startsWith(PORT_FORWARD_GROUP_PREFIX) && portForwardItem + ? portForwardItem.groups + : currentView?.groups[0]?.value === "themes" + ? changeThemeItem.groups + : currentView?.groups[0]?.value === "appearance" + ? changeAppearanceItem.groups + : (currentView?.groups ?? rootGroups); const isLinkedThreadSearch = linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query; diff --git a/apps/web/src/components/CommandPalettePortForwardItems.tsx b/apps/web/src/components/CommandPalettePortForwardItems.tsx new file mode 100644 index 0000000000000..2a03b19d300c1 --- /dev/null +++ b/apps/web/src/components/CommandPalettePortForwardItems.tsx @@ -0,0 +1,215 @@ +import { + AuthTerminalOperateScope, + type DesktopPortForward, + type EnvironmentId, + type ThreadId, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { useGT } from "gt-react"; +import { CableIcon, ClipboardCopyIcon, ExternalLinkIcon, SquareIcon } from "lucide-react"; + +import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; +import { readLocalApi } from "../localApi"; +import { useThreadDiscoveredPorts } from "../portDiscoveryState"; +import { useEnvironments } from "../state/environments"; +import { + canForwardPorts, + findPortForward, + forwardedUrl, + forwardPort, + forwardLocalitiesAtom, + stopPortForward, + usePortForwards, +} from "../state/portForwards"; +import { environmentIdsKey } from "../state/environmentAtomList"; +import { useEnvironmentsWithScope } from "../state/session"; +import { + ADDON_ICON_CLASS, + ITEM_ICON_CLASS, + type CommandPaletteActionItem, + type CommandPaletteGroup, + type CommandPaletteSubmenuItem, +} from "./CommandPalette.logic"; +import { toastManager } from "./ui/toast"; + +/** Prefix of this submenu's group values; the palette rebuilds them live while it is open. */ +export const PORT_FORWARD_GROUP_PREFIX = "port-forwards:"; + +const parsePort = (query: string) => { + const trimmed = query.trim(); + if (!/^\d{1,5}$/.test(trimmed)) return null; + const port = Number(trimmed); + return port >= 1 && port <= 65_535 ? port : null; +}; + +/** "Forwarded ports": each forward with its actions, then ports to forward from the thread or the query. */ +export function useCommandPalettePortForwardItem(input: { + readonly activeThread: { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + } | null; + readonly query: string; +}): CommandPaletteSubmenuItem | null { + const gt = useGT(); + const forwards = usePortForwards(); + const { environments } = useEnvironments(); + const reachable = environments.filter( + (environment) => + environment.connection.phase === "connected" && canForwardPorts(environment.entry.target), + ); + const tunnelling = useEnvironmentsWithScope(reachable, AuthTerminalOperateScope); + const tunnelled = reachable.filter((environment) => tunnelling.has(environment.environmentId)); + const localities = useAtomValue( + forwardLocalitiesAtom(environmentIdsKey(tunnelled.map(({ environmentId }) => environmentId))), + ); + const sources = tunnelled.filter((_, index) => localities[index] === "remote"); + // Only a forwardable thread's servers are listed, so other clients never subscribe to them. + const threadEnvironmentId = sources.some( + (environment) => environment.environmentId === input.activeThread?.environmentId, + ) + ? (input.activeThread?.environmentId ?? null) + : null; + const threadServers = useThreadDiscoveredPorts({ + environmentId: threadEnvironmentId, + threadId: threadEnvironmentId === null ? null : (input.activeThread?.id ?? null), + }); + if (forwards.length === 0 && sources.length === 0) return null; + + const labelOf = (environmentId: EnvironmentId) => + environments.find((environment) => environment.environmentId === environmentId)?.label ?? + environmentId; + + const start = async (environmentId: EnvironmentId, remotePort: number) => { + const forward = await forwardPort(environmentId, remotePort); + toastManager.add({ + type: "success", + title: gt("Forwarded port {port}", { port: remotePort }), + description: gt("Apps on this machine reach it at localhost:{port}.", { + port: forward.localPort, + }), + }); + }; + + const forwardedItem = (forward: DesktopPortForward): CommandPaletteSubmenuItem => { + const address = `localhost:${forward.localPort}`; + const environment = labelOf(forward.environmentId); + return { + kind: "submenu", + value: `port-forward:${forward.environmentId}:${forward.remotePort}`, + title: address, + description: gt("Port {port} on {environment}", { port: forward.remotePort, environment }), + searchTerms: [address, String(forward.remotePort), environment, "forwarded port"], + icon: , + addonIcon: , + groups: [ + { + value: "port-forward-actions", + label: address, + items: [ + { + kind: "action", + value: "port-forward:open", + title: gt("Open in browser"), + searchTerms: ["open", "browser"], + icon: , + run: async () => { + await readLocalApi()?.shell.openExternal(forwardedUrl(forward)); + }, + }, + { + kind: "action", + value: "port-forward:copy", + title: gt("Copy address"), + searchTerms: ["copy", "address", "url"], + icon: , + run: async () => { + await writeTextToClipboard(forwardedUrl(forward)); + }, + }, + { + kind: "action", + value: "port-forward:stop", + title: gt("Stop forwarding"), + searchTerms: ["stop", "remove", "close"], + icon: , + run: () => stopPortForward(forward.environmentId, forward.remotePort), + }, + ], + }, + ], + }; + }; + + const startItems: CommandPaletteActionItem[] = []; + for (const server of threadServers) { + const environmentId = threadEnvironmentId; + if (environmentId === null) break; + if (findPortForward(forwards, environmentId, server.port)) continue; + startItems.push({ + kind: "action", + value: `port-forward:start:${environmentId}:${server.port}`, + title: gt("Forward localhost:{port}", { port: server.port }), + description: [labelOf(environmentId), server.processName].filter(Boolean).join(" · "), + searchTerms: [String(server.port), server.processName ?? "", "forward"], + icon: , + run: () => start(environmentId, server.port), + }); + } + const typedPort = parsePort(input.query); + if (typedPort !== null) { + for (const environment of sources) { + if (findPortForward(forwards, environment.environmentId, typedPort)) continue; + if ( + startItems.some((item) => item.value.endsWith(`:${environment.environmentId}:${typedPort}`)) + ) + continue; + startItems.push({ + kind: "action", + value: `port-forward:start:${environment.environmentId}:${typedPort}`, + title: gt("Forward port {port} from {environment}", { + port: typedPort, + environment: environment.label, + }), + searchTerms: [String(typedPort), "forward"], + icon: , + run: () => start(environment.environmentId, typedPort), + }); + } + } + + const groups: CommandPaletteGroup[] = []; + if (forwards.length > 0) { + groups.push({ + value: `${PORT_FORWARD_GROUP_PREFIX}forwarded`, + label: gt("Forwarded"), + items: forwards.map(forwardedItem), + }); + } + if (startItems.length === 0 && sources.length > 0) { + startItems.push({ + kind: "action", + value: "port-forward:hint", + title: gt("Type a port number to forward it"), + searchTerms: [], + icon: , + disabled: true, + run: async () => {}, + }); + } + // Always present, so the open submenu keeps a group to be recognized by. + groups.push({ + value: `${PORT_FORWARD_GROUP_PREFIX}start`, + label: startItems.length > 0 ? gt("Forward a port") : "", + items: startItems, + }); + + return { + kind: "submenu", + value: "action:port-forwards", + title: gt("Forwarded ports"), + searchTerms: ["forward port", "port forwarding", "forwarded ports", "ports", "tunnel"], + icon: , + addonIcon: , + groups, + }; +} diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index 10bfb11aa835a..b392a78f21b9a 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -3,6 +3,7 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { AuthPreviewOperateScope, + AuthTerminalOperateScope, type DiscoveredLocalServer, type EnvironmentId, type ThreadId, @@ -13,7 +14,7 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { T, useGT, Var } from "gt-react"; import { m } from "~/i18n/messages"; -import { GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import { CableIcon, GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"; import { type MouseEvent, useState } from "react"; import { resolveExternalServerUrl } from "../../browser/browserTargetResolver"; @@ -21,6 +22,15 @@ import { readLocalApi } from "../../localApi"; import { cn, isMacPlatform } from "../../lib/utils"; import { useThreadDiscoveredPorts } from "../../portDiscoveryState"; import { useEnvironment } from "../../state/environments"; +import { + canForwardPorts, + findPortForward, + forwardedUrl, + forwardPort, + stopPortForward, + useForwardLocality, + usePortForwards, +} from "../../state/portForwards"; import { previewEnvironment } from "../../state/preview"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -53,14 +63,21 @@ function ThreadServersList(props: ThreadServersPanelProps) { const canStop = useAtomValue( previewEnvironment.stopLocalServer.permissionAtom(props.environmentId), ); - const supportsStop = - useEnvironment(props.environmentId)?.serverConfig?.environment.capabilities.localServerStop === - true; + const environment = useEnvironment(props.environmentId); + const supportsStop = environment?.serverConfig?.environment.capabilities.localServerStop === true; + const forwards = usePortForwards(); + const forwardable = + useEnvironmentScope(props.environmentId, AuthTerminalOperateScope) && + environment?.connection.phase === "connected" && + canForwardPorts(environment.entry.target); + const locality = useForwardLocality(forwardable ? props.environmentId : null); + const canForward = locality === "remote"; const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const stopServer = useAtomCommand(previewEnvironment.stopLocalServer, { label: "thread server stop", }); const [stoppingKey, setStoppingKey] = useState(null); + const [forwardingPort, setForwardingPort] = useState(null); const [visibleCount, setVisibleCount] = useState(SERVER_PAGE_COUNT); if (servers.length === 0) return null; @@ -83,7 +100,19 @@ function ThreadServersList(props: ThreadServersPanelProps) { // Like links: modified and middle clicks go to the system browser. if (event.metaKey || event.ctrlKey || event.button === 1) { event.preventDefault(); - const url = resolveExternalServerUrl(props.environmentId, server.url); + // This machine's browser reaches another environment's loopback only through a forward. + // Starting a forward runs the probe; only a confirmed local environment opens directly. + const url = + forwardable && locality !== "local" + ? await forwardPort(props.environmentId, server.port).then( + (forward) => forwardedUrl(forward, server.url), + (error: unknown) => { + reportFailure(gt("Could not forward port {port}", { port: server.port }), error); + return null; + }, + ) + : resolveExternalServerUrl(props.environmentId, server.url); + if (url === null) return; await readLocalApi() ?.shell.openExternal(url) .catch((error: unknown) => reportFailure(gt("Unable to open in browser"), error)); @@ -108,6 +137,19 @@ function ThreadServersList(props: ThreadServersPanelProps) { } }; + const toggleForward = async (server: DiscoveredLocalServer, forwarded: boolean) => { + if (forwardingPort !== null) return; + setForwardingPort(server.port); + await ( + forwarded + ? stopPortForward(props.environmentId, server.port) + : forwardPort(props.environmentId, server.port) + ).catch((error: unknown) => + reportFailure(gt("Could not forward port {port}", { port: server.port }), error), + ); + setForwardingPort(null); + }; + return ( { const key = serverKey(server); const stoppable = canStop && supportsStop && server.pid !== null; + const forward = findPortForward(forwards, props.environmentId, server.port); + const actionCount = Number(stoppable) + Number(canForward); return (
  • {/* The end padding keeps text clear of the stop button. */} - + localhost:{server.port} {[ + // First, so the narrow panel truncates the less useful parts. + forward + ? gt("Forwarded to :{port}", { + $context: "a remote dev server reachable on this machine's port", + port: forward.localPort, + }) + : null, server.terminal === null ? gt("Agent", { $context: "who started a dev server" }) : gt("Terminal", { $context: "who started a dev server" }), @@ -162,32 +219,83 @@ function ThreadServersList(props: ThreadServersPanelProps) { - {stoppable ? ( -
    - - void stop(server)} - /> - } - > - {stoppingKey === key ? ( - - ) : ( - - )} - - - Stop server - - + {actionCount > 0 ? ( +
    + {canForward ? ( + + void toggleForward(server, forward !== undefined)} + /> + } + > + {forwardingPort === server.port ? ( + + ) : ( + + )} + + + {forward ? ( + + Forwarded to localhost:{forward.localPort} on this machine. + Click to stop. + + ) : ( + Forward to this machine, for any app here + )} + + + ) : null} + {stoppable ? ( + + void stop(server)} + /> + } + > + {stoppingKey === key ? ( + + ) : ( + + )} + + + Stop server + + + ) : null}
    ) : null}
  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 22f9bcf953f2b..661098ee35afc 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1840,6 +1840,18 @@ "480646ceb98c7163": "Schließen", "32fc9124998ebc18": "Lokal", "1c4158d741eec5da": "{label} (lokal)", + "a12a4958ca6b924b": "Port {port} weitergeleitet", + "0f14a51b016f825d": "Apps auf diesem Rechner erreichen ihn unter localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} auf {environment}", + "7a462e32dba47f4c": "Im Browser öffnen", + "4b8087450e97c995": "Adresse kopieren", + "c170720e67d01733": "Weiterleitung beenden", + "1e5c6d1c33667b17": "localhost:{port} weiterleiten", + "e76f45b6a412a0b6": "Port {port} von {environment} weiterleiten", + "ecf3b95b3d9e6e74": "Weitergeleitet", + "b3123e5b8602a134": "Gib eine Portnummer ein, um sie weiterzuleiten", + "1bdeef9819b4a055": "Port weiterleiten", + "de8a46b66f8ec455": "Weitergeleitete Ports", "f844c41fac2d339c": "Aktuell", "69154433587763c0": "Keine passenden Aktionen.", "90c3a382ecefa0ce": "Keine passenden Befehle, Projekte oder Threads.", @@ -2975,6 +2987,10 @@ "314cdccee9c14774": "Dieser Server unterstützt keine Registry-Abfragen. Aktualisiere ihn, bevor du den Kanal wechselst.", "22da1d00403ab2fd": "Die npm-Registry dieser Umgebung konnte nicht geprüft werden. Prüfe die Verbindung und die Registry-Einstellungen.", "2fc0f7a698c95c90": "Verbinde dich mit einem Server, um nach Releases zu suchen.", + "922269f8691aa3ba": "Es ließ sich nicht feststellen, ob diese Umgebung auf diesem Computer läuft.", + "35cade9cc8a01363": "Portweiterleitung braucht die Desktop-App.", + "9e303e0a794898d4": "Diese Umgebung läuft auf diesem Computer, daher erreicht localhost:{port} sie bereits.", + "2d49965e0e27e23b": "Diese Umgebung ist gerade nicht erreichbar. Versuche es erneut, sobald sie wieder verbunden ist.", "7280baf7517dad1c": "Refs konnten nicht geladen werden.", "567c0fed6ab8efc1": "Diese Verbindung kann keine Host-Dateien durchsuchen.", "5189720b9436f98c": "Die Suche ist auf {count} Zeichen begrenzt.", @@ -4024,6 +4040,15 @@ } ], "e58a1d884fa1d8f2": "Thread-Details", + "43c5fbd02c6f330a": "Weniger anzeigen", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " weitere anzeigen" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} Kommentar} other {{count} Kommentare}}", "42f634397f3960aa": "In Thread-Details anzeigen", @@ -4063,15 +4088,6 @@ ], "159ddd0d146a0f22": "Beobachtet: Der Agent wird geweckt, wenn Checks fertig sind, jemand kommentiert oder der Branch Konflikte hat. Klicke zum Beenden.", "1cbc8b5db51b4c77": "Mergen", - "43c5fbd02c6f330a": "Weniger anzeigen", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " weitere anzeigen" - ], "a3d040c4ef4fc6e9": "Über dem Tempo", "b16fdf56b16d99c9": "Im Tempo", "90f977e97ae8b6c6": "Unter dem Tempo", @@ -4086,6 +4102,7 @@ "66be4fb43249bbd2": "{used} von {max} Tokens", "ee3ae58c8b38a425": "{left} % übrig", "ebb26f93fb83a71b": "{label}: {left} % übrig", + "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.", @@ -4179,12 +4196,16 @@ ], "3237699bd13dd4bb": "Subagent stoppen", "075398ac562d74b0": "Agentensitzung trennen", + "1d2025060ba3d1c3": "Port {port} konnte nicht weitergeleitet werden", "086ecbb6f4c2e959": "Kann nicht im Browser geöffnet werden", "51052c00ab1ac8cc": "Vorschau kann nicht geöffnet werden", "0ccd37739f9cf2b6": "Server konnte nicht gestoppt werden", "a610a81c4061bb4c": "Server", + "253bc8b5e99002dc": "Weitergeleitet an :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Weiterleitung von localhost:{port} beenden", + "95bbbac2f2e17273": "localhost:{port} an diesen Rechner weiterleiten", "95b263aa683271cc": "localhost:{port} stoppen", "f94866e17faddc05": [ "Im Browser-Panel öffnen. ", @@ -4195,6 +4216,16 @@ }, " für deinen Browser." ], + "781fba367a220012": [ + "An localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " auf diesem Rechner weitergeleitet. Klicke zum Beenden." + ], + "92347683e33e9f02": "An diesen Rechner weiterleiten, für jede App hier", "3c7763243445b28d": "Server stoppen", "991cc9fb37606c91": "(leere Antwort)", "36e4b8d2db087296": "Ab dieser Antwort forken", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Video abspielen", "11a5a4d340e6397d": "Original öffnen", "1b74242b0d303272": "Video herunterladen", - "7a462e32dba47f4c": "Im Browser öffnen", "f9ca1e61d515445e": "Nutzdaten der Data-URL fehlen.", "1b547c297573369c": "Dieses eingebettete Medium konnte nicht decodiert werden.", "84f7c359e5f050b1": "Die Datei konnte nicht abgerufen werden (HTTP {status}).", @@ -11860,7 +11890,6 @@ "0bd938825ffcf992": "+{percent} % des Kontingents", "09c0e00d7fb55402": "Reset-Guthaben wird verwendet…", "4df3ff1be768a7ab": "{name}: {remaining} % übrig", - "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", "a16b48709357a5a7": "Nutzung verwalten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 442486e2decb0..a873be091b0c9 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Close", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (Local)", + "a12a4958ca6b924b": "Forwarded port {port}", + "0f14a51b016f825d": "Apps on this machine reach it at localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} on {environment}", + "7a462e32dba47f4c": "Open in browser", + "4b8087450e97c995": "Copy address", + "c170720e67d01733": "Stop forwarding", + "1e5c6d1c33667b17": "Forward localhost:{port}", + "e76f45b6a412a0b6": "Forward port {port} from {environment}", + "ecf3b95b3d9e6e74": "Forwarded", + "b3123e5b8602a134": "Type a port number to forward it", + "1bdeef9819b4a055": "Forward a port", + "de8a46b66f8ec455": "Forwarded ports", "f844c41fac2d339c": "Current", "69154433587763c0": "No matching actions.", "90c3a382ecefa0ce": "No matching commands, projects, or threads.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "This server does not support registry lookups. Update it before switching tracks.", "22da1d00403ab2fd": "Could not check this environment's npm registry. Check the connection and registry settings.", "2fc0f7a698c95c90": "Connect to a server to check releases.", + "922269f8691aa3ba": "Could not tell whether this environment runs on this computer.", + "35cade9cc8a01363": "Port forwarding needs the desktop app.", + "9e303e0a794898d4": "This environment runs on this computer, so localhost:{port} already reaches it.", + "2d49965e0e27e23b": "This environment can't be reached right now. Try again once it reconnects.", "7280baf7517dad1c": "Failed to load refs.", "567c0fed6ab8efc1": "This connection cannot search host files.", "5189720b9436f98c": "Search is limited to {count} characters.", @@ -4022,6 +4038,16 @@ } ], "e58a1d884fa1d8f2": "Thread details", + "43c5fbd02c6f330a": "Show less", + "de45b075b016cb14": [ + "Show ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " more" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comment} other {{count} comments}}", "42f634397f3960aa": "Show in thread details", @@ -4061,16 +4087,6 @@ ], "159ddd0d146a0f22": "Watching: the agent wakes when checks finish, someone comments, or the branch conflicts. Click to stop.", "1cbc8b5db51b4c77": "Merge", - "43c5fbd02c6f330a": "Show less", - "de45b075b016cb14": [ - "Show ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " more" - ], "a3d040c4ef4fc6e9": "Ahead of pace", "b16fdf56b16d99c9": "On pace", "90f977e97ae8b6c6": "Under pace", @@ -4085,6 +4101,7 @@ "66be4fb43249bbd2": "{used} of {max} tokens", "ee3ae58c8b38a425": "{left}% left", "ebb26f93fb83a71b": "{label}: {left}% left", + "1b16346722b65812": "{timeLeft}% of the window left", "728c6cc1431e76c8": "Resets in {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.", @@ -4178,12 +4195,16 @@ ], "3237699bd13dd4bb": "Stop subagent", "075398ac562d74b0": "Disconnect agent session", + "1d2025060ba3d1c3": "Could not forward port {port}", "086ecbb6f4c2e959": "Unable to open in browser", "51052c00ab1ac8cc": "Unable to open preview", "0ccd37739f9cf2b6": "Could not stop server", "a610a81c4061bb4c": "Servers", + "253bc8b5e99002dc": "Forwarded to :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Stop forwarding localhost:{port}", + "95bbbac2f2e17273": "Forward localhost:{port} to this machine", "95b263aa683271cc": "Stop localhost:{port}", "f94866e17faddc05": [ "Open in the browser panel. ", @@ -4194,6 +4215,16 @@ }, " for your browser." ], + "781fba367a220012": [ + "Forwarded to localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " on this machine. Click to stop." + ], + "92347683e33e9f02": "Forward to this machine, for any app here", "3c7763243445b28d": "Stop server", "991cc9fb37606c91": "(empty response)", "36e4b8d2db087296": "Fork from this response", @@ -5933,7 +5964,6 @@ "a74538a7917c1c96": "Play video", "11a5a4d340e6397d": "Open original", "1b74242b0d303272": "Download video", - "7a462e32dba47f4c": "Open in browser", "f9ca1e61d515445e": "Missing data URL payload.", "1b547c297573369c": "This inline media could not be decoded.", "84f7c359e5f050b1": "The file could not be fetched (HTTP {status}).", @@ -11868,7 +11898,6 @@ "0bd938825ffcf992": "+{percent}% of pool", "09c0e00d7fb55402": "Using reset credit…", "4df3ff1be768a7ab": "{name}: {remaining}% left", - "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", "a16b48709357a5a7": "Manage usage", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 87c7e9a861a93..3e730353316fe 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Cerrar", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Puerto {port} reenviado", + "0f14a51b016f825d": "Las apps de este equipo lo alcanzan en localhost:{port}.", + "4bdb9a086e77ee6d": "Puerto {port} en {environment}", + "7a462e32dba47f4c": "Abrir en el navegador", + "4b8087450e97c995": "Copiar dirección", + "c170720e67d01733": "Dejar de reenviar", + "1e5c6d1c33667b17": "Reenviar localhost:{port}", + "e76f45b6a412a0b6": "Reenviar el puerto {port} desde {environment}", + "ecf3b95b3d9e6e74": "Reenviados", + "b3123e5b8602a134": "Escribe un número de puerto para reenviarlo", + "1bdeef9819b4a055": "Reenviar un puerto", + "de8a46b66f8ec455": "Puertos reenviados", "f844c41fac2d339c": "Actual", "69154433587763c0": "No hay acciones que coincidan.", "90c3a382ecefa0ce": "No hay comandos, proyectos ni hilos que coincidan.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Este servidor no permite consultas al registro. Actualízalo antes de cambiar de canal.", "22da1d00403ab2fd": "No se pudo comprobar el registro npm de este entorno. Revisa la conexión y los ajustes del registro.", "2fc0f7a698c95c90": "Conéctate a un servidor para comprobar las versiones.", + "922269f8691aa3ba": "No se pudo saber si este entorno se ejecuta en este equipo.", + "35cade9cc8a01363": "El reenvío de puertos necesita la app de escritorio.", + "9e303e0a794898d4": "Este entorno se ejecuta en este equipo, así que localhost:{port} ya lo alcanza.", + "2d49965e0e27e23b": "No se puede acceder a este entorno ahora. Inténtalo de nuevo cuando se vuelva a conectar.", "7280baf7517dad1c": "No se pudieron cargar las refs.", "567c0fed6ab8efc1": "Esta conexión no puede buscar archivos del host.", "5189720b9436f98c": "La búsqueda está limitada a {count} caracteres.", @@ -4020,6 +4036,16 @@ } ], "e58a1d884fa1d8f2": "Detalles del hilo", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " más" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentario} other {{count} comentarios}}", "42f634397f3960aa": "Mostrar en los detalles del hilo", @@ -4059,16 +4085,6 @@ ], "159ddd0d146a0f22": "Siguiendo: el agente se activa cuando terminan las comprobaciones, alguien comenta o la rama tiene conflictos. Haz clic para dejar de seguir.", "1cbc8b5db51b4c77": "Fusionar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " más" - ], "a3d040c4ef4fc6e9": "Por encima del ritmo", "b16fdf56b16d99c9": "Al ritmo", "90f977e97ae8b6c6": "Por debajo del ritmo", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left} % restante", "ebb26f93fb83a71b": "{label}: {left} % restante", + "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "728c6cc1431e76c8": "Se restablece en {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Detener subagente", "075398ac562d74b0": "Desconectar la sesión del agente", + "1d2025060ba3d1c3": "No se pudo reenviar el puerto {port}", "086ecbb6f4c2e959": "No se puede abrir en el navegador", "51052c00ab1ac8cc": "No se puede abrir la vista previa", "0ccd37739f9cf2b6": "No se pudo detener el servidor", "a610a81c4061bb4c": "Servidores", + "253bc8b5e99002dc": "Reenviado a :{port}", "bd1ca8ccb6d0b87c": "Agente", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Dejar de reenviar localhost:{port}", + "95bbbac2f2e17273": "Reenviar localhost:{port} a este equipo", "95b263aa683271cc": "Detener localhost:{port}", "f94866e17faddc05": [ "Abrir en el panel del navegador. ", @@ -4192,6 +4213,16 @@ }, " para tu navegador." ], + "781fba367a220012": [ + "Reenviado a localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " en este equipo. Haz clic para detenerlo." + ], + "92347683e33e9f02": "Reenviar a este equipo, para cualquier app aquí", "3c7763243445b28d": "Detener servidor", "991cc9fb37606c91": "(respuesta vacía)", "36e4b8d2db087296": "Bifurcar desde esta respuesta", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Reproducir vídeo", "11a5a4d340e6397d": "Abrir original", "1b74242b0d303272": "Descargar vídeo", - "7a462e32dba47f4c": "Abrir en el navegador", "f9ca1e61d515445e": "Falta el contenido de la URL de datos.", "1b547c297573369c": "No se pudo decodificar este contenido en línea.", "84f7c359e5f050b1": "No se pudo obtener el archivo (HTTP {status}).", @@ -11853,7 +11883,6 @@ "0bd938825ffcf992": "+{percent}% del total", "09c0e00d7fb55402": "Usando el crédito de restablecimiento…", "4df3ff1be768a7ab": "{name}: queda un {remaining}%", - "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", "a16b48709357a5a7": "Gestionar uso", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a3a16e772103e..24dba2e932684 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Fermer", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Port {port} redirigé", + "0f14a51b016f825d": "Les apps de cette machine l’atteignent sur localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} sur {environment}", + "7a462e32dba47f4c": "Ouvrir dans le navigateur", + "4b8087450e97c995": "Copier l’adresse", + "c170720e67d01733": "Arrêter la redirection", + "1e5c6d1c33667b17": "Rediriger localhost:{port}", + "e76f45b6a412a0b6": "Rediriger le port {port} depuis {environment}", + "ecf3b95b3d9e6e74": "Redirigés", + "b3123e5b8602a134": "Saisis un numéro de port pour le rediriger", + "1bdeef9819b4a055": "Rediriger un port", + "de8a46b66f8ec455": "Ports redirigés", "f844c41fac2d339c": "Actuel", "69154433587763c0": "Aucune action correspondante.", "90c3a382ecefa0ce": "Aucune commande, aucun projet ni aucun fil correspondant.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Ce serveur ne prend pas en charge les recherches dans le registre. Mettez-le à jour avant de changer de canal.", "22da1d00403ab2fd": "Impossible de vérifier le registre npm de cet environnement. Vérifiez la connexion et les paramètres du registre.", "2fc0f7a698c95c90": "Connectez-vous à un serveur pour vérifier les versions.", + "922269f8691aa3ba": "Impossible de savoir si cet environnement tourne sur cet ordinateur.", + "35cade9cc8a01363": "La redirection de ports nécessite l’app de bureau.", + "9e303e0a794898d4": "Cet environnement tourne sur cet ordinateur, donc localhost:{port} l’atteint déjà.", + "2d49965e0e27e23b": "Cet environnement est injoignable pour le moment. Réessaie une fois qu’il est reconnecté.", "7280baf7517dad1c": "Échec du chargement des refs.", "567c0fed6ab8efc1": "Cette connexion ne peut pas rechercher dans les fichiers de l’hôte.", "5189720b9436f98c": "La recherche est limitée à {count} caractères.", @@ -4021,6 +4037,16 @@ } ], "e58a1d884fa1d8f2": "Détails du fil", + "43c5fbd02c6f330a": "Afficher moins", + "de45b075b016cb14": [ + "Afficher ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " de plus" + ], "02d9667ff2c8e0b8": "Ticket {key} : {title}", "4276743ee60a3c62": "{count, plural, one {{count} commentaire} other {{count} commentaires}}", "42f634397f3960aa": "Afficher dans les détails du fil", @@ -4060,16 +4086,6 @@ ], "159ddd0d146a0f22": "Surveillance : l’agent se réveille quand les checks se terminent, que quelqu’un commente ou que la branche entre en conflit. Cliquez pour arrêter.", "1cbc8b5db51b4c77": "Fusionner", - "43c5fbd02c6f330a": "Afficher moins", - "de45b075b016cb14": [ - "Afficher ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " de plus" - ], "a3d040c4ef4fc6e9": "En avance sur le rythme", "b16fdf56b16d99c9": "Dans le rythme", "90f977e97ae8b6c6": "En dessous du rythme", @@ -4084,6 +4100,7 @@ "66be4fb43249bbd2": "{used} tokens sur {max}", "ee3ae58c8b38a425": "{left} % restant", "ebb26f93fb83a71b": "{label} : {left} % restant", + "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}", "e16b0b9b490c8bc7": "{label} : {value}", "ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.", @@ -4177,12 +4194,16 @@ ], "3237699bd13dd4bb": "Arrêter le sous-agent", "075398ac562d74b0": "Déconnecter la session de l’agent", + "1d2025060ba3d1c3": "Impossible de rediriger le port {port}", "086ecbb6f4c2e959": "Impossible d’ouvrir dans le navigateur", "51052c00ab1ac8cc": "Impossible d’ouvrir l’aperçu", "0ccd37739f9cf2b6": "Impossible d’arrêter le serveur", "a610a81c4061bb4c": "Serveurs", + "253bc8b5e99002dc": "Redirigé vers :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Arrêter de rediriger localhost:{port}", + "95bbbac2f2e17273": "Rediriger localhost:{port} vers cette machine", "95b263aa683271cc": "Arrêter localhost:{port}", "f94866e17faddc05": [ "Ouvrir dans le panneau du navigateur. ", @@ -4193,6 +4214,16 @@ }, " pour votre navigateur." ], + "781fba367a220012": [ + "Redirigé vers localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " sur cette machine. Clique pour arrêter." + ], + "92347683e33e9f02": "Rediriger vers cette machine, pour toute app ici", "3c7763243445b28d": "Arrêter le serveur", "991cc9fb37606c91": "(réponse vide)", "36e4b8d2db087296": "Créer un fork depuis cette réponse", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Lire la vidéo", "11a5a4d340e6397d": "Ouvrir l’original", "1b74242b0d303272": "Télécharger la vidéo", - "7a462e32dba47f4c": "Ouvrir dans le navigateur", "f9ca1e61d515445e": "Contenu de la data URL manquant.", "1b547c297573369c": "Impossible de décoder ce média intégré.", "84f7c359e5f050b1": "Impossible de récupérer le fichier (HTTP {status}).", @@ -11858,7 +11888,6 @@ "0bd938825ffcf992": "+{percent} % du quota", "09c0e00d7fb55402": "Utilisation du crédit de réinitialisation…", "4df3ff1be768a7ab": "{name} : {remaining} % restant", - "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", "a16b48709357a5a7": "Gérer l’utilisation", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8459e9cf87854..e88cc490a8590 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1839,6 +1839,18 @@ "480646ceb98c7163": "閉じる", "32fc9124998ebc18": "ローカル", "1c4158d741eec5da": "{label} (ローカル)", + "a12a4958ca6b924b": "ポート {port} を転送しました", + "0f14a51b016f825d": "このマシンのアプリから localhost:{port} でアクセスできます。", + "4bdb9a086e77ee6d": "{environment} のポート {port}", + "7a462e32dba47f4c": "ブラウザーで開く", + "4b8087450e97c995": "アドレスをコピー", + "c170720e67d01733": "転送を停止", + "1e5c6d1c33667b17": "localhost:{port} を転送", + "e76f45b6a412a0b6": "{environment} からポート {port} を転送", + "ecf3b95b3d9e6e74": "転送中", + "b3123e5b8602a134": "転送するポート番号を入力", + "1bdeef9819b4a055": "ポートを転送", + "de8a46b66f8ec455": "転送中のポート", "f844c41fac2d339c": "現在", "69154433587763c0": "一致するアクションはありません。", "90c3a382ecefa0ce": "一致するコマンド、プロジェクト、スレッドはありません。", @@ -2972,6 +2984,10 @@ "314cdccee9c14774": "このサーバーはレジストリの検索をサポートしていません。トラックを切り替える前に更新してください。", "22da1d00403ab2fd": "この環境の npm レジストリを確認できませんでした。接続とレジストリの設定を確認してください。", "2fc0f7a698c95c90": "リリースを確認するにはサーバーに接続してください。", + "922269f8691aa3ba": "この環境がこのコンピューターで動いているか判断できませんでした。", + "35cade9cc8a01363": "ポート転送にはデスクトップアプリが必要です。", + "9e303e0a794898d4": "この環境はこのコンピューターで動いているため、localhost:{port} で既にアクセスできます。", + "2d49965e0e27e23b": "現在この環境に接続できません。再接続されてからもう一度お試しください。", "7280baf7517dad1c": "ref を読み込めませんでした。", "567c0fed6ab8efc1": "この接続ではホストのファイルを検索できません。", "5189720b9436f98c": "検索は {count} 文字までです。", @@ -4011,6 +4027,16 @@ } ], "e58a1d884fa1d8f2": "スレッドの詳細", + "43c5fbd02c6f330a": "表示を減らす", + "de45b075b016cb14": [ + "さらに ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 件を表示" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, other {{count} 件のコメント}}", "42f634397f3960aa": "スレッドの詳細に表示", @@ -4050,16 +4076,6 @@ ], "159ddd0d146a0f22": "監視中: チェックの完了、コメントの追加、ブランチの競合が発生するとエージェントが起動します。クリックすると停止します。", "1cbc8b5db51b4c77": "マージ", - "43c5fbd02c6f330a": "表示を減らす", - "de45b075b016cb14": [ - "さらに ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 件を表示" - ], "a3d040c4ef4fc6e9": "ペースより速い", "b16fdf56b16d99c9": "ペースどおり", "90f977e97ae8b6c6": "ペースより遅い", @@ -4074,6 +4090,7 @@ "66be4fb43249bbd2": "{used} / {max} トークン", "ee3ae58c8b38a425": "残り {left}%", "ebb26f93fb83a71b": "{label}: 残り {left}%", + "1b16346722b65812": "期間の残り {timeLeft}%", "728c6cc1431e76c8": "{duration} 後にリセット · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。", @@ -4167,12 +4184,16 @@ ], "3237699bd13dd4bb": "サブエージェントを停止", "075398ac562d74b0": "エージェントのセッションを切断", + "1d2025060ba3d1c3": "ポート {port} を転送できませんでした", "086ecbb6f4c2e959": "ブラウザーで開けません", "51052c00ab1ac8cc": "プレビューを開けません", "0ccd37739f9cf2b6": "サーバーを停止できませんでした", "a610a81c4061bb4c": "サーバー", + "253bc8b5e99002dc": ":{port} に転送中", "bd1ca8ccb6d0b87c": "エージェント", "e25e045607262b40": "ターミナル", + "194a9791a83d3f79": "localhost:{port} の転送を停止", + "95bbbac2f2e17273": "localhost:{port} をこのマシンに転送", "95b263aa683271cc": "localhost:{port} を停止", "f94866e17faddc05": [ "ブラウザーパネルで開きます。", @@ -4183,6 +4204,16 @@ }, " で自分のブラウザーで開きます。" ], + "781fba367a220012": [ + "このマシンの localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " に転送中です。クリックで停止します。" + ], + "92347683e33e9f02": "このマシンに転送し、ここのどのアプリからも使えるようにする", "3c7763243445b28d": "サーバーを停止", "991cc9fb37606c91": "(空のレスポンス)", "36e4b8d2db087296": "この応答からフォーク", @@ -5913,7 +5944,6 @@ "a74538a7917c1c96": "動画を再生", "11a5a4d340e6397d": "元のファイルを開く", "1b74242b0d303272": "動画をダウンロード", - "7a462e32dba47f4c": "ブラウザーで開く", "f9ca1e61d515445e": "データ URL のペイロードがありません。", "1b547c297573369c": "このインラインメディアをデコードできませんでした。", "84f7c359e5f050b1": "ファイルを取得できませんでした (HTTP {status})。", @@ -11808,7 +11838,6 @@ "0bd938825ffcf992": "プールの +{percent}%", "09c0e00d7fb55402": "リセットクレジットを使用しています…", "4df3ff1be768a7ab": "{name}: 残り {remaining}%", - "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "使用量を管理", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c523c5dc7b1fc..c80d5dc373208 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "닫기", "32fc9124998ebc18": "로컬", "1c4158d741eec5da": "{label}(로컬)", + "a12a4958ca6b924b": "포트 {port}을(를) 포워딩했습니다", + "0f14a51b016f825d": "이 컴퓨터의 앱에서 localhost:{port}로 접속할 수 있습니다.", + "4bdb9a086e77ee6d": "{environment}의 포트 {port}", + "7a462e32dba47f4c": "브라우저에서 열기", + "4b8087450e97c995": "주소 복사", + "c170720e67d01733": "포워딩 중지", + "1e5c6d1c33667b17": "localhost:{port} 포워딩", + "e76f45b6a412a0b6": "{environment}에서 포트 {port} 포워딩", + "ecf3b95b3d9e6e74": "포워딩됨", + "b3123e5b8602a134": "포워딩할 포트 번호를 입력하세요", + "1bdeef9819b4a055": "포트 포워딩", + "de8a46b66f8ec455": "포워딩된 포트", "f844c41fac2d339c": "현재", "69154433587763c0": "일치하는 작업이 없습니다.", "90c3a382ecefa0ce": "일치하는 명령, 프로젝트, 스레드가 없습니다.", @@ -2973,6 +2985,10 @@ "314cdccee9c14774": "이 서버는 레지스트리 조회를 지원하지 않습니다. 트랙을 전환하기 전에 업데이트하세요.", "22da1d00403ab2fd": "이 환경의 npm 레지스트리를 확인할 수 없습니다. 연결 및 레지스트리 설정을 확인하세요.", "2fc0f7a698c95c90": "릴리스를 확인하려면 서버에 연결하세요.", + "922269f8691aa3ba": "이 환경이 이 컴퓨터에서 실행 중인지 확인할 수 없습니다.", + "35cade9cc8a01363": "포트 포워딩은 데스크톱 앱이 필요합니다.", + "9e303e0a794898d4": "이 환경은 이 컴퓨터에서 실행 중이므로 localhost:{port}로 이미 접속할 수 있습니다.", + "2d49965e0e27e23b": "지금은 이 환경에 연결할 수 없습니다. 다시 연결되면 다시 시도하세요.", "7280baf7517dad1c": "참조를 불러오지 못했습니다.", "567c0fed6ab8efc1": "이 연결로는 호스트 파일을 검색할 수 없습니다.", "5189720b9436f98c": "검색어는 {count}자로 제한됩니다.", @@ -4009,6 +4025,15 @@ } ], "e58a1d884fa1d8f2": "스레드 세부 정보", + "43c5fbd02c6f330a": "간략히 보기", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "개 더 보기" + ], "02d9667ff2c8e0b8": "이슈 {key}: {title}", "4276743ee60a3c62": "{count, plural, other {댓글 {count}개}}", "42f634397f3960aa": "스레드 세부 정보에 표시", @@ -4048,15 +4073,6 @@ ], "159ddd0d146a0f22": "지켜보는 중: 검사가 끝나거나, 누군가 댓글을 달거나, 브랜치가 충돌하면 에이전트가 깨어납니다. 클릭하여 중지하세요.", "1cbc8b5db51b4c77": "병합", - "43c5fbd02c6f330a": "간략히 보기", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "개 더 보기" - ], "a3d040c4ef4fc6e9": "예상보다 빠름", "b16fdf56b16d99c9": "예상대로", "90f977e97ae8b6c6": "예상보다 느림", @@ -4071,6 +4087,7 @@ "66be4fb43249bbd2": "토큰 {max}개 중 {used}개", "ee3ae58c8b38a425": "{left}% 남음", "ebb26f93fb83a71b": "{label}: {left}% 남음", + "1b16346722b65812": "기간 {timeLeft}% 남음", "728c6cc1431e76c8": "{duration} 후 초기화 · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.", @@ -4164,12 +4181,16 @@ ], "3237699bd13dd4bb": "서브에이전트 중지", "075398ac562d74b0": "에이전트 세션 연결 끊기", + "1d2025060ba3d1c3": "포트 {port}을(를) 포워딩할 수 없습니다", "086ecbb6f4c2e959": "브라우저에서 열 수 없습니다", "51052c00ab1ac8cc": "미리 보기를 열 수 없습니다", "0ccd37739f9cf2b6": "서버를 중지할 수 없습니다", "a610a81c4061bb4c": "서버", + "253bc8b5e99002dc": ":{port}로 포워딩됨", "bd1ca8ccb6d0b87c": "에이전트", "e25e045607262b40": "터미널", + "194a9791a83d3f79": "localhost:{port} 포워딩 중지", + "95bbbac2f2e17273": "localhost:{port}을(를) 이 컴퓨터로 포워딩", "95b263aa683271cc": "localhost:{port} 중지", "f94866e17faddc05": [ "브라우저 패널에서 엽니다. ", @@ -4180,6 +4201,16 @@ }, "하면 내 브라우저에서 엽니다." ], + "781fba367a220012": [ + "이 컴퓨터의 localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "(으)로 포워딩 중입니다. 클릭하면 중지합니다." + ], + "92347683e33e9f02": "이 컴퓨터로 포워딩해 여기 있는 모든 앱에서 사용", "3c7763243445b28d": "서버 중지", "991cc9fb37606c91": "(빈 응답)", "36e4b8d2db087296": "이 응답에서 포크", @@ -5911,7 +5942,6 @@ "a74538a7917c1c96": "동영상 재생", "11a5a4d340e6397d": "원본 열기", "1b74242b0d303272": "동영상 다운로드", - "7a462e32dba47f4c": "브라우저에서 열기", "f9ca1e61d515445e": "데이터 URL 페이로드가 없습니다.", "1b547c297573369c": "이 인라인 미디어를 디코딩할 수 없습니다.", "84f7c359e5f050b1": "파일을 가져올 수 없습니다(HTTP {status}).", @@ -11805,7 +11835,6 @@ "0bd938825ffcf992": "풀의 +{percent}%", "09c0e00d7fb55402": "초기화 크레딧 사용 중…", "4df3ff1be768a7ab": "{name}: {remaining}% 남음", - "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", "a16b48709357a5a7": "사용량 관리", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index bd34cd96c3d8b..a2a2daa2b7ccc 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Fechar", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Porta {port} encaminhada", + "0f14a51b016f825d": "Os apps desta máquina a acessam em localhost:{port}.", + "4bdb9a086e77ee6d": "Porta {port} em {environment}", + "7a462e32dba47f4c": "Abrir no navegador", + "4b8087450e97c995": "Copiar endereço", + "c170720e67d01733": "Parar de encaminhar", + "1e5c6d1c33667b17": "Encaminhar localhost:{port}", + "e76f45b6a412a0b6": "Encaminhar a porta {port} de {environment}", + "ecf3b95b3d9e6e74": "Encaminhadas", + "b3123e5b8602a134": "Digite um número de porta para encaminhá-la", + "1bdeef9819b4a055": "Encaminhar uma porta", + "de8a46b66f8ec455": "Portas encaminhadas", "f844c41fac2d339c": "Atual", "69154433587763c0": "Nenhuma ação correspondente.", "90c3a382ecefa0ce": "Nenhum comando, projeto ou thread correspondente.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Este servidor não permite consultas ao registro. Atualize-o antes de trocar de canal.", "22da1d00403ab2fd": "Não foi possível verificar o registro npm deste ambiente. Verifique a conexão e as configurações do registro.", "2fc0f7a698c95c90": "Conecte-se a um servidor para verificar as versões.", + "922269f8691aa3ba": "Não foi possível saber se este ambiente roda neste computador.", + "35cade9cc8a01363": "O encaminhamento de portas precisa do app para desktop.", + "9e303e0a794898d4": "Este ambiente roda neste computador, então localhost:{port} já o alcança.", + "2d49965e0e27e23b": "Não é possível acessar este ambiente agora. Tente novamente quando ele se reconectar.", "7280baf7517dad1c": "Falha ao carregar as refs.", "567c0fed6ab8efc1": "Esta conexão não pode pesquisar arquivos do host.", "5189720b9436f98c": "A pesquisa é limitada a {count} caracteres.", @@ -4021,6 +4037,15 @@ } ], "e58a1d884fa1d8f2": "Detalhes da thread", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar mais ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentário} other {{count} comentários}}", "42f634397f3960aa": "Mostrar nos detalhes da thread", @@ -4060,15 +4085,6 @@ ], "159ddd0d146a0f22": "Acompanhando: o agente é ativado quando as verificações terminam, alguém comenta ou o branch entra em conflito. Clique para parar.", "1cbc8b5db51b4c77": "Mesclar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar mais ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Acima do ritmo", "b16fdf56b16d99c9": "No ritmo", "90f977e97ae8b6c6": "Abaixo do ritmo", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left}% restante", "ebb26f93fb83a71b": "{label}: {left}% restante", + "1b16346722b65812": "{timeLeft}% da janela restante", "728c6cc1431e76c8": "Renova em {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Parar subagente", "075398ac562d74b0": "Desconectar a sessão do agente", + "1d2025060ba3d1c3": "Não foi possível encaminhar a porta {port}", "086ecbb6f4c2e959": "Não foi possível abrir no navegador", "51052c00ab1ac8cc": "Não foi possível abrir a pré-visualização", "0ccd37739f9cf2b6": "Não foi possível parar o servidor", "a610a81c4061bb4c": "Servidores", + "253bc8b5e99002dc": "Encaminhada para :{port}", "bd1ca8ccb6d0b87c": "Agente", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Parar de encaminhar localhost:{port}", + "95bbbac2f2e17273": "Encaminhar localhost:{port} para esta máquina", "95b263aa683271cc": "Parar localhost:{port}", "f94866e17faddc05": [ "Abrir no painel do navegador. ", @@ -4192,6 +4213,16 @@ }, " para o seu navegador." ], + "781fba367a220012": [ + "Encaminhada para localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " nesta máquina. Clique para parar." + ], + "92347683e33e9f02": "Encaminhar para esta máquina, para qualquer app aqui", "3c7763243445b28d": "Parar servidor", "991cc9fb37606c91": "(resposta vazia)", "36e4b8d2db087296": "Criar fork a partir desta resposta", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Reproduzir vídeo", "11a5a4d340e6397d": "Abrir original", "1b74242b0d303272": "Baixar vídeo", - "7a462e32dba47f4c": "Abrir no navegador", "f9ca1e61d515445e": "Falta o conteúdo da data URL.", "1b547c297573369c": "Não foi possível decodificar esta mídia em linha.", "84f7c359e5f050b1": "Não foi possível buscar o arquivo (HTTP {status}).", @@ -11857,7 +11887,6 @@ "0bd938825ffcf992": "+{percent}% do total", "09c0e00d7fb55402": "Usando crédito de redefinição…", "4df3ff1be768a7ab": "{name}: {remaining}% restante", - "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", "a16b48709357a5a7": "Gerenciar uso", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4242d78d5f3c5..852b80217f746 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Закрыть", "32fc9124998ebc18": "Локально", "1c4158d741eec5da": "{label} (локально)", + "a12a4958ca6b924b": "Порт {port} перенаправлен", + "0f14a51b016f825d": "Приложения на этом компьютере открывают его по адресу localhost:{port}.", + "4bdb9a086e77ee6d": "Порт {port} в {environment}", + "7a462e32dba47f4c": "Открыть в браузере", + "4b8087450e97c995": "Копировать адрес", + "c170720e67d01733": "Остановить перенаправление", + "1e5c6d1c33667b17": "Перенаправить localhost:{port}", + "e76f45b6a412a0b6": "Перенаправить порт {port} из {environment}", + "ecf3b95b3d9e6e74": "Перенаправленные", + "b3123e5b8602a134": "Введите номер порта, чтобы перенаправить его", + "1bdeef9819b4a055": "Перенаправить порт", + "de8a46b66f8ec455": "Перенаправленные порты", "f844c41fac2d339c": "Текущий", "69154433587763c0": "Нет подходящих действий.", "90c3a382ecefa0ce": "Нет подходящих команд, проектов или тредов.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Этот сервер не поддерживает запросы к реестру. Обновите его перед сменой канала.", "22da1d00403ab2fd": "Не удалось проверить реестр npm этого окружения. Проверьте подключение и настройки реестра.", "2fc0f7a698c95c90": "Подключитесь к серверу, чтобы проверить выпуски.", + "922269f8691aa3ba": "Не удалось определить, работает ли это окружение на этом компьютере.", + "35cade9cc8a01363": "Для перенаправления портов нужно приложение для компьютера.", + "9e303e0a794898d4": "Это окружение работает на этом компьютере, поэтому localhost:{port} уже ведёт к нему.", + "2d49965e0e27e23b": "Сейчас это окружение недоступно. Попробуйте снова, когда оно переподключится.", "7280baf7517dad1c": "Не удалось загрузить ссылки.", "567c0fed6ab8efc1": "Это подключение не может искать файлы на хосте.", "5189720b9436f98c": "Поиск ограничен {count} символами.", @@ -4021,6 +4037,15 @@ } ], "e58a1d884fa1d8f2": "Сведения о треде", + "43c5fbd02c6f330a": "Показать меньше", + "de45b075b016cb14": [ + "Показать ещё ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} комментарий} few {{count} комментария} many {{count} комментариев} other {{count} комментария}}", "42f634397f3960aa": "Показывать в сведениях о треде", @@ -4060,15 +4085,6 @@ ], "159ddd0d146a0f22": "Отслеживается: агент проснётся, когда завершатся проверки, кто-то оставит комментарий или в ветке появится конфликт. Нажмите, чтобы прекратить.", "1cbc8b5db51b4c77": "Слить", - "43c5fbd02c6f330a": "Показать меньше", - "de45b075b016cb14": [ - "Показать ещё ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Быстрее темпа", "b16fdf56b16d99c9": "В темпе", "90f977e97ae8b6c6": "Медленнее темпа", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} из {max} токенов", "ee3ae58c8b38a425": "Осталось {left}%", "ebb26f93fb83a71b": "{label}: осталось {left}%", + "1b16346722b65812": "От окна осталось {timeLeft}%", "728c6cc1431e76c8": "Сброс через {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Остановить субагента", "075398ac562d74b0": "Отключить сеанс агента", + "1d2025060ba3d1c3": "Не удалось перенаправить порт {port}", "086ecbb6f4c2e959": "Не удалось открыть в браузере", "51052c00ab1ac8cc": "Не удалось открыть предпросмотр", "0ccd37739f9cf2b6": "Не удалось остановить сервер", "a610a81c4061bb4c": "Серверы", + "253bc8b5e99002dc": "Перенаправлен на :{port}", "bd1ca8ccb6d0b87c": "Агент", "e25e045607262b40": "Терминал", + "194a9791a83d3f79": "Остановить перенаправление localhost:{port}", + "95bbbac2f2e17273": "Перенаправить localhost:{port} на этот компьютер", "95b263aa683271cc": "Остановить localhost:{port}", "f94866e17faddc05": [ "Открыть в панели браузера. ", @@ -4192,6 +4213,16 @@ }, " — в вашем браузере." ], + "781fba367a220012": [ + "Перенаправлен на localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " на этом компьютере. Нажмите, чтобы остановить." + ], + "92347683e33e9f02": "Перенаправить на этот компьютер для любых приложений", "3c7763243445b28d": "Остановить сервер", "991cc9fb37606c91": "(пустой ответ)", "36e4b8d2db087296": "Ответвить от этого ответа", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Воспроизвести видео", "11a5a4d340e6397d": "Открыть оригинал", "1b74242b0d303272": "Скачать видео", - "7a462e32dba47f4c": "Открыть в браузере", "f9ca1e61d515445e": "Нет данных data URL.", "1b547c297573369c": "Не удалось декодировать это встроенное медиа.", "84f7c359e5f050b1": "Не удалось получить файл (HTTP {status}).", @@ -11858,7 +11888,6 @@ "0bd938825ffcf992": "+{percent}% пула", "09c0e00d7fb55402": "Использование кредита на сброс…", "4df3ff1be768a7ab": "{name}: осталось {remaining}%", - "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", "a16b48709357a5a7": "Управление использованием", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d3d7bec015020..f8c06f7408c75 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Stäng", "32fc9124998ebc18": "Lokal", "1c4158d741eec5da": "{label} (lokal)", + "a12a4958ca6b924b": "Port {port} vidarebefordrad", + "0f14a51b016f825d": "Appar på den här datorn når den på localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} på {environment}", + "7a462e32dba47f4c": "Öppna i webbläsaren", + "4b8087450e97c995": "Kopiera adress", + "c170720e67d01733": "Sluta vidarebefordra", + "1e5c6d1c33667b17": "Vidarebefordra localhost:{port}", + "e76f45b6a412a0b6": "Vidarebefordra port {port} från {environment}", + "ecf3b95b3d9e6e74": "Vidarebefordrade", + "b3123e5b8602a134": "Skriv ett portnummer för att vidarebefordra det", + "1bdeef9819b4a055": "Vidarebefordra en port", + "de8a46b66f8ec455": "Vidarebefordrade portar", "f844c41fac2d339c": "Aktuellt", "69154433587763c0": "Inga matchande åtgärder.", "90c3a382ecefa0ce": "Inga matchande kommandon, projekt eller trådar.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Den här servern stöder inte registeruppslag. Uppdatera den innan du byter spår.", "22da1d00403ab2fd": "Kunde inte kontrollera den här miljöns npm-register. Kontrollera anslutningen och registerinställningarna.", "2fc0f7a698c95c90": "Anslut till en server för att söka efter versioner.", + "922269f8691aa3ba": "Det gick inte att avgöra om den här miljön körs på den här datorn.", + "35cade9cc8a01363": "Portvidarebefordring kräver skrivbordsappen.", + "9e303e0a794898d4": "Den här miljön körs på den här datorn, så localhost:{port} når den redan.", + "2d49965e0e27e23b": "Den här miljön går inte att nå just nu. Försök igen när den har anslutit igen.", "7280baf7517dad1c": "Det gick inte att läsa in refs.", "567c0fed6ab8efc1": "Den här anslutningen kan inte söka i värdens filer.", "5189720b9436f98c": "Sökningen är begränsad till {count} tecken.", @@ -4021,6 +4037,16 @@ } ], "e58a1d884fa1d8f2": "Tråddetaljer", + "43c5fbd02c6f330a": "Visa mindre", + "de45b075b016cb14": [ + "Visa ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " till" + ], "02d9667ff2c8e0b8": "Ärende {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} kommentar} other {{count} kommentarer}}", "42f634397f3960aa": "Visa i tråddetaljer", @@ -4060,16 +4086,6 @@ ], "159ddd0d146a0f22": "Bevakar: agenten vaknar när kontrollerna är klara, någon kommenterar eller grenen får konflikter. Klicka för att sluta.", "1cbc8b5db51b4c77": "Merga", - "43c5fbd02c6f330a": "Visa mindre", - "de45b075b016cb14": [ - "Visa ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " till" - ], "a3d040c4ef4fc6e9": "Före takten", "b16fdf56b16d99c9": "I takt", "90f977e97ae8b6c6": "Under takten", @@ -4084,6 +4100,7 @@ "66be4fb43249bbd2": "{used} av {max} token", "ee3ae58c8b38a425": "{left} % kvar", "ebb26f93fb83a71b": "{label}: {left} % kvar", + "1b16346722b65812": "{timeLeft} % av fönstret kvar", "728c6cc1431e76c8": "Återställs om {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.", @@ -4177,12 +4194,16 @@ ], "3237699bd13dd4bb": "Stoppa subagent", "075398ac562d74b0": "Koppla från agentsession", + "1d2025060ba3d1c3": "Kunde inte vidarebefordra port {port}", "086ecbb6f4c2e959": "Det gick inte att öppna i webbläsaren", "51052c00ab1ac8cc": "Det gick inte att öppna förhandsvisningen", "0ccd37739f9cf2b6": "Kunde inte stoppa servern", "a610a81c4061bb4c": "Servrar", + "253bc8b5e99002dc": "Vidarebefordrad till :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Sluta vidarebefordra localhost:{port}", + "95bbbac2f2e17273": "Vidarebefordra localhost:{port} till den här datorn", "95b263aa683271cc": "Stoppa localhost:{port}", "f94866e17faddc05": [ "Öppna i webbläsarpanelen. ", @@ -4193,6 +4214,16 @@ }, " för din webbläsare." ], + "781fba367a220012": [ + "Vidarebefordrad till localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " på den här datorn. Klicka för att stoppa." + ], + "92347683e33e9f02": "Vidarebefordra till den här datorn, för alla appar här", "3c7763243445b28d": "Stoppa server", "991cc9fb37606c91": "(tomt svar)", "36e4b8d2db087296": "Forka från det här svaret", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Spela upp video", "11a5a4d340e6397d": "Öppna original", "1b74242b0d303272": "Ladda ned video", - "7a462e32dba47f4c": "Öppna i webbläsaren", "f9ca1e61d515445e": "Data-URL:ens innehåll saknas.", "1b547c297573369c": "Det här inbäddade mediet kunde inte avkodas.", "84f7c359e5f050b1": "Filen kunde inte hämtas (HTTP {status}).", @@ -11866,7 +11896,6 @@ "0bd938825ffcf992": "+{percent} % av poolen", "09c0e00d7fb55402": "Använder återställningskredit…", "4df3ff1be768a7ab": "{name}: {remaining} % kvar", - "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", "a16b48709357a5a7": "Hantera användning", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5923adef292f5..74245c4e54300 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1842,6 +1842,18 @@ "480646ceb98c7163": "关闭", "32fc9124998ebc18": "本地", "1c4158d741eec5da": "{label}(本地)", + "a12a4958ca6b924b": "已转发端口 {port}", + "0f14a51b016f825d": "本机上的应用可通过 localhost:{port} 访问它。", + "4bdb9a086e77ee6d": "{environment} 上的端口 {port}", + "7a462e32dba47f4c": "在浏览器中打开", + "4b8087450e97c995": "复制地址", + "c170720e67d01733": "停止转发", + "1e5c6d1c33667b17": "转发 localhost:{port}", + "e76f45b6a412a0b6": "从 {environment} 转发端口 {port}", + "ecf3b95b3d9e6e74": "已转发", + "b3123e5b8602a134": "输入端口号以转发", + "1bdeef9819b4a055": "转发端口", + "de8a46b66f8ec455": "已转发的端口", "f844c41fac2d339c": "当前", "69154433587763c0": "没有匹配的操作。", "90c3a382ecefa0ce": "没有匹配的命令、项目或会话。", @@ -2978,6 +2990,10 @@ "314cdccee9c14774": "此服务器不支持查询仓库。请先更新,再切换通道。", "22da1d00403ab2fd": "无法检查此环境的 npm 仓库。请检查连接和仓库设置。", "2fc0f7a698c95c90": "连接一个服务器以检查版本。", + "922269f8691aa3ba": "无法判断此环境是否运行在这台计算机上。", + "35cade9cc8a01363": "端口转发需要桌面应用。", + "9e303e0a794898d4": "此环境运行在这台计算机上,localhost:{port} 已经可以访问它。", + "2d49965e0e27e23b": "目前无法访问此环境。请在它重新连接后再试。", "7280baf7517dad1c": "无法加载引用。", "567c0fed6ab8efc1": "此连接无法搜索主机文件。", "5189720b9436f98c": "搜索最多 {count} 个字符。", @@ -4026,6 +4042,16 @@ } ], "e58a1d884fa1d8f2": "会话详情", + "43c5fbd02c6f330a": "收起", + "de45b075b016cb14": [ + "再显示 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 个" + ], "02d9667ff2c8e0b8": "issue {key}:{title}", "4276743ee60a3c62": "{count, plural, other {{count} 条评论}}", "42f634397f3960aa": "在会话详情中显示", @@ -4066,16 +4092,6 @@ ], "159ddd0d146a0f22": "关注中:检查完成、有人评论或分支出现冲突时,智能体会被唤醒。点击停止关注。", "1cbc8b5db51b4c77": "合并", - "43c5fbd02c6f330a": "收起", - "de45b075b016cb14": [ - "再显示 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 个" - ], "a3d040c4ef4fc6e9": "用量消耗偏快", "b16fdf56b16d99c9": "用量消耗适中", "90f977e97ae8b6c6": "用量消耗偏慢", @@ -4090,6 +4106,7 @@ "66be4fb43249bbd2": "{used} / {max} token", "ee3ae58c8b38a425": "剩余 {left}%", "ebb26f93fb83a71b": "{label}:剩余 {left}%", + "1b16346722b65812": "窗口剩余 {timeLeft}%", "728c6cc1431e76c8": "{duration} 后重置 · {time}", "e16b0b9b490c8bc7": "{label}:{value}", "ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。", @@ -4183,12 +4200,16 @@ ], "3237699bd13dd4bb": "停止子智能体", "075398ac562d74b0": "断开智能体会话", + "1d2025060ba3d1c3": "无法转发端口 {port}", "086ecbb6f4c2e959": "无法在浏览器中打开", "51052c00ab1ac8cc": "无法打开预览", "0ccd37739f9cf2b6": "无法停止服务器", "a610a81c4061bb4c": "服务器", + "253bc8b5e99002dc": "已转发到 :{port}", "bd1ca8ccb6d0b87c": "智能体", "e25e045607262b40": "终端", + "194a9791a83d3f79": "停止转发 localhost:{port}", + "95bbbac2f2e17273": "将 localhost:{port} 转发到本机", "95b263aa683271cc": "停止 localhost:{port}", "f94866e17faddc05": [ "在浏览器面板中打开。", @@ -4199,6 +4220,16 @@ }, " 以在你的浏览器中打开。" ], + "781fba367a220012": [ + "已转发到本机的 localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "。点击停止。" + ], + "92347683e33e9f02": "转发到本机,供这里的任何应用使用", "3c7763243445b28d": "停止服务器", "991cc9fb37606c91": "(空响应)", "36e4b8d2db087296": "从这条回复分叉", @@ -5938,7 +5969,6 @@ "a74538a7917c1c96": "播放视频", "11a5a4d340e6397d": "打开原始链接", "1b74242b0d303272": "下载视频", - "7a462e32dba47f4c": "在浏览器中打开", "f9ca1e61d515445e": "缺少 data URL 数据。", "1b547c297573369c": "无法解码此内嵌媒体。", "84f7c359e5f050b1": "无法获取该文件(HTTP {status})。", @@ -11883,7 +11913,6 @@ "0bd938825ffcf992": "+{percent}%(按共享池总额度计算)", "09c0e00d7fb55402": "正在使用重置额度…", "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", - "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "管理用量", diff --git a/apps/web/src/state/portForwards.ts b/apps/web/src/state/portForwards.ts new file mode 100644 index 0000000000000..3a0c767791bfb --- /dev/null +++ b/apps/web/src/state/portForwards.ts @@ -0,0 +1,152 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { DesktopPortForward, EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; +import { Atom } from "effect/reactivity"; +import { msg } from "gt-react"; + +import type { ConnectionTarget } from "@t3tools/client-runtime/connection"; + +import { tunnelsEnvironmentLoopback } from "../browser/browserTargetResolver"; +import { m } from "../i18n/messages"; +import { environmentAtomList } from "./environmentAtomList"; +import { environmentSession } from "./session"; + +const EMPTY_FORWARDS: ReadonlyArray = []; + +const previewBridge = () => + typeof window === "undefined" ? undefined : window.desktopBridge?.preview; + +/** Ports of other environments the desktop app forwards to this machine; empty elsewhere. */ +const portForwardsAtom = Atom.make( + Stream.callback>((queue) => + Effect.gen(function* () { + const bridge = previewBridge(); + if (!bridge) return yield* Effect.never; + let changed = false; + yield* Effect.acquireRelease( + Effect.sync(() => + bridge.onPortForwards((forwards) => { + changed = true; + Queue.offerUnsafe(queue, forwards); + }), + ), + (unsubscribe) => Effect.sync(unsubscribe), + ); + const initial = yield* Effect.promise(() => bridge.listPortForwards()); + if (!changed) Queue.offerUnsafe(queue, initial); + return yield* Effect.never; + }), + ), + { initialValue: EMPTY_FORWARDS }, +).pipe(Atom.keepAlive, Atom.withLabel("desktop:port-forwards")); + +export function usePortForwards(): ReadonlyArray { + return AsyncResult.getOrElse(useAtomValue(portForwardsAtom), () => EMPTY_FORWARDS); +} + +/** Only the desktop app forwards, and only from environments it reaches through the tunnel. */ +export const canForwardPorts = (target: ConnectionTarget | undefined): boolean => + previewBridge() !== undefined && tunnelsEnvironmentLoopback(target); + +/** + * Whether the environment runs on another machine. A saved route can still lead back to this + * computer (its own Tailscale address, a relay), where a forward would only loop. + */ +export type ForwardLocality = "remote" | "local" | "pending" | "unknown"; + +class PortForwardLocalityError extends Schema.TaggedError()( + "PortForwardLocalityError", + { environmentId: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return m(msg("Could not tell whether this environment runs on this computer.")); + } +} + +const localityResultAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + // Each established connection probes anew, so a failed probe never outlives a reconnect. + const connection = AsyncResult.getOrElse( + get(environmentSession.transportSessionAtom(environmentId)), + () => Option.none(), + ); + const bridge = previewBridge(); + if (Option.isNone(connection) || bridge === undefined) return Effect.never; + return Effect.tryPromise({ + try: () => bridge.sharesLoopback(environmentId), + catch: (cause) => new PortForwardLocalityError({ environmentId, cause }), + }).pipe(Effect.map((shares): ForwardLocality => (shares ? "local" : "remote"))); + }).pipe( + Atom.setIdleTTL(10 * 60_000), + Atom.withLabel(`desktop:port-forward-locality-probe:${environmentId}`), + ), +); + +const localityAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get): ForwardLocality => { + const result = get(localityResultAtom(environmentId)); + if (AsyncResult.isSuccess(result)) return result.value; + return AsyncResult.isFailure(result) ? "unknown" : "pending"; + }).pipe(Atom.withLabel(`desktop:port-forward-locality:${environmentId}`)), +); + +const NO_LOCALITY = Atom.make("unknown").pipe( + Atom.withLabel("desktop:port-forward-locality:none"), +); + +/** Pass `null` for an environment the desktop doesn't tunnel to; that one never probes. */ +export function useForwardLocality(environmentId: EnvironmentId | null): ForwardLocality { + return useAtomValue(environmentId === null ? NO_LOCALITY : localityAtom(environmentId)); +} + +export const forwardLocalitiesAtom = environmentAtomList( + "desktop:port-forward-localities", + localityAtom, +); + +export const findPortForward = ( + forwards: ReadonlyArray, + environmentId: EnvironmentId, + remotePort: number, +) => + forwards.find( + (forward) => forward.environmentId === environmentId && forward.remotePort === remotePort, + ); + +export function forwardPort(environmentId: EnvironmentId, remotePort: number) { + const bridge = previewBridge(); + if (!bridge) return Promise.reject(new Error(m(msg("Port forwarding needs the desktop app.")))); + return bridge.forwardPort(environmentId, remotePort).catch((error: unknown) => { + // Electron flattens main-process errors into "Error invoking remote method '…': Tag: text". + const raw = error instanceof Error ? error.message : String(error); + throw new Error( + raw.includes("LoopbackTunnelSameMachineError") + ? m( + msg("This environment runs on this computer, so localhost:{port} already reaches it.", { + port: remotePort, + }), + ) + : raw.includes("LoopbackTunnelUnavailableError") + ? m(msg("This environment can't be reached right now. Try again once it reconnects.")) + : raw.replace(/^Error invoking remote method '[^']*':\s*(\w+Error:\s*)?/u, ""), + { cause: error }, + ); + }); +} + +export function stopPortForward(environmentId: EnvironmentId, remotePort: number) { + return previewBridge()?.stopPortForward(environmentId, remotePort) ?? Promise.resolve(); +} + +/** `url` with its host and port moved to the forward's end on this machine. */ +export function forwardedUrl(forward: DesktopPortForward, url?: string): string { + const local = new URL(url ?? "http://localhost/"); + local.hostname = "localhost"; + local.port = String(forward.localPort); + return local.toString(); +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 8a8e87fe0ba57..17c6e36df1576 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -303,6 +303,23 @@ do. These tabs ignore your system proxy settings, so they can't reach a host you connect to only through a proxy or over HTTPS with a privately issued certificate. The web app keeps streaming. +The desktop app can also forward a port on the host to your computer, so any +app there, such as your own browser, `curl`, or a database client, reaches it +at `localhost`. Use the forward button on a server in the thread's **Servers** +list, or **Forwarded ports** in the command palette, where you can also type +any port number and stop forwards. A forward keeps the host's port number +unless that port is taken on your computer, in which case it uses a free one +and shows it. Forwards end when you stop them or quit the app. ⌘-click +(Ctrl-click on Windows and Linux) on a remote server forwards it and opens it +in your browser. + +A forwarded port behaves like a server running on your computer: anything on +your computer can reach it, including web pages open in your browser, so a +forwarded service is exposed the same way a local dev server is. Forwards +listen only on your computer's loopback, never on your network. On Linux they +accept only apps running as your user; on macOS and Windows, other users signed +in to the same computer can reach them too. + On iPhone, iPad, and Android, a tab showing one of the host's `localhost` pages has **Open on this device** in its menu. So does a long press on a `localhost` link in a chat. It opens the page in the phone's own browser view, at the same diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.ts index 6fdec4bd91580..e6066910d36f4 100644 --- a/packages/client-runtime/src/state/session.ts +++ b/packages/client-runtime/src/state/session.ts @@ -271,6 +271,7 @@ function makeEnvironmentSessionAtoms( preparedConnectionValueAtom, sessionStateAtom, sessionStateValueAtom, + transportSessionAtom, }; } diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index a9dbc8b81de98..77a523c03608f 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -2,7 +2,7 @@ import * as Schema from "effect/Schema"; import type { PreviewCaptureFailureEncoded } from "./previewCapture.ts"; import { SnapShotSource } from "./chatAttachment.ts"; -import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { EnvironmentId, PortSchema, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { BrowserProfileId } from "./browserProfile.ts"; import type { BrowserImportResult, @@ -1002,6 +1002,22 @@ export const DesktopPreviewTunnelAccessResolutionInputSchema = Schema.Struct({ url: Schema.NullOr(Schema.String), }); +/** A loopback port of another environment, reachable on this machine's 127.0.0.1. */ +export const DesktopPortForwardSchema = Schema.Struct({ + environmentId: EnvironmentId, + remotePort: PortSchema, + /** The same as `remotePort` unless that port was taken here. */ + localPort: PortSchema, +}); +export type DesktopPortForward = typeof DesktopPortForwardSchema.Type; + +export const DesktopSharesLoopbackInputSchema = Schema.Struct({ environmentId: EnvironmentId }); + +export const DesktopPortForwardInputSchema = Schema.Struct({ + environmentId: EnvironmentId, + remotePort: PortSchema, +}); + export const DesktopPreviewClearDataInputSchema = Schema.Struct({ environmentId: EnvironmentId, /** Omit to clear every profile; otherwise only this profile's partition. */ @@ -1324,6 +1340,13 @@ export interface DesktopPreviewBridge { listener: (request: DesktopPreviewTunnelAccessRequest) => void, ) => () => void; resolveTunnelAccess: (requestId: string, url: string | null) => Promise; + /** Forwards an environment's loopback port to this machine until stopped or the app quits. */ + forwardPort: (environmentId: EnvironmentId, remotePort: number) => Promise; + stopPortForward: (environmentId: EnvironmentId, remotePort: number) => Promise; + listPortForwards: () => Promise>; + /** Whether the environment runs on this machine, where its ports need no forward. */ + sharesLoopback: (environmentId: EnvironmentId) => Promise; + onPortForwards: (listener: (forwards: ReadonlyArray) => void) => () => void; listBrowserImportSources: () => Promise>; importBrowserCookies: (input: { readonly environmentId: EnvironmentId; From fda679a036720f915395f0f69b1edd5b35e4d415 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 23:21:29 +0000 Subject: [PATCH 5/5] test(client-runtime): trim overlapping reconnect loop cases Co-Authored-By: Claude Opus 5.5 --- .../src/connection/supervisor.test.ts | 72 ++----------------- 1 file changed, 7 insertions(+), 65 deletions(-) diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index b2d67a38865c6..81c8bf4064a45 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -697,20 +697,6 @@ describe("EnvironmentSupervisor", () => { releaseDefect: false, log: "Connection attempt failed with an unexpected interruption.", }, - { - label: "fails and dies while interrupted", - closed: Exit.failCause( - Cause.combine( - Cause.combine( - Cause.fail(transient("Session closed.")), - Cause.die(new Error("Session closed defect.")), - ), - Cause.interrupt(), - ), - ), - releaseDefect: false, - log: "Connection attempt failed with an unexpected defect.", - }, { label: "fails while interrupted", closed: Exit.failCause( @@ -759,35 +745,13 @@ describe("EnvironmentSupervisor", () => { }).pipe(Effect.provide(TestClock.layer())), ); - it.effect.each([ - { - label: "its attempt defects after its session went live", - closed: Exit.interrupt(), - releaseDefect: false, - lost: { phase: "backoff", generation: 1, lastFailure: null }, - // The earlier failed attempt still counts, so this is the ladder's second step. - soonestMs: 2000, - latestMs: 4000, - }, - { - label: "logging its release defect dies", - closed: Exit.fail(transient("Session closed.")), - releaseDefect: true, - lost: { phase: "backoff", generation: 1 }, - soonestMs: 300_000, - latestMs: 300_000, - }, - ])( - "does not reuse a live session's generation when $label", - ({ closed, releaseDefect, lost, soonestMs, latestMs }) => + it.effect( + "does not reuse a live session's generation when its attempt defects after going live", + () => Effect.gen(function* () { const harness = yield* makeHarness({ prepare: (attempt) => attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), - release: (session) => - releaseDefect && session === 1 - ? Effect.die(new Error("Session release defect.")) - : Effect.void, }); let logCalls = 0; const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { @@ -798,7 +762,7 @@ describe("EnvironmentSupervisor", () => { harness.dependencies, Logger.layer( [ - // The first log line throws, which is how each row injects its defect. + // Logging the lost session's interruption throws, so the attempt itself defects. Logger.make(() => { logCalls += 1; if (logCalls === 1) throw new Error("Logger defect."); @@ -816,15 +780,11 @@ describe("EnvironmentSupervisor", () => { supervisor.state, (state) => state.phase === "connected" && state.generation === 1, ); - yield* harness.closeLatestSession(closed); + yield* harness.closeLatestSession(Exit.interrupt()); const backoff = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); - expect(logCalls).toBe(2); - expect(backoff).toMatchObject(lost); - const retryInMs = (backoff.retryAt ?? 0) - (yield* Clock.currentTimeMillis); - expect(retryInMs).toBeGreaterThanOrEqual(soonestMs); - expect(retryInMs).toBeLessThanOrEqual(latestMs); + expect(backoff).toMatchObject({ generation: 1, lastFailure: null }); - yield* TestClock.adjust(`${latestMs} millis`); + yield* TestClock.adjust("4 seconds"); const replaced = yield* awaitState( supervisor.state, (state) => state.phase === "connected", @@ -833,24 +793,6 @@ describe("EnvironmentSupervisor", () => { }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("keeps a released session's outcome", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ - release: () => Effect.die(new Error("Session release defect.")), - }); - const logs: unknown[] = []; - const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { - initiallyDesired: true, - }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs)))); - - yield* awaitState(supervisor.state, (state) => state.phase === "connected"); - yield* supervisor.disconnect; - const released = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); - expect(released.phase).toBe("available"); - expect(logs).toEqual([["Connection release failed with an unexpected defect."]]); - }).pipe(Effect.provide(TestClock.layer())), - ); - it.effect("restarts the loop after a defect outside an attempt", () => Effect.gen(function* () { const harness = yield* makeHarness();