Skip to content

Commit 3e05aec

Browse files
fix(cli): report the selected preview and its owned log
1 parent 87b05a7 commit 3e05aec

5 files changed

Lines changed: 304 additions & 23 deletions

File tree

‎docs/guides/troubleshooting.mdx‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,16 @@ an existing managed preview to the requested port, add `--force-new` to stop and
9292
replace it. Without `--port`, discovery starts at the saved preview's port.
9393

9494
`preview --status --port 4567` uses the same discovery range and checks an
95-
out-of-range saved port separately. `preview --stop` checks only this project's
96-
saved port when a session exists, even with an explicit `--port`. Without a saved
97-
session, `--stop --port 4567` discovers previews in ports 4567–4666. Shutdown waits
98-
check only the port being stopped.
95+
out-of-range saved port separately. Among previews for this project, status
96+
prefers the exact requested port, then the saved preview's port, then another
97+
match. The saved log path appears only when the selected server is verified as
98+
that background preview. If the listener PID cannot be determined, JSON reports
99+
`pid: null` and text output omits the PID.
100+
101+
`preview --stop` checks only this project's saved port when a session exists,
102+
even with an explicit `--port`. Without a saved session, `--stop --port 4567`
103+
discovers previews in ports 4567–4666. Shutdown waits check only the port being
104+
stopped.
99105

100106
## Media problems
101107

‎packages/cli/src/commands/preview.test.ts‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,108 @@ describe.each(["status", "stop"] as const)("preview --%s port scope", (operation
9191
});
9292
});
9393

