Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 40 additions & 3 deletions apps/web/src/components/ServerUpdateAction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { useServerConfigs } from "~/state/entities";
import { useManagedPolicy } from "~/state/managedPolicy";
import { environmentPresentations } from "~/state/presentation";
import { ManagedControl } from "./ManagedPolicy";
import { manualServerUpdateCommand } from "~/versionSkew";
import { isAppStartedSshServer, manualServerUpdateCommand, sshRestartVersion } from "~/versionSkew";
import { crossesReleaseTrack } from "@t3tools/shared/cliRelease";
import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
Expand Down Expand Up @@ -96,6 +96,8 @@ export interface ServerUpdateTarget {
readonly targetDatabaseMigration?: number;
/** The host already runs its track's newest build and only saves the track. */
readonly trackOnly?: boolean;
/** This desktop app started the server over SSH and updates it by restarting it. */
readonly restartSshServer?: boolean;
}

type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
Expand Down Expand Up @@ -134,6 +136,7 @@ export function useServerUpdate() {
pendingUpdateEnvironmentIds.add(environmentId);
const result = await updateServer({
environmentId,
...(target.restartSshServer === true ? { restartSshServer: true } : {}),
input: {
targetVersion,
...(target.channel === undefined ? {} : { channel: target.channel }),
Expand Down Expand Up @@ -184,7 +187,7 @@ export function ServerUpdatesAction({
const [isPending, setIsPending] = useState(false);
const eligible = targets.filter(
(target) =>
target.selfUpdate !== null &&
(target.selfUpdate !== null || target.restartSshServer === true) &&
(target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) &&
managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy) === undefined &&
!refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion),
Expand All @@ -206,6 +209,14 @@ export function ServerUpdatesAction({
)) ?? true;
if (!confirmed) return;
}
const sshTargets = available.filter((target) => target.restartSshServer === true);
if (sshTargets.length > 0) {
const confirmed =
(await requestConfirmDialog(sshRestartConfirmation(sshTargets), {
initialFocus: "confirm",
})) ?? true;
if (!confirmed) return;
}
await Promise.all(available.map((target) => update(target)));
});
pending.current = false;
Expand All @@ -224,6 +235,10 @@ export function ServerUpdatesAction({
);
}

function sshRestartConfirmation(targets: ReadonlyArray<Pick<ServerUpdateTarget, "serverLabel">>) {
return `Restart T3 Code on ${targets.map((target) => target.serverLabel).join(", ")} to update? Agent turns running there will stop.`;
}

export function canUpdateServer(
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
): boolean {
Expand Down Expand Up @@ -271,6 +286,9 @@ export function ServerUpdateAction({
appearance = "button",
}: ServerUpdateTarget & UpdateButtonProps) {
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId));
const restartSshServer =
presentation !== null && sshRestartVersion(presentation) === targetVersion;
const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion;
const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer);
Expand Down Expand Up @@ -305,6 +323,13 @@ export function ServerUpdateAction({
) {
return;
}
if (restartSshServer) {
const confirmed =
(await requestConfirmDialog(sshRestartConfirmation([{ serverLabel }]), {
initialFocus: "confirm",
})) ?? true;
if (!confirmed) return;
}
if (isDesktopAppUpdate) {
const confirmed =
(await requestConfirmDialog(
Expand All @@ -322,6 +347,7 @@ export function ServerUpdateAction({
selfUpdate,
desktopAppUpdate,
targetVersion,
restartSshServer,
});
};

Expand Down Expand Up @@ -350,7 +376,9 @@ export function ServerUpdateAction({
}

const manualCommand =
selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
selfUpdate === null && !restartSshServer
? manualServerUpdateCommand(targetVersion, installation)
: null;
const actionLabel =
manualCommand !== null
? installation?.kind === "npm-global"
Expand Down Expand Up @@ -412,8 +440,17 @@ export function OutdatedServerUpdateAction({
readonly label?: string;
}) {
const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId));
const restartsSshServer = presentation !== null && isAppStartedSshServer(presentation.entry);
const handleUpdate = async () => {
if (pendingUpdateEnvironmentIds.has(environmentId)) return;
if (restartsSshServer) {
const confirmed =
(await requestConfirmDialog(sshRestartConfirmation([{ serverLabel }]), {
initialFocus: "confirm",
})) ?? true;
if (!confirmed || pendingUpdateEnvironmentIds.has(environmentId)) return;
}
pendingUpdateEnvironmentIds.add(environmentId);
const result = await update({
environmentId,
Expand Down
10 changes: 8 additions & 2 deletions apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
isVersionMismatchDismissed,
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
sshRestartVersion,
supportsDesktopAppUpdate,
} from "~/versionSkew";
import {
Expand Down Expand Up @@ -55,16 +56,21 @@ export function useAutoBalanceUpdateBanner(
return [];
const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig);
const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig);
const targetVersion = state.status === "idle" ? mismatch!.clientVersion : state.targetVersion;
const restartSshServer = sshRestartVersion(environment) === targetVersion;
return [
{
environmentId: environment.environmentId,
serverLabel: environment.label,
selfUpdate,
installation: environment.serverConfig?.environment.capabilities.serverInstallation,
desktopAppUpdate,
targetVersion: state.status === "idle" ? mismatch!.clientVersion : state.targetVersion,
targetVersion,
restartSshServer,
connected: environment.connection.phase === "connected",
remoteUpdate: selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate),
remoteUpdate:
restartSshServer ||
(selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate)),
state,
dismissKey,
},
Expand Down
6 changes: 5 additions & 1 deletion apps/web/src/components/settings/ConnectionsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import { useUiStateStore } from "~/uiStateStore";
import {
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
sshRestartVersion,
supportsDesktopAppUpdate,
} from "~/versionSkew";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
Expand Down Expand Up @@ -281,13 +282,15 @@ function ConnectionsSettingsContent({
const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig);
const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig);
const restartSshServer =
mismatch !== null && sshRestartVersion(environment) === mismatch.clientVersion;
if (
!mismatch ||
updateStatus === "running" ||
!environment.entry.enabled ||
environment.connection.phase !== "connected" ||
isDesktopLocalConnectionTarget(environment.entry.target) ||
selfUpdate === null ||
(selfUpdate === null && !restartSshServer) ||
(selfUpdate === "desktop-managed" && !desktopAppUpdate)
) {
return [];
Expand All @@ -300,6 +303,7 @@ function ConnectionsSettingsContent({
installation: environment.serverConfig?.environment.capabilities.serverInstallation,
desktopAppUpdate,
targetVersion: mismatch.clientVersion,
restartSshServer,
},
];
},
Expand Down
13 changes: 10 additions & 3 deletions apps/web/src/components/sidebar/updateEverything.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,19 @@ describe("collectServerUpdateTargets", () => {
machine("current", "0.0.50", "boot-service"),
machine("current-offline", "0.0.50", "boot-service", { connected: false }),
machine("manual", "0.0.40", undefined),
machine("ssh", "0.0.40", undefined, { sshRestartVersion: "0.0.50" }),
// This app has not restarted on 0.0.50 yet, so a restart would start 0.0.49.
machine("ssh-before-app", "0.0.40", undefined, { sshRestartVersion: "0.0.49" }),
],
"0.0.50",
);

expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([
["service", "0.0.50"],
["other-desktop", "0.0.50"],
expect(
targets.map((target) => [target.serverLabel, target.targetVersion, target.restartSshServer]),
).toEqual([
["service", "0.0.50", undefined],
["other-desktop", "0.0.50", undefined],
["ssh", "0.0.50", true],
]);
expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
["nightly-service", "on the nightly channel"],
Expand All @@ -82,6 +88,7 @@ describe("collectServerUpdateTargets", () => {
["no-scope", "no permission"],
["busy", "already updating"],
["manual", "needs a manual update"],
["ssh-before-app", "updates after this app restarts"],
]);
});

Expand Down
18 changes: 18 additions & 0 deletions apps/web/src/components/sidebar/updateEverything.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export interface UpdateEverythingMachine {
} | null;
readonly connected: boolean;
readonly hostedByThisApp: boolean;
/** Set when this app started the server over SSH: the version restarting it starts. */
readonly sshRestartVersion?: string | null;
readonly canMaintain: boolean;
readonly updateState: ServerUpdateState;
}
Expand Down Expand Up @@ -104,6 +106,22 @@ export function collectServerUpdateTargets(
continue;
}
const desktopAppUpdate = supportsDesktopAppUpdate(config);
if (selfUpdate === null && machine.sshRestartVersion != null) {
// The restart starts this app's own version, so a pending app update comes first.
if (machine.sshRestartVersion !== targetVersion) {
skip("updates after this app restarts");
continue;
}
targets.push({
environmentId: machine.environmentId,
serverLabel: machine.label,
selfUpdate,
desktopAppUpdate,
targetVersion,
restartSshServer: true,
});
continue;
}
if (selfUpdate === null) {
skip("needs a manual update");
continue;
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/sidebar/useUpdateEverything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useEnvironments } from "~/state/environments";
import { environmentIdsKey } from "~/state/environmentAtomList";
import { environmentUpdateStatesAtom } from "~/state/server";
import { environmentSessionStatesAtom } from "~/state/session";
import { sshRestartVersion } from "~/versionSkew";
import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
import { useProviderUpdates } from "../ProviderUpdatesAction";
import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
Expand Down Expand Up @@ -63,6 +64,7 @@ export function useUpdateEverything(
serverConfig: environment.serverConfig,
connected: environment.connection.phase === "connected",
hostedByThisApp: isHostedByThisApp(environment),
sshRestartVersion: sshRestartVersion(environment),
canMaintain: canUpdateServer(sessionStates[index]!),
updateState: updateStates[index]!,
}));
Expand Down
7 changes: 6 additions & 1 deletion apps/web/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,12 @@ export const provisionDesktopSshEnvironment = Effect.fn(
}
return new ConnectionBlockedError({
reason: "configuration",
detail: `${descriptor.label} runs T3 Code ${descriptor.serverVersion}, but this desktop is ${APP_VERSION}, and that server could not accept its pairing. Restart the T3 server on ${descriptor.label} so it runs ${APP_VERSION}, then retry.`,
detail: `${descriptor.label} runs T3 Code ${descriptor.serverVersion}, but this desktop is ${APP_VERSION}, and that server could not accept its pairing. ${
bootstrap.remoteServerKind === "managed"
? // Without a session the Update button is unavailable; switching off stops the server.
`Switch ${descriptor.label} off and on in Settings → Connections to restart it on ${APP_VERSION}.`
: `Restart the T3 server on ${descriptor.label} so it runs ${APP_VERSION}, then retry.`
}`,
});
},
});
Expand Down
22 changes: 22 additions & 0 deletions apps/web/src/versionSkew.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import type {
ServerInstallation,
ServerSelfUpdateCapability,
} from "@t3tools/contracts";
import type { EnvironmentPresentation } from "@t3tools/client-runtime/connection";
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";

