@ldelossa/pi-ide 0.2.2 → 0.2.4

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 +103 -9
  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();
@@ -321,7 +377,11 @@ function alignSuggestion(block: string, params: SuggestionParams): string | null
321
377
  const prefix = currentLinePrefix(params);
322
378
  let suggestion = block.replace(/\r\n/g, "\n").replace(/^\n+/, "").replace(/\n+$/, "");
323
379
  if (suggestion === "") return null;
324
- if (prefix.trim() !== "" && suggestion.startsWith(prefix)) suggestion = suggestion.slice(prefix.length);
380
+ // The editor inserts the returned text at the cursor. When the cursor is
381
+ // already after indentation on an otherwise-empty line, a full-line model
382
+ // response often repeats that indentation; strip only that first-line prefix
383
+ // so the editor's existing indent is not doubled.
384
+ if (prefix !== "" && suggestion.startsWith(prefix)) suggestion = suggestion.slice(prefix.length);
325
385
  if (params.cursorInComment) return normalizeCommentSuggestion(suggestion, prefix);
326
386
  if (prefix.trim() !== "") {
327
387
  const firstLine = suggestion.split("\n", 1)[0] ?? "";
@@ -448,6 +508,7 @@ async function findCandidateLockfiles(cwd: string): Promise<Lockfile[]> {
448
508
  */
449
509
  async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi: ExtensionAPI): Promise<IdeClient | null> {
450
510
  const next = new IdeClient(lockfile);
511
+ ui = ctx.ui;
451
512
  next.onNotification = onNotification;
452
513
  next.onRequest("getSuggestions", async (params, signal) => {
453
514
  inFlightSuggestions++;
@@ -490,27 +551,57 @@ async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi:
490
551
  try {
491
552
  await next.connect();
492
553
  } catch (err) {
493
- ui?.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
554
+ ctx.ui.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
494
555
  return null;
495
556
  }
496
557
  client = next;
497
- ui = ctx.ui;
558
+ setStickyLockfile(lockfile);
498
559
  renderWidget();
499
560
  return next;
500
561
  }
501
562
 
502
563
  /**
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.
564
+ * Auto-connect to an IDE.
565
+ *
566
+ * When `preferSticky` is true (session replacement flow), tries the sticky
567
+ * IDE from the previous session first, bypassing the single-candidate rule.
568
+ * Falls back to the cold-start rule when sticky is absent or stale.
569
+ *
570
+ * When `preferSticky` is false (cold startup), connects only when exactly one
571
+ * valid IDE candidate exists for the cwd.
505
572
  */
506
- async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI): Promise<void> {
573
+ async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI, options: { preferSticky: boolean }): Promise<void> {
507
574
  if (client?.isConnected()) return;
508
- const candidates = await findCandidateLockfiles(ctx.cwd);
575
+ if (!isAutoconnectEnabled(ctx.cwd)) return;
576
+
577
+ let candidates = await findCandidateLockfiles(ctx.cwd);
578
+
579
+ if (options.preferSticky) {
580
+ const sticky = getStickyLockfile();
581
+ if (sticky) {
582
+ const candidate = candidates.find((c) => sameLockfile(c, sticky));
583
+ if (candidate) {
584
+ const connected = await connectToLockfile(candidate, ctx, pi);
585
+ if (connected) {
586
+ ctx.ui.notify(`Reconnected to ${candidate.ideName}`, "info");
587
+ return;
588
+ }
589
+ // Treat a failed sticky reconnect as stale. Do not retry the
590
+ // same lockfile in the cold-start fallback below.
591
+ clearStickyLockfile();
592
+ candidates = candidates.filter((c) => !sameLockfile(c, candidate));
593
+ } else {
594
+ // Sticky IDE is gone; clear it and fall through to cold start logic.
595
+ clearStickyLockfile();
596
+ }
597
+ }
598
+ }
599
+
509
600
  if (candidates.length !== 1) return;
510
601
  const lockfile = candidates[0];
511
602
  const connected = await connectToLockfile(lockfile, ctx, pi);
512
603
  if (connected) {
513
- ui?.notify(`Auto-connected to ${lockfile.ideName}`, "info");
604
+ ctx.ui.notify(`Auto-connected to ${lockfile.ideName}`, "info");
514
605
  }
515
606
  }
516
607
 
@@ -526,8 +617,11 @@ export default function (pi: ExtensionAPI) {
526
617
 
527
618
  pi.on("session_start", async (event, ctx) => {
528
619
  sessionCtx = ctx;
620
+ if (event.reason === "startup") {
621
+ await autoConnect(ctx, pi, { preferSticky: false });
622
+ }
529
623
  if (event.reason === "new" || event.reason === "resume" || event.reason === "reload") {
530
- await autoConnect(ctx, pi);
624
+ await autoConnect(ctx, pi, { preferSticky: true });
531
625
  }
532
626
  });
533
627
 
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.4",
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": [