94+
describe("preview --status reporting", () => {
95+
it("reports an unknown listener PID without borrowing the saved wrapper's PID", async () => {
96+
const dir = tempProject();
97+
writeFileSync(join(dir, "index.html"), "<html></html>");
98+
vi.spyOn(previewLifecycle, "readBackgroundPreviewStatus").mockResolvedValue({
99+
pid: null,
100+
port: 32600,
101+
projectDir: dir,
102+
});
103+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
104+
await runCommand(previewCommand, { rawArgs: [dir, "--status", "--json"] });
105+
106+
const result = JSON.parse(log.mock.calls.flat().join("\n")).result;
107+
expect(result).toMatchObject({ state: "running", pid: null, mode: "unknown" });
108+
expect(result).not.toHaveProperty("logPath");
109+
});
110+
111+
it("lists an unverified endpoint without inventing its PID or background mode", async () => {
112+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
113+
await handlePreviewList(3002, true, {
114+
scan: async () => [],
115+
listManaged: async () => [{ pid: null, port: 32600, projectDir: "/tmp/preview-unverified" }],
116+
});
117+
118+
const result = JSON.parse(log.mock.calls.flat().join("\n")).result;
119+
expect(result.sessions).toMatchObject([{ port: 32600, pid: null, mode: "unknown" }]);
120+
});
121+
122+
it("keeps existing stop targets when status cannot confirm a listener PID", async () => {
123+
vi.spyOn(console, "log").mockImplementation(() => {});
124+
const stopManaged = vi.fn(async () => true);
125+
await handlePreviewKillAll(3002, true, {
126+
listManaged: async () => [{ pid: null, port: 32600, projectDir: "/tmp/preview-unverified" }],
127+
stopManaged,
128+
killScanned: async () => ({ killed: 0, unverified: [] }),
129+
});
130+
131+
expect(stopManaged).toHaveBeenCalledExactlyOnceWith("/tmp/preview-unverified", 32600);
132+
});
133+
134+
it("retains scanned metadata when the same endpoint has an unknown saved-status PID", async () => {
135+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
136+
await handlePreviewList(3002, true, {
137+
scan: async () => [
138+
{
139+
pid: "9876",
140+
pidSource: "os",
141+
port: 32600,
142+
host: "[::1]",
143+
projectDir: "/tmp/preview-unverified",
144+
projectName: "scanned-project",
145+
version: "test",
146+
},
147+
],
148+
listManaged: async () => [{ pid: null, port: 32600, projectDir: "/tmp/preview-unverified" }],
149+
});
150+
151+
const result = JSON.parse(log.mock.calls.flat().join("\n")).result;
152+
expect(result.sessions).toHaveLength(1);
153+
expect(result.sessions[0]).toMatchObject({
154+
pid: 9876,
155+
host: "[::1]",
156+
projectName: "scanned-project",
157+
mode: "unknown",
158+
});
159+
expect(result.sessions[0]).not.toHaveProperty("logPath");
160+
});
161+
162+
it.each([true, false])("reports log ownership in JSON=%s", async (json) => {
163+
const dir = tempProject();
164+
writeFileSync(join(dir, "index.html"), "<html></html>");
165+
const readStatus = vi.spyOn(previewLifecycle, "readBackgroundPreviewStatus");
166+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
167+
for (const logPath of [undefined, "/tmp/owned-preview.log"]) {
168+
readStatus.mockResolvedValue({ pid: 5555, port: 32530, projectDir: dir, logPath });
169+
log.mockClear();
170+
await runCommand(previewCommand, {
171+
rawArgs: [dir, "--status", ...(json ? ["--json"] : [])],
172+
});
173+
const output = log.mock.calls.flat().join("\n");
174+
if (json) {
175+
const result = JSON.parse(output).result;
176+
expect(result).toMatchObject({
177+
state: "running",
178+
pid: 5555,
179+
port: 32530,
180+
mode: logPath ? "background" : "unknown",
181+
});
182+
if (logPath) expect(result.logPath).toBe(logPath);
183+
else expect(result).not.toHaveProperty("logPath");
184+
} else if (logPath) {
185+
expect(output).toContain(`Log: ${logPath}`);
186+
expect(output).toContain("Background preview running");
187+
} else {
188+
expect(output).not.toContain("Log:");
189+
expect(output).not.toContain("Background preview running");
190+
expect(output).toContain("Preview running");
191+
}
192+
}
193+
});
194+
});
195+
94196
describe("Studio handoff URLs", () => {
95197
it("hands off the exact timeline project route", () => {
96198
expect(studioDeepLink("http://127.0.0.1:3002", "demo")).toBe(

‎packages/cli/src/commands/preview.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ export default defineCommand({
359359
"status",
360360
previewLifecycleSession({
361361
state: "running",
362-
mode: "background",
362+
mode: status.logPath ? "background" : "unknown",
363363
projectName: project.name,
364364
projectDir: project.dir,
365365
port: status.port,
@@ -371,7 +371,10 @@ export default defineCommand({
371371
return;
372372
}
373373
printStudioSummary(project.name, previewBaseUrl(status.port), project.dir, {
374-
details: [`Background preview running (PID ${status.pid}).`, `Log: ${status.logPath}`],
374+
details: [
375+
`${status.logPath ? "Background preview" : "Preview"} running${status.pid === null ? "" : ` (PID ${status.pid})`}.`,
376+
...(status.logPath ? [`Log: ${status.logPath}`] : []),
377+
],
375378
});
376379
return;
377380
} catch (error) {
@@ -732,17 +735,27 @@ export async function handlePreviewList(
732735
(dependencies.scan ?? scanActiveServers)(startPort),
733736
(dependencies.listManaged ?? listBackgroundPreviewStatuses)(),
734737
]);
738+
const listedSessions = managedSessions.filter(
739+
(session) =>
740+
session.pid !== null ||
741+
!scannedServers.some(
742+
(server) =>
743+
publicPreviewPid(server.pid, null) !== null &&
744+
server.port === session.port &&
745+
resolve(server.projectDir) === resolve(session.projectDir),
746+
),
747+
);
735748
const managedKeys = new Set(
736-
managedSessions.map((session) => `${resolve(session.projectDir)}\0${session.port}`),
749+
listedSessions.map((session) => `${resolve(session.projectDir)}\0${session.port}`),
737750
);
738751
const servers = [
739-
...managedSessions.map((session) => ({
752+
...listedSessions.map((session) => ({
740753
port: session.port,
741754
host: "127.0.0.1",
742755
projectName: basename(session.projectDir),
743756
projectDir: session.projectDir,
744-
version: "managed",
745-
pid: String(session.pid),
757+
version: session.logPath ? "managed" : "unknown",
758+
pid: session.pid === null ? null : String(session.pid),
746759
})),
747760
...scannedServers.filter(
748761
(server) => !managedKeys.has(`${resolve(server.projectDir)}\0${server.port}`),

‎packages/cli/src/commands/previewLifecycle.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,116 @@ function savePreviewSession(stateHome: string): void {
3737
);
3838
}
3939

40+
describe("preview status selection and logs", () => {
41+
const saved = {
42+
pid: 4321,
43+
wrapperIdentity: "wrapper-birth",
44+
port: 32600,
45+
projectDir,
46+
logPath: "/tmp/managed-preview.log",
47+
};
48+
const managed: ActiveServer = { ...server, port: saved.port, pidSource: "os" };
49+
50+
it("prefers the saved preview over a lower sibling when the requested port is absent", async () => {
51+
const stateHome = tempDir("hf-preview-status-");
52+
writePreviewSession(saved, stateHome);
53+
const before = readFileSync(previewSessionPath(projectDir, stateHome), "utf8");
54+
const status = await readBackgroundPreviewStatus(projectDir, 32521, {
55+
stateHome,
56+
preferredPort: 32521,
57+
scan: async () => [{ ...managed, port: 32530, pid: "5555" }, managed],
58+
identity: () => saved.wrapperIdentity,
59+
});
60+
61+
expect(status).toMatchObject({ port: 32600, pid: 4321, logPath: saved.logPath });
62+
expect(readFileSync(previewSessionPath(projectDir, stateHome), "utf8")).toBe(before);
63+
});
64+
65+
it("prefers the exact requested endpoint regardless of the supplied discovery order", async () => {
66+
const stateHome = tempDir("hf-preview-status-");
67+
writePreviewSession(saved, stateHome);
68+
const requested = { ...managed, port: 32580, pid: "8888" };
69+
const status = await readBackgroundPreviewStatus(projectDir, requested.port, {
70+
stateHome,
71+
preferredPort: requested.port,
72+
scan: async () => [{ ...managed, port: 32530, pid: "5555" }, managed, requested],
73+
});
74+
75+
expect(status).toMatchObject({ port: requested.port, pid: 8888 });
76+
expect(status).not.toHaveProperty("logPath");
77+
});
78+
79+
it.each(["4321", "9876"])("keeps the log for a confirmed managed listener %s", async (pid) => {
80+
const stateHome = tempDir("hf-preview-status-");
81+
writePreviewSession(saved, stateHome);
82+
const status = await readBackgroundPreviewStatus(projectDir, saved.port, {
83+
stateHome,
84+
scan: async () => [{ ...managed, pid }],
85+
identity: () => saved.wrapperIdentity,
86+
isDescendant: (child, parent) => child === 9876 && parent === saved.pid,
87+
});
88+
89+
expect(status).toMatchObject({ pid: Number(pid), port: saved.port, logPath: saved.logPath });
90+
});
91+
92+
it.each([
93+
{ name: "another listener", pid: "5555", identity: "wrapper-birth", recorded: "wrapper-birth" },
94+
{
95+
name: "a recycled wrapper",
96+
pid: "4321",
97+
identity: "another-birth",
98+
recorded: "wrapper-birth",
99+
},
100+
{ name: "an unavailable identity", pid: "4321", identity: null, recorded: "wrapper-birth" },
101+
{ name: "a legacy record", pid: "4321", identity: null, recorded: undefined },
102+
{
103+
name: "an unknown listener PID",
104+
pid: null,
105+
identity: "wrapper-birth",
106+
recorded: "wrapper-birth",
107+
},
108+
])("does not attach a managed log to $name", async ({ pid, identity, recorded }) => {
109+
const stateHome = tempDir("hf-preview-status-");
110+
writePreviewSession({ ...saved, wrapperIdentity: recorded }, stateHome);
111+
const before = readFileSync(previewSessionPath(projectDir, stateHome), "utf8");
112+
const status = await readBackgroundPreviewStatus(projectDir, saved.port, {
113+
stateHome,
114+
scan: async () => [{ ...managed, pid }],
115+
identity: () => identity,
116+
isDescendant: () => false,
117+
});
118+
119+
expect(status).toMatchObject({ port: saved.port, pid: pid === null ? null : Number(pid) });
120+
expect(status).not.toHaveProperty("logPath");
121+
expect(readFileSync(previewSessionPath(projectDir, stateHome), "utf8")).toBe(before);
122+
});
123+
124+
it("does not trust a self-reported PID to associate a log", async () => {
125+
const stateHome = tempDir("hf-preview-status-");
126+
writePreviewSession(saved, stateHome);
127+
const status = await readBackgroundPreviewStatus(projectDir, saved.port, {
128+
stateHome,
129+
scan: async () => [{ ...managed, pidSource: "self-reported" }],
130+
identity: () => saved.wrapperIdentity,
131+
});
132+
133+
expect(status).toMatchObject({ port: saved.port, pid: saved.pid });
134+
expect(status).not.toHaveProperty("logPath");
135+
});
136+
137+
it("reports an unmanaged endpoint without inventing a log path", async () => {
138+
const stateHome = tempDir("hf-preview-status-");
139+
const status = await readBackgroundPreviewStatus(projectDir, managed.port, {
140+
stateHome,
141+
scan: async () => [managed],
142+
});
143+
144+
expect(status).toMatchObject({ port: managed.port, pid: saved.pid });
145+
expect(status).not.toHaveProperty("logPath");
146+
expect(existsSync(previewSessionPath(projectDir, stateHome))).toBe(false);
147+
});
148+
});
149+
40150
/** Launch deps whose wrapper (PID 4321) brings up `server` (PID 9876) on spawn and takes it down on kill. */
41151
function reachableChildDependencies(stateHome: string, { immortal = false } = {}) {
42152
let spawned = false;
@@ -330,6 +440,7 @@ describe("background preview lifecycle", () => {
330440
writePreviewSession(
331441
{
332442
pid: 8765,
443+
wrapperIdentity: "custom-wrapper-birth",
333444
port: 41402,
334445
projectDir: otherProjectDir,
335446
logPath: "/tmp/custom.log",
@@ -348,6 +459,7 @@ describe("background preview lifecycle", () => {
348459

349460
const statuses = await listBackgroundPreviewStatuses({
350461
stateHome,
462+
identity: () => "custom-wrapper-birth",
351463
scan: async (startPort) =>
352464
startPort === 41402
353465
? [
@@ -357,6 +469,7 @@ describe("background preview lifecycle", () => {
357469
projectDir: otherProjectDir,
358470
version: "test",
359471
pid: "8765",
472+
pidSource: "os",
360473
},
361474
]
362475
: [],

0 commit comments

Comments
 (0)