@ldelossa/pi-ide 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +44 -3
  2. package/index.ts +98 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -50,9 +50,11 @@ Once both are running, use `/ide` inside pi to connect to the editor.
50
50
 
51
51
  1. Editor starts a loopback MCP server on a free TCP port. Writes a lockfile to
52
52
  `$PI_IDE_LOCK_DIR` (default `~/.pi/ide/<port>.lock`). Removes it on exit.
53
- 2. User runs `/ide` in pi. Extension enumerates lockfiles, filters to entries
54
- whose `workspaceFolders` cover `cwd`, whose `pid` is alive, and whose port
55
- accepts connections. Prompts on multiple matches.
53
+ 2. On startup, if `pi-ide.autoconnect` is not `false` and exactly one valid
54
+ lockfile matches `cwd`, the extension connects automatically. A sticky
55
+ reconnect target is remembered across `/new` sessions, keeping the same
56
+ IDE when multiple editors are open. Use `/ide` to manually connect,
57
+ switch IDEs, or disconnect.
56
58
  3. Extension opens `ws://127.0.0.1:<port>/` with header
57
59
  `x-pi-ide-authorization: <authToken>` and runs MCP `initialize`.
58
60
  4. While connected:
@@ -66,6 +68,45 @@ Once both are running, use `/ide` inside pi to connect to the editor.
66
68
  surfaced to the agent.
67
69
  5. Session shutdown closes the socket.
68
70
 
71
+ ## Autoconnect
72
+
73
+ Autoconnect saves a manual `/ide` step by connecting to the IDE automatically.
74
+ It is enabled by default.
75
+
76
+ Connections are made on two occasions:
77
+
78
+ **On start**
79
+ 1. `pi-ide.autoconnect` is not `false`
80
+ 2. Exactly one valid IDE lockfile exists for the current working directory
81
+
82
+ **On session replacement** (`/new`, `/resume`, `/reload`)
83
+ If the previous session was connected to an IDE, pi-ide tries to reconnect
84
+ to that same IDE. This sticky reconnect bypasses the single-candidate rule,
85
+ which means it can reconnect even when a second IDE has since started in the
86
+ same directory. If the sticky IDE is no longer valid (closed, stopped,
87
+ connection fails, or its project changed), autoconnect falls back to the
88
+ cold-start rule.
89
+
90
+ ### Disabling
91
+
92
+ Add to any Pi settings file:
93
+
94
+ ```json
95
+ {
96
+ "pi-ide": {
97
+ "autoconnect": false
98
+ }
99
+ }
100
+ ```
101
+
102
+ | Scope | File |
103
+ |-------|------|
104
+ | Global | `~/.pi/agent/settings.json` |
105
+ | Project | `.pi/settings.json` |
106
+
107
+ Project settings override global settings. A missing setting is treated as
108
+ enabled.
109
+
69
110
  ## Lockfile
70
111
 
71
112
  Path: `$PI_IDE_LOCK_DIR/<port>.lock` (default `~/.pi/ide/<port>.lock`).
package/index.ts CHANGED
@@ -3,6 +3,7 @@ import { basename, resolve as resolvePath } from "node:path";
3
3
  import { completeSimple } from "@earendil-works/pi-ai";
