Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
fe6a749
chore(deps): force vitest >=4.1.8 via overrides to resolve GHSA-5xrq-…
LSDimi Jun 4, 2026
35bde12
chore(deps): bump vitest to ^4.1.8 across all workspaces
LSDimi Jun 4, 2026
b05373b
chore(deps): hoist vitest + @vitest/coverage-v8 to root devDependencies
LSDimi Jun 4, 2026
63e8a8c
feat(mcp-server): add singleton types module
LSDimi Jun 4, 2026
663963e
feat(mcp-server): add lockfile primitive with stale-PID detection
LSDimi Jun 4, 2026
909eb68
feat(mcp-server): add pid-file r/w with atomic write
LSDimi Jun 4, 2026
cca8a3f
feat(mcp-server): add process takeover (SIGTERM → grace → SIGKILL)
LSDimi Jun 4, 2026
d0fcb30
feat(mcp-server): add state.json read/write helpers
LSDimi Jun 4, 2026
ea1c26e
feat(mcp-server): add singleton orchestrator (acquire + writeState + …
LSDimi Jun 4, 2026
03e1526
test(mcp-server): add two-process singleton integration test
LSDimi Jun 4, 2026
7137628
feat(mcp-server): wire singleton lock + state-file into startup
LSDimi Jun 4, 2026
a96b9d7
feat(mcp-server): add HTTP /state.json endpoint
LSDimi Jun 4, 2026
09cbd06
feat(bridge-plugin): add discovery module
LSDimi Jun 4, 2026
b6f932b
feat(bridge-plugin): use ranked discovery before port scan in connect()
LSDimi Jun 4, 2026
cd6bd01
feat(mcp-server): add wait_for_reconnect MCP tool
LSDimi Jun 4, 2026
ca945ef
docs(claude-plugin): document wait_for_reconnect in skill troubleshoo…
LSDimi Jun 4, 2026
27363df
style(mcp-server): drop unused buildStateFile import in singleton/ind…
LSDimi Jun 4, 2026
6a9c96f
style: apply prettier formatting across singleton + index.ts
LSDimi Jun 4, 2026
514b7b9
fix(mcp-server): apply Gemini review findings for PR-A1 connection fo…
LSDimi Jun 5, 2026
13daba3
fix(bridge-plugin): drop .js extension from discovery import for webpack
LSDimi Jun 5, 2026
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
1,510 changes: 240 additions & 1,270 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,18 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@vitest/coverage-v8": "^4.1.8",
"eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8",
"husky": "^9.1.7",
"prettier": "^3.8.2",
"typescript-eslint": "^8.58.2"
"typescript-eslint": "^8.58.2",
"vitest": "^4.1.8"
},
"overrides": {
"vite": "^6.4.2",
"esbuild": "^0.25.0"
"esbuild": "^0.25.0",
"vitest": "^4.1.8",
"@vitest/coverage-v8": "^4.1.8"
}
}
2 changes: 1 addition & 1 deletion packages/bridge-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"html-webpack-plugin": "^5.6.0",
"ts-loader": "^9.5.0",
"typescript": "^5.5.0",
"vitest": "^2.1.0",
"vitest": "^4.1.8",
"webpack": "^5.90.0",
"webpack-cli": "^5.1.0"
}
Expand Down
136 changes: 136 additions & 0 deletions packages/bridge-plugin/src/__tests__/discovery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import {
fetchStateJson,
rankCandidates,
discoverCandidatePorts,
type StateFile,
SUPPORTED_VERSION,
} from "../discovery.js";

describe("fetchStateJson", () => {
beforeEach(() => {
vi.stubGlobal("fetch", vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});

it("returns parsed state on 200 with a supported version", async () => {
const state: StateFile = {
version: 1,
pid: 1234,
port: 9500,
serverVersion: "0.4.3",
startedAt: 100,
parentPid: 99,
parentAlive: true,
socketPath: null,
};
(fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => state,
});
const result = await fetchStateJson(9500);
expect(result).toEqual(state);
});

it("returns null on a non-200 response", async () => {
(fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: false });
expect(await fetchStateJson(9500)).toBeNull();
});

it("returns null when fetch throws", async () => {
(fetch as unknown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("boom"));
expect(await fetchStateJson(9500)).toBeNull();
});

it("returns null for a future version", async () => {
(fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({ version: SUPPORTED_VERSION + 1, pid: 1, port: 9500 }),
});
expect(await fetchStateJson(9500)).toBeNull();
});
});

