Skip to content

Commit 99e3b72

Browse files
fix(connect): diagnose incomplete headless server setup (pingdotgg#9602)
1 parent c3b8825 commit 99e3b72

11 files changed

Lines changed: 614 additions & 42 deletions

File tree

‎apps/server/src/cli/connect.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
3535
import * as BootService from "../cloud/bootService.ts";
3636
import * as CliState from "../cloud/CliState.ts";
3737
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
38+
import { filterRelayResponse } from "../cloud/relayResponse.ts";
3839
import {
3940
CLOUD_LINKED_USER_ID,
4041
isAgentActivityPublishingEnabledValue,
@@ -208,6 +209,8 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
208209
` Relay: ${status.relayUrl ?? "not provisioned"}`,
209210
` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
210211
...formatRelayClientStatus(status.relayClient),
212+
"",
213+
"This is saved setup, not a live connection check. Check the background service with `t3 service status`.",
211214
...(nextStep ? ["", `Next: ${nextStep}`] : []),
212215
].join("\n");
213216
}
@@ -346,7 +349,7 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
346349
).pipe(
347350
HttpClientRequest.bearerToken(token.value.accessToken),
348351
httpClient.execute,
349-
Effect.flatMap(HttpClientResponse.filterStatusOk),
352+
Effect.flatMap(filterRelayResponse),
350353
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
351354
withRelayClientTracing,
352355
);
@@ -689,17 +692,17 @@ export const connectCommand = Command.make("connect", {
689692
// Show which account was linked so an unexpected identity (an
690693
// authorization code for a different account) is visible before the
691694
// machine is brought online.
692-
yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`);
695+
yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
693696

694-
// Connect itself already succeeded; a boot-service failure must not
695-
// fail the command, just tell the user what happened and move on.
697+
// Authorization is stored. If service setup fails, preserve it and
698+
// show how to run the server manually.
696699
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
697700
if (background) {
698701
const platform = yield* HostProcessPlatform;
699702
yield* Console.log(
700703
platform === "darwin"
701-
? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
702-
: "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
704+
? "\n✓ Background service ready\n\nT3 Code is set to run while you are logged in to this Mac. The server establishes the T3 Connect link on startup."
705+
: "\n✓ Background service ready\n\nT3 Code is set to keep running after you log out. The server establishes the T3 Connect link on startup.",
703706
);
704707
return;
705708
}

‎apps/server/src/cli/service.test.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,38 @@ it("reports the installed service version and host paths", () => {
4545
it("gives a direct repair command for a stale service", () => {
4646
assert.include(
4747
formatServiceStatus({ ...status, current: false }, "0.0.29"),
48-
"Next: Run `npx t3@latest service update`.",
48+
"Next: Run `npx t3@0.0.29 service update`.",
4949
);
5050
});
5151

52+
it("explains an incomplete nightly installation and keeps repair on its installed version", () => {
53+
const output = formatServiceStatus(
54+
{
55+
...status,
56+
current: false,
57+
installedVersion: "0.0.32-nightly.1",
58+
problems: ["linger-disabled", "service-stopped"],
59+
},
60+
"0.0.32-nightly.1",
61+
);
62+
63+
expect(output).toContain("[linger-disabled]");
64+
expect(output).toContain("last login session ends");
65+
expect(output).toContain('sudo loginctl enable-linger "$(id -un)"');
66+
expect(output).toContain("[service-stopped]");
67+
expect(output).toContain("npx [email protected] service update");
68+
expect(output).not.toContain("t3@latest");
69+
});
70+
71+
it("suggests the newer CLI version when the installed service needs an update", () => {
72+
const output = formatServiceStatus(
73+
{ ...status, current: false, installedVersion: "0.0.28" },
74+
"0.0.29",
75+
);
76+
expect(output).toContain("npx [email protected] service update");
77+
expect(output).not.toContain("npx [email protected] service update");
78+
});
79+
5280
it("explains where the service is supported", () => {
5381
assert.include(
5482
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
@@ -151,6 +179,15 @@ it.effect.each([
151179
name: "the same version",
152180
state: { ...status, current: false, installedVersion: packageJson.version },
153181
},
182+
{
183+
name: "an incomplete install of the same version",
184+
state: {
185+
...status,
186+
current: false,
187+
installedVersion: packageJson.version,
188+
problems: ["linger-disabled"] as const,
189+
},
190+
},
154191
{ name: "an unknown version", state: { ...status, current: false } },
155192
])("installs or repairs $name without an override", ({ state }) =>
156193
Effect.gen(function* () {
@@ -201,3 +238,12 @@ it.effect("keeps onboarding successful when a newer version appears before insta
201238
expect(ready).toBe(false);
202239
}),
203240
);
241+
242+
it.effect("keeps the manual-server fallback when background prerequisites fail", () =>
243+
Effect.gen(function* () {
244+
const ready = yield* recoverServiceOnboardingOffer(
245+
Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),
246+
);
247+
expect(ready).toBe(false);
248+
}),
249+
);

‎apps/server/src/cli/service.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ export function formatServiceStatus(
6868
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
6969
}
7070
const installedVersion = status.installedVersion ?? cliVersion;
71+
const problems = (status.problems ?? []).map(
72+
(problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
73+
);
7174
if (
7275
!status.current &&
7376
status.installedVersion !== undefined &&
@@ -78,6 +81,7 @@ export function formatServiceStatus(
7881
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
7982
` Unit: ${status.unitPath}`,
8083
` Logs: ${status.logPath}`,
84+
...problems,
8185
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
8286
].join("\n");
8387
}
@@ -86,7 +90,8 @@ export function formatServiceStatus(
8690
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
8791
` Unit: ${status.unitPath}`,
8892
` Logs: ${status.logPath}`,
89-
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
93+
...problems,
94+
...(status.current ? [] : [` Next: Run \`npx t3@${cliVersion} service update\`.`]),
9095
].join("\n");
9196
}
9297

@@ -189,6 +194,9 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
189194
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
190195
return true;
191196
}
197+
for (const problem of status.problems ?? []) {
198+
yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
199+
}
192200
if (
193201
installed &&
194202
status.installedVersion !== undefined &&
@@ -239,6 +247,8 @@ export const recoverServiceOnboardingOffer = <R>(
239247
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
240248
BootServiceInstallError: (error) =>
241249
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
250+
BootServicePrerequisiteError: (error) =>
251+
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
242252
BootServiceUpdatePendingError: (error) =>
243253
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
244254
BootServiceDowngradeRefusedError: (error) =>

‎apps/server/src/cloud/bootService.test.ts‎

Lines changed: 136 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,17 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
127127

128128
const commands: string[] = [];
129129
const timeouts = new Map<string, unknown>();
130-
const control: { failCommand: string | undefined; stateAfterStop?: string } = {
130+
const control: {
131+
failCommand: string | undefined;
132+
stateAfterStop?: string;
133+
linger: string;
134+
enabled: boolean;
135+
active: boolean;
136+
} = {
131137
failCommand: undefined,
138+
linger: "yes",
139+
enabled: true,
140+
active: true,
132141
};
133142
const runner = ProcessRunner.ProcessRunner.of({
134143
run: Effect.fn("test.run_boot_service_command")(function* (
@@ -137,6 +146,11 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
137146
const command = `${input.command} ${input.args.join(" ")}`;
138147
commands.push(command);
139148
timeouts.set(command, input.timeout);
149+
const failed = command === control.failCommand;
150+
if (!failed && command === "loginctl enable-linger --no-ask-password 501")
151+
control.linger = "yes";
152+
if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
153+
if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
140154
if (
141155
control.stateAfterStop !== undefined &&
142156
(command === "systemctl --user stop t3code.service" ||
@@ -145,9 +159,20 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
145159
yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
146160
}
147161
return {
148-
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
162+
stdout:
163+
input.args[1] === "--version"
164+
? "t3 v1.2.3\n"
165+
: input.command === "loginctl" && input.args[0] === "show-user"
166+
? `${control.linger}\n`
167+
: input.args[1] === "is-enabled"
168+
? control.enabled
169+
? "enabled\n"
170+
: "disabled\n"
171+
: "",
149172
stderr: "",
150-
code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
173+
code: ChildProcessSpawner.ExitCode(
174+
failed || (input.args[1] === "is-active" && !control.active) ? 1 : 0,
175+
),
151176
timedOut: false,
152177
stdoutTruncated: false,
153178
stderrTruncated: false,
@@ -182,10 +207,103 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
182207
),
183208
);
184209
const service = yield* makeService();
185-
return { service, makeService, fs, statePath, commands, timeouts, control };
210+
return { service, makeService, fs, statePath, commands, timeouts, control, runtime };
186211
});
187212

188213
it.layer(NodeServices.layer)("boot service install", (it) => {
214+
it.effect(
215+
"fails before installing files or validating a runtime when lingering needs an administrator",
216+
() =>
217+
Effect.gen(function* () {
218+
const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
219+
const before = yield* service.status;
220+
control.linger = "no";
221+
control.failCommand = "loginctl enable-linger --no-ask-password 501";
222+
yield* fs.remove(runtime.sentinelPath);
223+
224+
const error = yield* service.install().pipe(Effect.flip);
225+
226+
expect(error).toMatchObject({
227+
_tag: "BootServicePrerequisiteError",
228+
problem: "linger-disabled",
229+
});
230+
expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
231+
expect(error.message).toContain("last login session ends");
232+
expect(yield* fs.exists(before.unitPath)).toBe(false);
233+
expect(yield* fs.exists(statePath)).toBe(false);
234+
expect(
235+
commands.some((command) => command.startsWith("npm ") || command.includes("--version")),
236+
).toBe(false);
237+
expect(
238+
commands.some(
239+
(command) => command.includes("daemon-reload") || command.includes("restart"),
240+
),
241+
).toBe(false);
242+
expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
243+
}),
244+
);
245+
246+
it.effect(
247+
"detects a partial install and preserves the running service when repair lacks permission",
248+
() =>
249+
Effect.gen(function* () {
250+
const { service, fs, statePath, commands, control } = yield* makeHarness();
251+
const plan = yield* service.install();
252+
const before = yield* fs.readFileString(statePath);
253+
const unit = yield* fs.readFileString(plan.unitPath);
254+
control.linger = "no";
255+
control.failCommand = "loginctl enable-linger --no-ask-password 501";
256+
257+
expect(yield* service.status).toMatchObject({
258+
current: false,
259+
problems: ["linger-disabled"],
260+
});
261+
commands.length = 0;
262+
expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
263+
"BootServicePrerequisiteError",
264+
);
265+
expect(yield* fs.readFileString(statePath)).toBe(before);
266+
expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
267+
expect(commands).not.toContain("systemctl --user stop t3code.service");
268+
}),
269+
);
270+
271+
it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
272+
Effect.gen(function* () {
273+
const { service, commands, control } = yield* makeHarness();
274+
control.linger = "no";
275+
yield* service.install();
276+
expect(control.linger).toBe("yes");
277+
expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
278+
commands.indexOf("systemctl --user daemon-reload"),
279+
);
280+
281+
control.enabled = false;
282+
control.active = false;
283+
expect(yield* service.status).toMatchObject({
284+
current: false,
285+
problems: ["service-disabled", "service-stopped"],
286+
});
287+
yield* service.install();
288+
expect((yield* service.status).current).toBe(true);
289+
}),
290+
);
291+
292+
it.effect.each([
293+
{ command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
294+
{ command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
295+
])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
296+
Effect.gen(function* () {
297+
const { service, fs, statePath, control } = yield* makeHarness();
298+
control.failCommand = command;
299+
expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
300+
_tag: "BootServicePrerequisiteError",
301+
problem,
302+
});
303+
expect(yield* fs.exists(statePath)).toBe(false);
304+
}),
305+
);
306+
189307
it.effect("installs, reports current state, and uninstalls", () =>
190308
Effect.gen(function* () {
191309
const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
@@ -286,8 +404,10 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
286404
expect(yield* fs.readFileString(plan.launcherPath)).toBe(launcher);
287405
expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
288406
expect(
289-
commands.filter((command) =>
290-
command.startsWith(platform === "linux" ? "systemctl " : "launchctl "),
407+
commands.filter(
408+
(command) =>
409+
command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
410+
!command.includes("show-environment"),
291411
),
292412
).toEqual(
293413
platform === "linux"
@@ -351,7 +471,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
351471

352472
const error = yield* service.install().pipe(Effect.flip);
353473
expect(error._tag).toBe("BootServiceCommandError");
354-
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
474+
expect(
475+
commands.filter(
476+
(command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
477+
),
478+
).toEqual([
355479
"systemctl --user stop t3code.service",
356480
"systemctl --user daemon-reload",
357481
"systemctl --user restart t3code.service",
@@ -382,7 +506,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
382506
"BootServiceUpdatePendingError",
383507
);
384508
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
385-
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
509+
expect(
510+
commands.filter(
511+
(command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
512+
),
513+
).toEqual([
386514
"systemctl --user stop t3code.service",
387515
"systemctl --user restart t3code.service",
388516
]);

0 commit comments

Comments
 (0)