import { APP_VERSION } from "./branding";
import { isElectron } from "./env";
import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";

export interface VersionMismatch {
Expand Down Expand Up @@ -89,6 +92,25 @@ export function resolveServerSelfUpdateCapability(
return serverConfig?.environment.capabilities.serverSelfUpdate ?? null;
}

/** Whether this desktop app started the environment's server over SSH and can restart it. */
export function isAppStartedSshServer(entry: Pick<EnvironmentPresentation["entry"], "profile">) {
const profile = Option.getOrNull(entry.profile);
return (
isElectron && profile?._tag === "SshConnectionProfile" && profile.remoteServerKind === "managed"
);
}

/** The version a restart starts on a server this desktop app started over SSH, which reports no
* self-update of its own. Other servers keep their own update guidance. */
export function sshRestartVersion(
environment: Pick<EnvironmentPresentation, "entry" | "serverConfig">,
): string | null {
return resolveServerSelfUpdateCapability(environment.serverConfig) === null &&
isAppStartedSshServer(environment.entry)
? APP_VERSION
: null;
}

export function supportsDesktopAppUpdate(
serverConfig: Pick<ServerConfig, "environment"> | null | undefined,
): boolean {
Expand Down
11 changes: 7 additions & 4 deletions docs/internals/remote.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,13 @@ every route. See [environment authentication](./environment-auth.md) and the
SSH can launch a server as well as forward a port. Desktop main owns that
lifecycle because it can spawn SSH and handle authentication prompts. The
renderer uses the forwarded endpoint through the shared connection runtime.
[SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only if the
launcher owns it; a server it discovered already running must survive a client
disconnect. Reconnection restores the forward before opening the application
transport.
[SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only on an
explicit disconnect (removing or switching off the environment, or updating it)
and only if the launcher owns it; a server it discovered already running must
survive a client disconnect. Quitting the app or reconnecting with a newer
runner never stops a server, since agent turns may be running there; an update
stops it and the next connect starts the client's version. Reconnection restores
the forward before opening the application transport.

Remote servers can outlive several client releases. Clients must use advertised
capabilities and handle their absence, rather than assume their own version
Expand Down
9 changes: 6 additions & 3 deletions docs/user/remote-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,12 @@ check with:
ssh user@example.com 'sh -lc "command -v claude codex"'
```

If SSH reconnecting fails after an app update, retry the launch once. Removing
the connection stops a server that T3 Code launched; a server that was already
running is left alone.
A server T3 Code launched keeps running when you quit the app, so agent work
continues, and reconnecting picks it up again. After an app update it stays on
its old version until you choose **Update**, which restarts it on the app's
version and stops any agent turns running there. Removing the connection or
switching the environment off stops a server that T3 Code launched; a server
that was already running is left alone.

Each desktop app keeps one session on the host for its SSH connection and reuses
it when it reconnects. Revoke sessions you no longer use in **Settings →
Expand Down
2 changes: 2 additions & 0 deletions packages/client-runtime/src/connection/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export class SshConnectionProfile extends Schema.TaggedClass<SshConnectionProfil
{
...ConnectionProfileBase,
target: DesktopSshEnvironmentTargetSchema,
/** "managed" when this desktop app started the server, as of its last connect. */
remoteServerKind: Schema.optionalKey(Schema.Literals(["external", "managed"])),
},
) {}

Expand Down
3 changes: 3 additions & 0 deletions packages/client-runtime/src/connection/onboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ export const prepareSshRegistration = Effect.fn(
environmentId: provisioned.environmentId,
label,
target: provisioned.bootstrap.target,
...(provisioned.bootstrap.remoteServerKind === undefined
? {}
: { remoteServerKind: provisioned.bootstrap.remoteServerKind }),
}),
credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),
});
Expand Down
Loading
Loading