describe("rankCandidates", () => {
function makeState(overrides: Partial<StateFile>): StateFile {
return {
version: 1,
pid: 1,
port: 9500,
serverVersion: "0.4.3",
startedAt: 0,
parentPid: 99,
parentAlive: true,
socketPath: null,
...overrides,
};
}

it("filters out candidates with parentAlive=false", () => {
const ranked = rankCandidates([
{ port: 9500, state: makeState({ parentAlive: false, startedAt: 100 }) },
{ port: 9501, state: makeState({ parentAlive: true, startedAt: 50 }) },
]);
expect(ranked).toHaveLength(1);
expect(ranked[0].port).toBe(9501);
});

it("sorts by startedAt descending (newest first)", () => {
const ranked = rankCandidates([
{ port: 9500, state: makeState({ startedAt: 100 }) },
{ port: 9501, state: makeState({ startedAt: 200 }) },
{ port: 9502, state: makeState({ startedAt: 150 }) },
]);
expect(ranked.map((c) => c.port)).toEqual([9501, 9502, 9500]);
});
});

describe("discoverCandidatePorts (probe-and-rank end-to-end)", () => {
beforeEach(() => {
vi.stubGlobal("fetch", vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});

it("returns ranked candidates, excluding orphans", async () => {
const orphan: StateFile = {
version: 1,
pid: 1,
port: 9500,
serverVersion: "0.4.3",
startedAt: 100,
parentPid: 99,
parentAlive: false,
socketPath: null,
};
const live: StateFile = {
version: 1,
pid: 2,
port: 9501,
serverVersion: "0.4.3",
startedAt: 200,
parentPid: 100,
parentAlive: true,
socketPath: null,
};
const fetchMock = fetch as unknown as ReturnType<typeof vi.fn>;
fetchMock.mockImplementation(async (url: string) => {
if (url.includes(":9500")) return { ok: true, json: async () => orphan };
if (url.includes(":9501")) return { ok: true, json: async () => live };
throw new Error("ECONNREFUSED");
});
const ranked = await discoverCandidatePorts([9500, 9501, 9502]);
expect(ranked).toHaveLength(1);
expect(ranked[0].port).toBe(9501);
});

it("returns empty when no servers respond", async () => {
const fetchMock = fetch as unknown as ReturnType<typeof vi.fn>;
fetchMock.mockRejectedValue(new Error("ECONNREFUSED"));
const ranked = await discoverCandidatePorts([9500, 9501]);
expect(ranked).toEqual([]);
});
});
63 changes: 63 additions & 0 deletions packages/bridge-plugin/src/discovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export interface StateFile {
version: 1;
pid: number;
port: number;
serverVersion: string;
startedAt: number;
parentPid: number;
parentAlive: boolean;
socketPath: string | null;
}

export const SUPPORTED_VERSION = 1;
export const FETCH_TIMEOUT_MS = 300;

export interface DiscoveryCandidate {
port: number;
state: StateFile;
}

export async function fetchStateJson(port: number): Promise<StateFile | null> {
try {
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
let res: Response;
try {
res = await fetch(`http://127.0.0.1:${port}/state.json`, {
signal: controller.signal,
});
if (!res.ok) return null;
const body = (await res.json()) as unknown;
if (
typeof body === "object" &&
body !== null &&
typeof (body as { version?: unknown }).version === "number" &&
(body as { version: number }).version <= SUPPORTED_VERSION
) {
return body as StateFile;
}
return null;
} finally {
clearTimeout(t);
}
} catch {
return null;
}
}
Comment on lines +20 to +46

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In fetchStateJson, the timeout t is cleared on line 27, which is before await res.json() is called. If the server responds to the initial HTTP headers quickly but hangs or sends the body extremely slowly, await res.json() could block indefinitely without any timeout protection.\n\nAdditionally, if fetch throws an error (e.g., ECONNREFUSED), the execution immediately jumps to the catch block, skipping clearTimeout(t) entirely and leaking the timer resource.\n\nWrapping the logic in a try...finally block and keeping the timeout active during the entire request (including the body read) solves both issues cleanly.

export async function fetchStateJson(port: number): Promise<StateFile | null> {\n  const controller = new AbortController();\n  const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n  try {\n    const res = await fetch(`http://127.0.0.1:${port}/state.json`, {\n      signal: controller.signal,\n    });\n    if (!res.ok) return null;\n    const body = (await res.json()) as unknown;\n    if (\n      typeof body === "object" &&\n      body !== null &&\n      typeof (body as { version?: unknown }).version === "number" &&\n      (body as { version: number }).version <= SUPPORTED_VERSION\n    ) {\n      return body as StateFile;\n    }\n    return null;\n  } catch {\n    return null;\n  } finally {\n    clearTimeout(t);\n  }\n}


export function rankCandidates(candidates: DiscoveryCandidate[]): DiscoveryCandidate[] {
return candidates
.filter((c) => c.state.parentAlive !== false)
.sort((a, b) => b.state.startedAt - a.state.startedAt);
}

export async function discoverCandidatePorts(ports: number[]): Promise<DiscoveryCandidate[]> {
const probed = await Promise.all(
ports.map(async (port) => {
const state = await fetchStateJson(port);
return state ? { port, state } : null;
})
);
const candidates = probed.filter((c): c is DiscoveryCandidate => c !== null);
return rankCandidates(candidates);
}
17 changes: 17 additions & 0 deletions packages/bridge-plugin/src/ui-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { attachThemeListener, detectInitialTheme, applyTheme } from "./ui/theme"
import { getLastPort, setLastPort } from "./ui/storage";
import { ActivityLog, type LogEntry } from "./ui/activity-log";
import { isCompatible } from "./ui/version-check";
import { discoverCandidatePorts } from "./discovery";
import {
VERSION,
DXT_DOWNLOAD_URL,
Expand Down Expand Up @@ -171,13 +172,29 @@ async function scanAndConnect(): Promise<void> {
if (lastPort) order.push(lastPort);
for (let p = PORT_MIN; p <= PORT_MAX; p++) if (p !== lastPort) order.push(p);

// Phase 1: discovery probe — find live servers via /state.json
const ranked = await discoverCandidatePorts(order);

// Phase 2: try ranked candidates first (parentAlive=true, newest first)
for (const candidate of ranked) {
const ok = await tryConnect(candidate.port);
if (ok) {
setLastPort(candidate.port);
return;
}
}

// Phase 3: fallback — try all ports in original order (preserves existing scan behavior)
const triedPorts = new Set(ranked.map((c) => c.port));
for (const port of order) {
if (triedPorts.has(port)) continue;
const ok = await tryConnect(port);
if (ok) {
setLastPort(port);
return;
}
}

setStatus("disconnected");
scheduleReconnect();
} finally {
Expand Down
4 changes: 2 additions & 2 deletions packages/claude-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"devDependencies": {
"tsx": "^4.0.0",
"vitest": "^1.0.0",
"typescript": "^5.0.0"
"typescript": "^5.0.0",
"vitest": "^4.1.8"
}
}
1 change: 1 addition & 0 deletions packages/claude-plugin/skills/pluginos-figma/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ If any `pluginos.*` tool returns "No plugin connected" or times out:
1. Tell the user: "Open the PluginOS Bridge plugin in Figma (Plugins → PluginOS Bridge → Run), then let me know."
2. Do NOT silently fall back to Figma MCP.
3. Wait for confirmation before retrying.
4. If the user relaunches the plugin mid-task, call `pluginos.wait_for_reconnect({ timeoutSec: 60 })` to gracefully block until reconnect, then retry the failed op.

## Don'ts

Expand Down
4 changes: 2 additions & 2 deletions packages/mcp-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,11 @@
"@pluginos/shared": "*",
"@types/adm-zip": "^0.5.8",
"@types/ws": "^8.5.0",
"@vitest/coverage-v8": "^2.1.9",
"@vitest/coverage-v8": "^4.1.8",
"adm-zip": "^0.5.17",
"tsup": "^8.5.1",
"tsx": "^4.19.0",
"typescript": "^5.5.0",
"vitest": "^2.1.0"
"vitest": "^4.1.8"
}
}
47 changes: 47 additions & 0 deletions packages/mcp-server/src/__tests__/http-state-endpoint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { describe, it, expect } from "vitest";
import { createHttpServer } from "../http-server.js";
import type { StateFile } from "../singleton/types.js";

describe("HTTP /state.json endpoint", () => {
it("returns the current state object when set", async () => {
const state: StateFile = {
version: 1,
pid: 1234,
port: 9500,
serverVersion: "0.4.3",
startedAt: 1700000000000,
parentPid: 99,
parentAlive: true,
socketPath: null,
};
const server = createHttpServer(
() => "<html></html>",
() => state
);
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
const port = (server.address() as { port: number }).port;
try {
const res = await fetch(`http://127.0.0.1:${port}/state.json`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toEqual(state);
} finally {
server.close();
}
});

it("returns 503 when no state is set", async () => {
const server = createHttpServer(
() => "<html></html>",
() => null
);
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
const port = (server.address() as { port: number }).port;
try {
const res = await fetch(`http://127.0.0.1:${port}/state.json`);
expect(res.status).toBe(503);
} finally {
server.close();
}
});
});
Loading
Loading