4
4
  import {
5
5
  isToolCallEventType,
6
+ SettingsManager,
6
7
  type ExtensionAPI,
7
8
  type ExtensionContext,
8
9
  type ExtensionUIContext,
@@ -31,6 +32,60 @@ const WIDGET_KEY = "pi-ide";
31
32
  const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32
33
  const SPINNER_INTERVAL_MS = 80;
33
34
 
35
+ // --- Autoconnect config & state ---
36
+ const PI_IDE_SETTINGS_KEY = "pi-ide";
37
+ const STICKY_STATE_KEY = Symbol.for("@ldelossa/pi-ide:sticky-state");
38
+
39
+ type PiIdeSettings = {
40
+ autoconnect?: boolean;
41
+ };
42
+
43
+ type StickyState = {
44
+ lockfile?: Lockfile;
45
+ };
46
+
47
+ // --- Settings helpers ---
48
+
49
+ function extractPiIdeSettings(settings: Record<string, unknown>): PiIdeSettings {
50
+ const raw = settings[PI_IDE_SETTINGS_KEY];
51
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
52
+ const obj = raw as Record<string, unknown>;
53
+ return {
54
+ autoconnect: typeof obj.autoconnect === "boolean" ? obj.autoconnect : undefined,
55
+ };
56
+ }
57
+
58
+ function isAutoconnectEnabled(cwd: string): boolean {
59
+ const manager = SettingsManager.create(cwd);
60
+ const globalSettings = extractPiIdeSettings(manager.getGlobalSettings() as Record<string, unknown>);
61
+ const projectSettings = extractPiIdeSettings(manager.getProjectSettings() as Record<string, unknown>);
62
+ return projectSettings.autoconnect ?? globalSettings.autoconnect ?? true;
63
+ }
64
+
65
+ // --- Sticky state helpers ---
66
+
67
+ function getStickyState(): StickyState {
68
+ const g = globalThis as typeof globalThis & Record<symbol, StickyState | undefined>;
69
+ g[STICKY_STATE_KEY] ??= {};
70
+ return g[STICKY_STATE_KEY]!;
71
+ }
72
+
73
+ function setStickyLockfile(lockfile: Lockfile): void {
74
+ getStickyState().lockfile = lockfile;
75
+ }
76
+
77
+ function clearStickyLockfile(): void {
78
+ delete getStickyState().lockfile;
79
+ }
80
+
81
+ function getStickyLockfile(): Lockfile | undefined {
82
+ return getStickyState().lockfile;
83
+ }
84
+
85
+ function sameLockfile(a: Lockfile, b: Lockfile): boolean {
86
+ return a.port === b.port && a.pid === b.pid && a.authToken === b.authToken;
87
+ }
88
+
34
89
  let client: IdeClient | null = null;
35
90
  let state: EditorState = { filePath: null, cursorLine: null, selection: null };
36
91
  let ui: ExtensionUIContext | null = null;
@@ -41,6 +96,7 @@ let spinnerFrame = 0;
41
96
 
42
97
  function disconnectFromIde(): void {
43
98
  if (!client) return;
99
+ clearStickyLockfile();
44
100
  const old = client;
45
101
  client = null;
46
102
  old.close();
@@ -448,6 +504,7 @@ async function findCandidateLockfiles(cwd: string): Promise<Lockfile[]> {
448
504
  */
449
505
  async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi: ExtensionAPI): Promise<IdeClient | null> {
450
506
  const next = new IdeClient(lockfile);
507
+ ui = ctx.ui;
451
508
  next.onNotification = onNotification;
452
509
  next.onRequest("getSuggestions", async (params, signal) => {
453
510
  inFlightSuggestions++;
@@ -490,27 +547,57 @@ async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi:
490
547
  try {
491
548
  await next.connect();
492
549
  } catch (err) {
493
- ui?.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
550
+ ctx.ui.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
494
551
  return null;
495
552
  }
496
553
  client = next;
497
- ui = ctx.ui;
554
+ setStickyLockfile(lockfile);
498
555
  renderWidget();
499
556
  return next;
500
557
  }
501
558
 
502
559
  /**
503
- * Auto-connect to the single matching IDE for this cwd, if exactly one valid
504
- * lockfile exists. Does nothing when zero or multiple candidates are found.
560
+ * Auto-connect to an IDE.
561
+ *
562
+ * When `preferSticky` is true (session replacement flow), tries the sticky
563
+ * IDE from the previous session first, bypassing the single-candidate rule.
564
+ * Falls back to the cold-start rule when sticky is absent or stale.
565
+ *
566
+ * When `preferSticky` is false (cold startup), connects only when exactly one
567
+ * valid IDE candidate exists for the cwd.
505
568
  */
506
- async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI): Promise<void> {
569
+ async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI, options: { preferSticky: boolean }): Promise<void> {
507
570
  if (client?.isConnected()) return;
508
- const candidates = await findCandidateLockfiles(ctx.cwd);
571
+ if (!isAutoconnectEnabled(ctx.cwd)) return;
572
+
573
+ let candidates = await findCandidateLockfiles(ctx.cwd);
574
+
575
+ if (options.preferSticky) {
576
+ const sticky = getStickyLockfile();
577
+ if (sticky) {
578
+ const candidate = candidates.find((c) => sameLockfile(c, sticky));
579
+ if (candidate) {
580
+ const connected = await connectToLockfile(candidate, ctx, pi);
581
+ if (connected) {
582
+ ctx.ui.notify(`Reconnected to ${candidate.ideName}`, "info");
583
+ return;
584
+ }
585
+ // Treat a failed sticky reconnect as stale. Do not retry the
586
+ // same lockfile in the cold-start fallback below.
587
+ clearStickyLockfile();
588
+ candidates = candidates.filter((c) => !sameLockfile(c, candidate));
589
+ } else {
590
+ // Sticky IDE is gone; clear it and fall through to cold start logic.
591
+ clearStickyLockfile();
592
+ }
593
+ }
594
+ }
595
+
509
596
  if (candidates.length !== 1) return;
510
597
  const lockfile = candidates[0];
511
598
  const connected = await connectToLockfile(lockfile, ctx, pi);
512
599
  if (connected) {
513
- ui?.notify(`Auto-connected to ${lockfile.ideName}`, "info");
600
+ ctx.ui.notify(`Auto-connected to ${lockfile.ideName}`, "info");
514
601
  }
515
602
  }
516
603
 
@@ -526,8 +613,11 @@ export default function (pi: ExtensionAPI) {
526
613
 
527
614
  pi.on("session_start", async (event, ctx) => {
528
615
  sessionCtx = ctx;
616
+ if (event.reason === "startup") {
617
+ await autoConnect(ctx, pi, { preferSticky: false });
618
+ }
529
619
  if (event.reason === "new" || event.reason === "resume" || event.reason === "reload") {
530
- await autoConnect(ctx, pi);
620
+ await autoConnect(ctx, pi, { preferSticky: true });
531
621
  }
532
622
  });
533
623
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ldelossa/pi-ide",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Pi extension that connects to a running editor (Neovim today, more later) over a local WebSocket. Adds ambient editor context to the agent and routes write/edit tool calls through interactive diffs in the editor.",
5
5
  "keywords": ["pi-package", "pi", "ide", "neovim"],
6
6
  "files": [