inplan 0.3.10 → 0.3.12

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.
@@ -1695,6 +1695,13 @@ ${body.replace(/\s*$/, "")}
1695
1695
  }
1696
1696
  });
1697
1697
  let restarting = false;
1698
+ const logRestart = (msg) => {
1699
+ try {
1700
+ node_fs.appendFileSync(node_path.join(node_os.homedir(), ".inplan", "restart.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
1701
+ `);
1702
+ } catch {
1703
+ }
1704
+ };
1698
1705
  electron.ipcMain.handle("app:restart", async () => {
1699
1706
  const file = session?.paths.file;
1700
1707
  const cli = process.env.INPLAN_CLI;
@@ -1705,19 +1712,31 @@ ${body.replace(/\s*$/, "")}
1705
1712
  dir = node_fs.mkdtempSync(node_path.join(node_os.tmpdir(), "inplan-restart-"));
1706
1713
  const readyPath = node_path.join(dir, "ready");
1707
1714
  const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = process.env;
1708
- const launched = await new Promise((done) => {
1709
- node_child_process.execFile("node", [cli, "launch-editor", file], { env: { ...env, INPLAN_RESTART_READY: readyPath }, timeout: 2e4 }, (err, stdout) => {
1710
- try {
1711
- done(!err && JSON.parse(stdout.trim()).status === "launched");
1712
- } catch {
1713
- done(false);
1714
- }
1715
+ const attempts = [];
1716
+ if (process.env.INPLAN_NODE) attempts.push([process.env.INPLAN_NODE, {}]);
1717
+ attempts.push(["node", {}], [process.execPath, { ELECTRON_RUN_AS_NODE: "1" }]);
1718
+ let launched = false;
1719
+ for (const [exe, extra] of attempts) {
1720
+ launched = await new Promise((done) => {
1721
+ node_child_process.execFile(exe, [cli, "launch-editor", file], { env: { ...env, ...extra, INPLAN_RESTART_READY: readyPath }, timeout: 2e4 }, (err, stdout, stderr) => {
1722
+ try {
1723
+ done(!err && JSON.parse(stdout.trim()).status === "launched");
1724
+ } catch {
1725
+ done(false);
1726
+ } finally {
1727
+ if (err) logRestart(`launch via ${exe} failed: ${err.message} ${stderr.trim()}`);
1728
+ }
1729
+ });
1715
1730
  });
1716
- });
1731
+ if (launched) break;
1732
+ }
1717
1733
  if (!launched) return { ok: false };
1718
1734
  const deadline = Date.now() + 15e3;
1719
1735
  while (!node_fs.existsSync(readyPath)) {
1720
- if (Date.now() >= deadline) return { ok: false };
1736
+ if (Date.now() >= deadline) {
1737
+ logRestart("the replacement started but never reported ready");
1738
+ return { ok: false };
1739
+ }
1721
1740
  await new Promise((done) => setTimeout(done, 100));
1722
1741
  }
1723
1742
  } catch {
@@ -43635,6 +43635,9 @@ var EN = {
43635
43635
  // transient status messages
43636
43636
  "msg.proposedReview": "agent proposed changes — review below",
43637
43637
  "msg.agentUpdated": "agent updated the document",
43638
+ "msg.agentDraftKeptBoth": "The agent wrote its draft while you were typing — it is below your text. Both are kept; nothing is saved yet.",
43639
+ "msg.agentDraftRevised": "The agent revised its draft below your text — the new version is shown. Nothing is saved yet.",
43640
+ "msg.agentUpdatedKept": "The agent updated the document — its version is shown, and your other unsaved edits are kept.",
43638
43641
  "msg.agentUpdatedUnsaved": "The agent updated the document — your unsaved edits are kept here. Save or reopen to see its version.",
43639
43642
  "msg.agentCommented": "The agent left a comment — it is in the rail. Your unsaved edits are untouched.",
43640
43643
  "msg.agentCommentedAndChanged": "The agent left a comment (now in the rail) and changed the body — your unsaved edits are kept, so its version is not shown.",
@@ -43646,6 +43649,9 @@ var EN = {
43646
43649
  "msg.tookBack": "you took back control — the agent didn't hand it back",
43647
43650
  "msg.autosaving": "auto-saving…",
43648
43651
  "msg.autosaved": "autosaved (backup)",
43652
+ "msg.saved": "saved",
43653
+ "msg.checkpointSaved": "checkpoint saved",
43654
+ "msg.saveUnconfirmed": "Couldn't confirm your changes are saved — check your connection. inplan keeps retrying.",
43649
43655
  "msg.turnFinished": "turn finished — waiting for agent",
43650
43656
  "msg.unsavedAnswer": "You have an unsaved answer — click “Answer” to save it, or Send again to skip.",
43651
43657
  "msg.cantAnchor": "Comments can't be anchored to this selection",
@@ -43788,6 +43794,10 @@ var EN = {
43788
43794
  "thread.save": "Save",
43789
43795
  "thread.more": "More",
43790
43796
  "thread.copyDocLink": "Copy link to document",
43797
+ "thread.copyCommentLink": "Copy link to this comment",
43798
+ "msg.commentLinkGone": "The comment this link points to no longer exists.",
43799
+ "msg.copyCommentLinkDone": "Comment link copied to the clipboard.",
43800
+ "msg.copyCommentLinkFailed": "Copying the comment link failed — nothing was placed on the clipboard.",
43791
43801
  "msg.copyDocLinkDone": "Link copied to the clipboard.",
43792
43802
  "msg.copyDocLinkFailed": "Copying the link failed — nothing was placed on the clipboard.",
43793
43803
  "thread.modify": "Modify",
@@ -44903,7 +44913,12 @@ var SourceEditor = reactExports.forwardRef(function SourceEditor2({ value, edita
44903
44913
  if (!v2 || bindingRef.current) return;
44904
44914
  const current = v2.state.doc.toString();
44905
44915
  if (value !== current) {
44906
- v2.dispatch({ changes: { from: 0, to: current.length, insert: value } });
44916
+ let from = 0;
44917
+ const max = Math.min(value.length, current.length);
44918
+ while (from < max && value.charCodeAt(from) === current.charCodeAt(from)) from++;
44919
+ let tail = 0;
44920
+ while (tail < max - from && value.charCodeAt(value.length - 1 - tail) === current.charCodeAt(current.length - 1 - tail)) tail++;
44921
+ v2.dispatch({ changes: { from, to: current.length - tail, insert: value.slice(from, value.length - tail) } });
44907
44922
  }
44908
44923
  }, [value]);
44909
44924
  reactExports.useEffect(() => {
@@ -46029,6 +46044,7 @@ var IMAGE_EXT_BY_MIME = {
46029
46044
  "image/svg+xml": "svg"
46030
46045
  };
46031
46046
  var BINDING_READY_TIMEOUT_MS = 1e4;
46047
+ var DURABLE_ACK_TIMEOUT_MS = 3e4;
46032
46048
  function settleWithin(ready, ms) {
46033
46049
  if (!ready) return Promise.resolve(false);
46034
46050
  let timer;
@@ -46044,6 +46060,17 @@ function settleWithin(ready, ms) {
46044
46060
  }
46045
46061
  var ZOOM_MIN = 0.6;
46046
46062
  var ZOOM_MAX = 1.8;
46063
+ function commentLinkFor(docLink, param, id2) {
46064
+ if (!param.trim() || !docLink) return "";
46065
+ try {
46066
+ const u2 = new URL(docLink);
46067
+ if (u2.protocol !== "https:" && u2.protocol !== "http:") return "";
46068
+ u2.searchParams.set(param, id2);
46069
+ return u2.toString();
46070
+ } catch {
46071
+ return "";
46072
+ }
46073
+ }
46047
46074
  function anchoredText(body, id2) {
46048
46075
  const m2 = new RegExp(`\\[([^\\]]*)\\]\\(#${id2}\\)`).exec(body);
46049
46076
  return m2 ? m2[1] : null;
@@ -46229,6 +46256,7 @@ function App(props = {}) {
46229
46256
  const commentRangeRef = reactExports.useRef(null);
46230
46257
  const docPathRef = reactExports.useRef("");
46231
46258
  const docLinkRef = reactExports.useRef("");
46259
+ const commentLinkParamRef = reactExports.useRef("");
46232
46260
  const railRef = reactExports.useRef(null);
46233
46261
  const overlayComments = panes === 1 && commentOverlay;
46234
46262
  reactExports.useEffect(() => {
@@ -46248,12 +46276,32 @@ function App(props = {}) {
46248
46276
  }, [overlayComments, focused]);
46249
46277
  const editorRef = reactExports.useRef(null);
46250
46278
  const [pendingFocusCommentId, setPendingFocusCommentId] = reactExports.useState(null);
46279
+ const missingFocusCommentId = reactExports.useRef(null);
46251
46280
  const autosaveTimer = reactExports.useRef(null);
46281
+ const durableAckedRef = reactExports.useRef(null);
46282
+ const durablePendingRef = reactExports.useRef(null);
46283
+ const durableTimer = reactExports.useRef(null);
46284
+ const awaitDurable = reactExports.useCallback((content2) => {
46285
+ if (!hostApi().onDurable) return false;
46286
+ if (durableTimer.current) clearTimeout(durableTimer.current);
46287
+ if (durableAckedRef.current === content2) {
46288
+ durablePendingRef.current = null;
46289
+ setStatus(t2("msg.saved"));
46290
+ return true;
46291
+ }
46292
+ durablePendingRef.current = content2;
46293
+ setStatus(t2("msg.autosaving"));
46294
+ durableTimer.current = setTimeout(() => {
46295
+ if (durablePendingRef.current === content2) setStatus(t2("msg.saveUnconfirmed"));
46296
+ }, DURABLE_ACK_TIMEOUT_MS);
46297
+ return true;
46298
+ }, []);
46252
46299
  const history2 = reactExports.useRef([]);
46253
46300
  const future = reactExports.useRef([]);
46254
46301
  const humanTouchedComments = reactExports.useRef(/* @__PURE__ */ new Set());
46255
46302
  const historyByDoc = reactExports.useRef(/* @__PURE__ */ new Map());
46256
46303
  const savedRef = reactExports.useRef("");
46304
+ const landedBodyRef = reactExports.useRef(null);
46257
46305
  const [checkpoint, setCheckpoint] = reactExports.useState("");
46258
46306
  const skipPreviewScroll = reactExports.useRef(false);
46259
46307
  const autoResolvedRef = reactExports.useRef(/* @__PURE__ */ new Set());
@@ -46295,11 +46343,12 @@ function App(props = {}) {
46295
46343
  let cancelled = false;
46296
46344
  const adoptedAtStart = externalAdoptedRef.current;
46297
46345
  const bindingReady = settleWithin(hostApi().binding?.ready, BINDING_READY_TIMEOUT_MS);
46298
- Promise.all([hostApi().load(), bindingReady]).then(([{ content: content2, path, readOnly: ro, focusCommentId, shareLink, draftPending }, synced]) => {
46346
+ Promise.all([hostApi().load(), bindingReady]).then(([{ content: content2, path, readOnly: ro, focusCommentId, shareLink, commentLinkParam, draftPending }, synced]) => {
46299
46347
  if (cancelled || docGenRef.current !== loadGen) return;
46300
46348
  docPathRef.current = path;
46301
46349
  humanTouchedComments.current = /* @__PURE__ */ new Set();
46302
46350
  docLinkRef.current = shareLink?.trim() ? shareLink : path;
46351
+ commentLinkParamRef.current = commentLinkParam?.trim() ?? "";
46303
46352
  setReadOnly(!!ro);
46304
46353
  setPendingFocusCommentId(focusCommentId ?? null);
46305
46354
  if (externalAdoptedRef.current === adoptedAtStart) {
@@ -46316,10 +46365,11 @@ function App(props = {}) {
46316
46365
  void hostApi().getProposal().then((parked) => docGenRef.current === gen && parked != null && showProposal(parked.content, parked.id, parked.baseContent, parked.pending)).catch(() => {
46317
46366
  });
46318
46367
  }).catch(() => setLoaded(true));
46319
- const processNavigated = ({ content: content2, path, readOnly: ro, focusCommentId, shareLink, draftPending }) => {
46368
+ const processNavigated = ({ content: content2, path, readOnly: ro, focusCommentId, shareLink, commentLinkParam, draftPending }) => {
46320
46369
  if (docPathRef.current) historyByDoc.current.set(docPathRef.current, { undo: history2.current, redo: future.current, touched: humanTouchedComments.current });
46321
46370
  docPathRef.current = path;
46322
46371
  docLinkRef.current = shareLink?.trim() ? shareLink : path;
46372
+ commentLinkParamRef.current = commentLinkParam?.trim() ?? "";
46323
46373
  setLoaded(true);
46324
46374
  setReadOnly(!!ro);
46325
46375
  resetMentionRoster();
@@ -46418,7 +46468,37 @@ function App(props = {}) {
46418
46468
  });
46419
46469
  const takenRevisions = revised.filter((c, i) => c !== prevDoc.comments[i]);
46420
46470
  const arriving = incoming.comments.filter((c) => !mine.has(c.id) && !humanTouchedComments.current.has(c.id)).map((c) => !c.parentId && c.anchor !== "doc" && !prevDoc.body.includes(`](#${c.id})`) ? { ...c, anchor: "doc" } : c);
46421
- const withComments = commentStore ? { ...prevDoc, comments: storeList } : { ...prevDoc, comments: orderComments([...revised, ...arriving]) };
46471
+ const held = landedBodyRef.current;
46472
+ const heldBody = held && held.path === docPathRef.current && held.saved === savedRef.current ? held.body : null;
46473
+ let savedBody = null;
46474
+ try {
46475
+ savedBody = savedRef.current === "" ? "" : parse(savedRef.current).body;
46476
+ } catch {
46477
+ }
46478
+ const bodyBase = heldBody ?? savedBody;
46479
+ const blank = (s) => s.trim() === "";
46480
+ let body = prevDoc.body;
46481
+ let bodyTake = "none";
46482
+ let prefix = "";
46483
+ let inserted = incoming.body;
46484
+ if (!hostApi().binding?.setText && bodyBase !== null && !(blank(bodyBase) ? blank(incoming.body) : incoming.body === bodyBase)) {
46485
+ if (heldBody !== null && held.prefix !== "" && prevDoc.body === held.prefix + held.inserted) {
46486
+ prefix = held.prefix;
46487
+ inserted = incoming.body.replace(/^\s+/, "");
46488
+ body = prefix + inserted;
46489
+ bodyTake = "revised";
46490
+ } else if (prevDoc.body === bodyBase || blank(bodyBase) && blank(prevDoc.body)) {
46491
+ body = incoming.body;
46492
+ bodyTake = "taken";
46493
+ } else if (blank(bodyBase) && heldBody === null) {
46494
+ prefix = prevDoc.body + (prevDoc.body.endsWith("\n\n") ? "" : prevDoc.body.endsWith("\n") ? "\n" : "\n\n");
46495
+ inserted = incoming.body.replace(/^\s+/, "");
46496
+ body = prefix + inserted;
46497
+ bodyTake = "both";
46498
+ }
46499
+ if (bodyTake !== "none") landedBodyRef.current = { path: docPathRef.current, saved: savedRef.current, body: incoming.body, prefix, inserted };
46500
+ }
46501
+ const withComments = commentStore ? { ...prevDoc, body, comments: storeList } : { ...prevDoc, body, comments: orderComments([...revised, ...arriving]) };
46422
46502
  const settleList = [];
46423
46503
  for (const c of [...settledDelta, ...arriving, ...takenRevisions]) {
46424
46504
  if (!settleList.some((x2) => x2.id === c.id)) settleList.push(c);
@@ -46427,10 +46507,10 @@ function App(props = {}) {
46427
46507
  setDoc(withComments);
46428
46508
  docRef.current = withComments;
46429
46509
  externalAdoptedRef.current++;
46430
- let bodyMoved = true;
46431
- try {
46432
- bodyMoved = savedRef.current !== "" ? incoming.body !== parse(savedRef.current).body : incoming.body.trim() !== "";
46433
- } catch {
46510
+ const bodyMoved = bodyBase === null ? true : savedRef.current === "" && heldBody === null ? incoming.body.trim() !== "" : incoming.body !== bodyBase;
46511
+ if (bodyTake !== "none") {
46512
+ setStatus(t2(bodyTake === "both" ? "msg.agentDraftKeptBoth" : bodyTake === "revised" ? "msg.agentDraftRevised" : "msg.agentUpdatedKept"));
46513
+ return;
46434
46514
  }
46435
46515
  const gained = commentStore ? settledDelta.length : arriving.length + takenRevisions.length;
46436
46516
  setStatus(t2(gained > 0 ? bodyMoved ? "msg.agentCommentedAndChanged" : "msg.agentCommented" : "msg.agentUpdatedUnsaved"));
@@ -46642,7 +46722,7 @@ function App(props = {}) {
46642
46722
  if (mode.autosaveKind === "canonical") {
46643
46723
  savedRef.current = content2;
46644
46724
  setDirty(false);
46645
- setStatus(t2("msg.autosaving"));
46725
+ if (!awaitDurable(content2)) setStatus(t2("msg.autosaving"));
46646
46726
  } else {
46647
46727
  setStatus(t2("msg.autosaved"));
46648
46728
  }
@@ -46651,6 +46731,22 @@ function App(props = {}) {
46651
46731
  if (autosaveTimer.current) clearTimeout(autosaveTimer.current);
46652
46732
  };
46653
46733
  }, [doc2, dirty, loaded, cadence]);
46734
+ reactExports.useEffect(() => {
46735
+ const onDurable = hostApi().onDurable;
46736
+ if (!loaded || !onDurable) return;
46737
+ const off = onDurable(() => {
46738
+ const acked = serialize(docRef.current);
46739
+ durableAckedRef.current = acked;
46740
+ if (durablePendingRef.current !== acked || dirtyRef.current) return;
46741
+ durablePendingRef.current = null;
46742
+ if (durableTimer.current) clearTimeout(durableTimer.current);
46743
+ setStatus(t2("msg.saved"));
46744
+ });
46745
+ return () => {
46746
+ off();
46747
+ if (durableTimer.current) clearTimeout(durableTimer.current);
46748
+ };
46749
+ }, [loaded]);
46654
46750
  reactExports.useEffect(() => {
46655
46751
  if (loaded) void hostApi().reportState(dirty, serialize(docRef.current));
46656
46752
  }, [dirty, doc2, loaded]);
@@ -46821,8 +46917,10 @@ function App(props = {}) {
46821
46917
  if (kind === "canonical") {
46822
46918
  savedRef.current = content2;
46823
46919
  setDirty(false);
46920
+ if (!awaitDurable(content2)) setStatus(t2("msg.saved"));
46921
+ } else {
46922
+ setStatus(t2("msg.checkpointSaved"));
46824
46923
  }
46825
- setStatus(kind === "canonical" ? "saved" : "checkpoint saved");
46826
46924
  }, [cadence, mode, readOnly2]);
46827
46925
  saveNowRef.current = saveNow;
46828
46926
  const pendingAnswersRef = reactExports.useRef(/* @__PURE__ */ new Set());
@@ -47324,13 +47422,26 @@ function App(props = {}) {
47324
47422
  reactExports.useEffect(() => {
47325
47423
  if (!loaded || !pendingFocusCommentId) return;
47326
47424
  const id2 = pendingFocusCommentId;
47327
- setPendingFocusCommentId(null);
47328
47425
  const c = doc2.comments.find((x2) => x2.id === id2);
47329
- const rootId = c?.parentId ?? id2;
47426
+ if (!c) {
47427
+ if (missingFocusCommentId.current !== id2) {
47428
+ missingFocusCommentId.current = id2;
47429
+ setStatus(t2("msg.commentLinkGone"));
47430
+ }
47431
+ return;
47432
+ }
47433
+ missingFocusCommentId.current = null;
47434
+ const rootId = c.parentId ?? id2;
47330
47435
  if (!visible.some((o) => o.thread.root.id === rootId)) setShowResolvedOrphaned(true);
47331
- const raf = requestAnimationFrame(() => focusComment(id2));
47436
+ setStatus("");
47437
+ if (panes === 1) setCommentOverlay(true);
47438
+ if (panes === 2 && rightTab !== "comments") setRightTab("comments");
47439
+ const raf = requestAnimationFrame(() => {
47440
+ focusComment(id2);
47441
+ setPendingFocusCommentId(null);
47442
+ });
47332
47443
  return () => cancelAnimationFrame(raf);
47333
- }, [loaded, pendingFocusCommentId, focusComment, doc2.comments, visible]);
47444
+ }, [loaded, pendingFocusCommentId, focusComment, doc2.comments, visible, panes, rightTab, t2]);
47334
47445
  const revealTip = resolvedCount > 0 && orphanedCount > 0 ? t2("rail.showResolved", { resolved: resolvedCount, orphaned: orphanedCount }) : resolvedCount > 0 ? t2("rail.showResolvedOnly", { resolved: resolvedCount }) : t2("rail.showOrphanedOnly", { orphaned: orphanedCount });
47335
47446
  const selBlocker = reactExports.useMemo(() => {
47336
47447
  const sel = window.getSelection();
@@ -47870,7 +47981,9 @@ function App(props = {}) {
47870
47981
  onEdit: (id2, text2) => apply(editCommentText(docRef.current, id2, text2), { type: "comment_modified", payload: { id: id2 } }),
47871
47982
  onDelete: (id2) => apply(deleteComment(docRef.current, id2), { type: "comment_deleted", payload: { id: id2 } }),
47872
47983
  docLink: () => docLinkRef.current,
47873
- onCopyOutcome: (ok2) => setStatus(t2(ok2 ? "msg.copyDocLinkDone" : "msg.copyDocLinkFailed"))
47984
+ commentLink: (id2) => commentLinkFor(docLinkRef.current, commentLinkParamRef.current, id2),
47985
+ onCopyOutcome: (ok2) => setStatus(t2(ok2 ? "msg.copyDocLinkDone" : "msg.copyDocLinkFailed")),
47986
+ onCopyCommentOutcome: (ok2) => setStatus(t2(ok2 ? "msg.copyCommentLinkDone" : "msg.copyCommentLinkFailed"))
47874
47987
  }
47875
47988
  )
47876
47989
  ] }, o.thread.root.id)),
@@ -48455,6 +48568,18 @@ function ThreadCard(props) {
48455
48568
  children: t2("thread.copyDocLink")
48456
48569
  }
48457
48570
  ),
48571
+ props.commentLink(c.id) !== "" && /* @__PURE__ */ jsxRuntimeExports.jsx(
48572
+ "button",
48573
+ {
48574
+ onClick: () => {
48575
+ const write = navigator.clipboard?.writeText?.(props.commentLink(c.id));
48576
+ if (write) void write.then(() => props.onCopyCommentOutcome(true), () => props.onCopyCommentOutcome(false));
48577
+ else props.onCopyCommentOutcome(false);
48578
+ setMenuOpenId(null);
48579
+ },
48580
+ children: t2("thread.copyCommentLink")
48581
+ }
48582
+ ),
48458
48583
  /* @__PURE__ */ jsxRuntimeExports.jsx(
48459
48584
  "button",
48460
48585
  {
@@ -21,7 +21,7 @@
21
21
  content="default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' inplan-plugin:; img-src 'self' file: https:; connect-src 'self' inplan-plugin: ws://127.0.0.1:* ws://localhost:*; frame-src https://inplan.ai http://127.0.0.1:* http://localhost:*"
22
22
  />
23
23
  <title>inplan</title>
24
- <script type="module" crossorigin src="./assets/index-C5EEY2VA.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-CK4CX-zj.js"></script>
25
25
  <link rel="stylesheet" crossorigin href="./assets/index-CD5LIK6f.css">
26
26
  </head>
27
27
  <body>
package/bin/cli.js CHANGED
@@ -1170,6 +1170,23 @@ function clearAuth() {
1170
1170
  const path = authPath();
1171
1171
  if (existsSync5(path)) rmSync2(path, { force: true });
1172
1172
  }
1173
+ async function revokeAndClearAuth() {
1174
+ const auth = loadAuth();
1175
+ let revoked = false;
1176
+ if (auth) {
1177
+ try {
1178
+ const cached = await reuseCached(auth, 0);
1179
+ const session = cached ?? await authedSession();
1180
+ if (session) {
1181
+ const { error } = await session.db.auth.signOut({ scope: "local" });
1182
+ revoked = !error;
1183
+ }
1184
+ } catch {
1185
+ }
1186
+ }
1187
+ clearAuth();
1188
+ return { revoked };
1189
+ }
1173
1190
  var LOCK_WAIT_MS = 1e4;
1174
1191
  var LOCK_STALE_MS = 6e4;
1175
1192
  function lockDir() {
@@ -1443,16 +1460,22 @@ import { dirname as dirname6, join as join7 } from "path";
1443
1460
  import { homedir as homedir4 } from "os";
1444
1461
  import { join as join6 } from "path";
1445
1462
  import { pathToFileURL } from "url";
1463
+ import * as Y from "yjs";
1446
1464
  var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1447
1465
  var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1448
1466
  var hubHttpBase = () => resolveHubUrl().replace(/^ws/, "http").replace(/\/+$/, "");
1449
1467
  var PLUGIN_HTTP = hubHttpBase();
1450
1468
  var defaultCacheDir = () => join6(process.env.INPLAN_HOME || join6(homedir4(), ".inplan"), "plugin-cache");
1451
- var defaultDeps = {
1452
- resolve: resolvePluginOutcome,
1453
- importCli: (p) => import(pathToFileURL(p).href)
1454
- };
1455
- async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1469
+ function shareYjsWithPlugin() {
1470
+ globalThis.__inplanYjs = Y;
1471
+ }
1472
+ function importPluginCli(path) {
1473
+ shareYjsWithPlugin();
1474
+ return import(pathToFileURL(path).href);
1475
+ }
1476
+ var defaultDeps = { resolve: resolvePluginOutcome, importCli: importPluginCli };
1477
+ async function loadPluginGateOutcome(session, options, overrides = {}) {
1478
+ const deps = { ...defaultDeps, ...overrides };
1456
1479
  try {
1457
1480
  const { plugin, reason } = await deps.resolve({
1458
1481
  apiBase: options.apiBase ?? PLUGIN_HTTP,
@@ -1474,7 +1497,7 @@ async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1474
1497
  return { gate: null, reason: "unavailable" };
1475
1498
  }
1476
1499
  }
1477
- async function loadPluginGate(session, options, deps = defaultDeps) {
1500
+ async function loadPluginGate(session, options, deps = {}) {
1478
1501
  try {
1479
1502
  return (await loadPluginGateOutcome(session, options, deps)).gate;
1480
1503
  } catch {
@@ -1997,6 +2020,32 @@ var RemoteDocState = class {
1997
2020
  clearReplayPending() {
1998
2021
  if (existsSync10(this.pendingPath)) rmSync3(this.pendingPath);
1999
2022
  }
2023
+ /** Where a refused working copy with this text is kept (see replaceRefusedCopy). Content-
2024
+ * addressed, so a second, different refusal never overwrites the first, and refusing the same
2025
+ * text twice keeps one file. */
2026
+ refusedPathFor(text) {
2027
+ return `${this.workFile}.refused-${hashBody(text).slice(0, 12)}.md`;
2028
+ }
2029
+ /**
2030
+ * The gate refused the working copy on integrity (#118). The copy is disposable — the document
2031
+ * lives on the hub — but left in place it is validated again on every attach and refused again,
2032
+ * so a stale or broken copy locks the agent out for good. Keep its text aside (the agent may
2033
+ * still want it), then replace the copy with `fresh` canonical and mark it synced, so the next
2034
+ * attach hydrates normally. A pending replay is cleared: what it would have replayed is exactly
2035
+ * the refused text, now kept aside. The proposal record is not touched — it tracks a proposal
2036
+ * already in the cloud, independent of this copy. Order matters: the refused text is written
2037
+ * BEFORE the copy is replaced, so a crash between the two never loses it.
2038
+ * Returns the path the refused text was kept at, or null if there was no copy.
2039
+ */
2040
+ replaceRefusedCopy(fresh) {
2041
+ const refused = this.readWorkFile();
2042
+ const kept = refused !== null ? this.refusedPathFor(refused) : null;
2043
+ if (refused !== null && kept !== null) writeFileSync8(kept, refused);
2044
+ this.writeWorkFile(fresh);
2045
+ this.recordSynced(fresh);
2046
+ this.clearReplayPending();
2047
+ return kept;
2048
+ }
2000
2049
  // ── Proposal record: the durable "did my edit land?" signal (#88) ─────────────────────────────
2001
2050
  /**
2002
2051
  * Park a proposal: publish the record + its exact text as ONE atomic rename, then refresh the
@@ -2235,6 +2284,7 @@ async function withdrawOwnPending(store, _canonicalText, landed) {
2235
2284
  }
2236
2285
 
2237
2286
  // src/gate.ts
2287
+ var integrityKey = (e) => `${e.code}\0${e.commentId ?? ""}\0${e.message}`;
2238
2288
  function evaluateAgentEdit(canonicalText, currentText, confirmed) {
2239
2289
  const current = parse(currentText);
2240
2290
  const canonical = parse(canonicalText);
@@ -2258,8 +2308,9 @@ function evaluateAgentEdit(canonicalText, currentText, confirmed) {
2258
2308
  const dangling = [...deletionGraph.values()].filter((c) => c.parentId !== void 0 && removedSet.has(c.parentId) && !removedSet.has(c.id));
2259
2309
  const danglingIds = new Set(dangling.map((c) => c.id));
2260
2310
  const unconfirmed = [...lost.filter((c) => !confirmed.has(c.id)), ...dangling];
2311
+ const inherited = new Set(checkIntegrity(canonical).errors.map(integrityKey));
2261
2312
  const integrityErrors = checkIntegrity(accepted).errors.filter(
2262
- (e) => e.code !== "span_missing_link" && !(e.code === "missing_parent" && e.commentId !== void 0 && danglingIds.has(e.commentId))
2313
+ (e) => e.code !== "span_missing_link" && !(e.code === "missing_parent" && e.commentId !== void 0 && danglingIds.has(e.commentId)) && !inherited.has(integrityKey(e))
2263
2314
  );
2264
2315
  return {
2265
2316
  integrityOk: integrityErrors.length === 0,
@@ -2381,10 +2432,20 @@ function demoteSource({ hubReadable, fromStore }) {
2381
2432
  if (hubReadable) return { use: "hub" };
2382
2433
  return fromStore ? { use: "store" } : { use: "abort", reason: "hub_unreadable" };
2383
2434
  }
2435
+ async function recoverRefusedCopy(gate, rds) {
2436
+ const fresh = await gate.readCanonical();
2437
+ const refusedCopy = rds.replaceRefusedCopy(fresh);
2438
+ const kept = refusedCopy ? `; the refused text is at ${refusedCopy}` : "";
2439
+ return {
2440
+ workFile: rds.workFile,
2441
+ ...refusedCopy ? { refusedCopy } : {},
2442
+ message: `The working copy was refreshed from the latest canonical${kept}. Re-apply your edit to ${rds.workFile} and re-run.`
2443
+ };
2444
+ }
2384
2445
 
2385
2446
  // src/presence.ts
2386
2447
  import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider";
2387
- import * as Y from "yjs";
2448
+ import * as Y2 from "yjs";
2388
2449
  import WebSocket2 from "ws";
2389
2450
  var COLLAB_URL = resolveHubUrl();
2390
2451
  var AUTH_REPORT_DELAY_MS = 15e3;
@@ -2415,7 +2476,7 @@ function jwtExpMs(token) {
2415
2476
  }
2416
2477
  function announcePresence(docId, token, model) {
2417
2478
  try {
2418
- const ydoc = new Y.Doc();
2479
+ const ydoc = new Y2.Doc();
2419
2480
  const socket = new HocuspocusProviderWebsocket({ url: COLLAB_URL, WebSocketPolyfill: WebSocket2 });
2420
2481
  let reported = false;
2421
2482
  let authCheck;
@@ -2888,7 +2949,7 @@ function resolveBundledApp() {
2888
2949
  }
2889
2950
  function spawnApp(file) {
2890
2951
  const { ELECTRON_RUN_AS_NODE: _runAsNode, ...inherited } = process.env;
2891
- const env = { ...inherited, INPLAN_CLI: process.argv[1] ?? "" };
2952
+ const env = { ...inherited, INPLAN_CLI: process.argv[1] ?? "", ...process.versions.electron ? {} : { INPLAN_NODE: process.execPath } };
2892
2953
  const override = process.env.INPLAN_APP_CMD;
2893
2954
  if (override) {
2894
2955
  const child = spawn3(override, [file], { detached: true, stdio: "ignore", shell: true, env });
@@ -3031,7 +3092,8 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null,
3031
3092
  return "exiting";
3032
3093
  }
3033
3094
  if (!ev.integrityOk) {
3034
- output({ status: "integrity_error", errors: ev.integrityErrors });
3095
+ const recovery = backend.onIntegrityRefused ? await backend.onIntegrityRefused().catch(() => ({})) : {};
3096
+ output({ status: "integrity_error", errors: ev.integrityErrors, ...recovery });
3035
3097
  exitAfterFlush(2);
3036
3098
  return "exiting";
3037
3099
  }
@@ -3790,6 +3852,10 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
3790
3852
  },
3791
3853
  localPendingProposalId: () => rds.pendingProposal()?.id,
3792
3854
  // local file read only — see WaitBackend
3855
+ // A refused working copy must not stay in place: attaching validates it, so it would refuse
3856
+ // every later run too, locking the agent out exactly when the doc needs it (#118). Keep the
3857
+ // refused text beside the copy, refresh the copy from the hub, and say where both are.
3858
+ onIntegrityRefused: () => recoverRefusedCopy(gate, rds),
3793
3859
  ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
3794
3860
  },
3795
3861
  explicitCursor,
@@ -4313,9 +4379,9 @@ function doInstallSkill(args) {
4313
4379
  }
4314
4380
  if (!quiet) output({ status: "ok", installed });
4315
4381
  }
4316
- function doLogout() {
4317
- clearAuth();
4318
- output({ status: "logged_out" });
4382
+ async function doLogout() {
4383
+ const { revoked } = await revokeAndClearAuth();
4384
+ output({ status: "logged_out", revoked });
4319
4385
  }
4320
4386
  async function doUpload(file, args) {
4321
4387
  const s = await authedSession();
@@ -4673,7 +4739,7 @@ async function main() {
4673
4739
  return;
4674
4740
  }
4675
4741
  if (cmd === "logout") {
4676
- doLogout();
4742
+ await doLogout();
4677
4743
  return;
4678
4744
  }
4679
4745
  if (cmd === "launch-editor") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inplan",
3
- "version": "0.3.10",
3
+ "version": "0.3.12",
4
4
  "description": "inplan — a Markdown editor for human ⇄ coding-agent planning. CLI + desktop editor.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "postinstall": "node bin/cli.js install-skill --quiet || true"
26
26
  },
27
27
  "dependencies": {
28
- "electron": "^43.4.1",
28
+ "electron": "^44.12.0",
29
29
  "@hocuspocus/provider": "^2.15.3",
30
30
  "@supabase/supabase-js": "^2.45.0",
31
31
  "ws": "^8.18.0",