longtable 0.1.33 → 0.1.35

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.
package/bin/longtable.mjs CHANGED
@@ -118,6 +118,9 @@ async function connect() {
118
118
  if (!(await codexSignIn(codex))) await leave("The ChatGPT sign-in didn't finish. Press Connect again.");
119
119
  }
120
120
 
121
+ // A connection already running holds the old settings in memory: it is ended first, so the one the start-up task
122
+ // starts now (which never replaces a running one) is this new one.
123
+ try { const old = runningConnection(); if (old && old !== process.pid) endConnection(old); } catch {}
121
124
  const auto = has("no-autostart") ? { started: false } : enableAutostart(process.execPath, binPath);
122
125
  if (!has("no-run") && !auto.started) {
123
126
  // A stand-in until the start-up task runs it: it never ends a connection the task started.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.33",
3
+ "version": "0.1.35",
4
4
  "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
5
  "homepage": "https://longtable.chat",
6
6
  "repository": {
package/src/autostart.mjs CHANGED
@@ -8,10 +8,10 @@
8
8
  // that ran `connect` may itself live somewhere only the app can see.
9
9
 
10
10
  import { spawnSync } from "node:child_process";
11
- import { cpSync, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
12
12
  import { homedir } from "node:os";
13
13
  import { dirname, join, normalize } from "node:path";
14
- import { home } from "./store.mjs";
14
+ import { defaultHome, home } from "./store.mjs";
15
15
 
16
16
  export const TASK = "Longtable connection";
17
17
  const legacyStartup = () => join(process.env.APPDATA || "", "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "Longtable.vbs");
@@ -61,7 +61,9 @@ export function writeStarter(nodePath, binPath) {
61
61
  // Written as UTF-16 with its mark: Windows Script Host reads any other file in the system's old code page, so a
62
62
  // profile folder with letters outside it (an Arabic or accented name) made a path that did not exist, and the
63
63
  // connection never started.
64
- writeFileSync(file, `\ufeffCreateObject("Wscript.Shell").Run """${q(nodePath)}"" ""${q(binPath)}"" run", 0, False\r\n`, "utf16le");
64
+ // "--backup": started by the task (at sign-in, or by the watchdog every few minutes) it only starts a connection
65
+ // when none is running, and never replaces one.
66
+ writeFileSync(file, `\ufeffCreateObject("Wscript.Shell").Run """${q(nodePath)}"" ""${q(binPath)}"" run --backup", 0, False\r\n`, "utf16le");
65
67
  return file;
66
68
  }
67
69
 
@@ -69,9 +71,12 @@ export function registerTask(name, starter) {
69
71
  powershell(
70
72
  "$a = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('\"' + $env:LT_STARTER + '\"'); " +
71
73
  "$t = New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name); " +
74
+ // The watchdog: every five minutes, for as long as the computer is on. A connection that stopped for any
75
+ // reason is running again within five minutes, without waiting for the next sign-in.
76
+ "$w = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 5); " +
72
77
  "$p = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited; " +
73
78
  "$s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable; " +
74
- "Register-ScheduledTask -TaskName $env:LT_TASK -Action $a -Trigger $t -Principal $p -Settings $s -Force | Out-Null",
79
+ "Register-ScheduledTask -TaskName $env:LT_TASK -Action $a -Trigger @($t, $w) -Principal $p -Settings $s -Force | Out-Null",
75
80
  { LT_TASK: name, LT_STARTER: starter },
76
81
  );
77
82
  }
@@ -96,6 +101,7 @@ export function taskExists(name) {
96
101
 
97
102
  // Returns how the connection will start: on Windows the task also starts it now, outside whatever ran `connect`.
98
103
  export function enableAutostart(nodePath, binPath) {
104
+ if (!ownsStartup()) return { started: false, where: "not this computer's start-up entry (a connection in a folder of its own)" };
99
105
  if (process.platform === "win32") {
100
106
  const copy = installCopy(binPath);
101
107
  registerTask(TASK, writeStarter(nodePath, copy));
@@ -136,7 +142,26 @@ export function enableAutostart(nodePath, binPath) {
136
142
  return { started: on.status === 0, where: unitFile() };
137
143
  }
138
144
 
145
+ // The computer's start-up entry is one per person, named the same whatever folder a connection keeps its settings in.
146
+ // Only the connection in the real ~/.longtable may change it: a test's connection in a folder of its own once removed
147
+ // the person's real start-up task every time it disconnected.
148
+ const ownsStartup = () => normalize(home) === normalize(defaultHome);
149
+
150
+ // Every connection keeps its computer's start-up entry as the current version writes it (the watchdog came later):
151
+ // rewritten once per version, quietly, by the connection in the real ~/.longtable.
152
+ export function keepStartupCurrent(nodePath, binPath, version) {
153
+ if (!ownsStartup() || process.platform !== "win32" || !version) return;
154
+ const mark = join(home, "startup-written");
155
+ try { if (readFileSync(mark, "utf8").trim() === version) return; } catch {}
156
+ try {
157
+ if (!taskExists(TASK)) return;
158
+ registerTask(TASK, writeStarter(nodePath, binPath));
159
+ writeFileSync(mark, version);
160
+ } catch (e) { console.error(`keeping the start-up task current failed: ${e.message}`); }
161
+ }
162
+
139
163
  export function disableAutostart() {
164
+ if (!ownsStartup()) return;
140
165
  if (process.platform === "win32") {
141
166
  removeTask(TASK);
142
167
  rmSync(join(home, "start.vbs"), { force: true });
package/src/repo.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
  import { home, log } from "./store.mjs";
7
8
 
8
9
  // Git never stops to ask for a name or password here: if this computer's saved sign-in cannot reach a repository,
@@ -314,10 +315,27 @@ export function realRepo(seat) {
314
315
  try { return existsSync(join(folder, ".git")) ? resolve(folder) : null; } catch { return null; }
315
316
  }
316
317
 
317
- function originDefault(repo) {
318
- try { return tgit(repo, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]); } catch {}
319
- for (const b of ["origin/main", "origin/master"]) { try { tgit(repo, ["rev-parse", "--verify", "--quiet", b]); return b; } catch {} }
320
- return "HEAD";
318
+ // Where the team's code lives is the table's source (what the locked mode reads too), never whatever the person's own
319
+ // repository happens to call origin: that can be somebody else's repository (a client's), which work must never reach.
320
+ // When the source is this very repository, work stays in it as a local branch and nothing is pushed anywhere.
321
+ function sameRepo(source, repo) {
322
+ if (!source) return true;
323
+ let p = String(source);
324
+ if (/^file:/i.test(p)) { try { p = fileURLToPath(p); } catch { return false; } }
325
+ else if (!/^([A-Za-z]:[\\/]|[\\/])/.test(p)) return false;
326
+ const norm = (x) => resolve(x).replace(/[\\/]+$/, "").toLowerCase();
327
+ return norm(p) === norm(repo) || norm(p) === norm(join(repo, ".git"));
328
+ }
329
+
330
+ // The tip of a branch (or of the source's default branch) at the source, fetched under a private name of the
331
+ // connection's and read back as a commit: nothing of the person's own refs or remotes changes.
332
+ function sourceTip(repo, url, ref) {
333
+ const tmp = `refs/longtable-src/tip-${process.pid}-${Date.now()}`;
334
+ try {
335
+ tgit(repo, ["fetch", "--quiet", "--no-tags", url, `+${ref}:${tmp}`]);
336
+ return tgit(repo, ["rev-parse", tmp]);
337
+ } catch { return null; }
338
+ finally { try { tgit(repo, ["update-ref", "-d", tmp]); } catch {} }
321
339
  }
322
340
 
323
341
  // Only files git ignores are copied, as Claude Code does: something tracked is already in the worktree, and something
@@ -347,26 +365,35 @@ export function openTree(seat, branch, { doing = false, job = "read" } = {}) {
347
365
  const repo = realRepo(seat) || join(home, "copies", table);
348
366
  const dir = doing ? join(home, "trees", table, `work-${branch.slice("longtable/".length)}`)
349
367
  : join(home, "trees", table, `read-${String(job).replace(/[^A-Za-z0-9-]/g, "").slice(0, 36) || "job"}`);
350
- try { tgit(repo, ["fetch", "--quiet", "origin"]); } catch (e) { log(`fetch before a worktree failed: ${String(e.message).split(/\r?\n/)[0]}`); }
368
+ // The table's code: this repository itself, or the address the table reads from (never "origin" by name).
369
+ const local = sameRepo(seat.source, repo);
370
+ const url = local ? null : seat.source;
351
371
  let onRemote = false;
352
- if (branch) { try { tgit(repo, ["rev-parse", "--verify", "--quiet", `origin/${branch}`]); onRemote = true; } catch {} }
353
- const base = onRemote ? `origin/${branch}` : originDefault(repo);
372
+ let base = null;
373
+ if (local) {
374
+ if (branch) { try { base = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); onRemote = true; } catch {} }
375
+ base ??= tgit(repo, ["rev-parse", "HEAD"]);
376
+ } else {
377
+ if (branch) { base = sourceTip(repo, url, `refs/heads/${branch}`); onRemote = !!base; }
378
+ base ??= sourceTip(repo, url, "HEAD");
379
+ if (!base) throw new Error("the project's code could not be fetched from where the table reads it");
380
+ }
354
381
  const fresh = !existsSync(join(dir, ".git"));
355
382
  if (fresh) {
356
383
  mkdirSync(join(home, "trees", table), { recursive: true });
357
384
  // A worktree of ours whose folder is gone is let go by name; the person's own worktrees are never touched.
358
385
  try { tgit(repo, ["worktree", "remove", "--force", dir]); } catch {}
359
- if (doing) {
386
+ if (doing && !local) {
360
387
  // Their own local branch of the same name is never reset over work that is not on the server.
361
- let local = null;
362
- try { local = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); } catch {}
363
- if (local) {
364
- try { tgit(repo, ["merge-base", "--is-ancestor", local, base]); }
388
+ let mine = null;
389
+ try { mine = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); } catch {}
390
+ if (mine) {
391
+ try { tgit(repo, ["merge-base", "--is-ancestor", mine, base]); }
365
392
  catch { throw new Error(`a branch named ${branch} on this computer has work that is not on the server, so it was left as it is`); }
366
393
  }
367
394
  }
368
395
  tgit(repo, ["worktree", "add", "--quiet", ...(doing ? ["-B", branch, dir, base] : ["--detach", dir, base])]);
369
- } else if (doing && onRemote) {
396
+ } else if (doing && onRemote && !local) {
370
397
  // Work picked up again starts from what is on the server (another AI's part may have landed there since), unless
371
398
  // this computer holds commits the server does not have yet.
372
399
  try { tgit(dir, ["merge-base", "--is-ancestor", "HEAD", base]); tgit(dir, ["reset", "--quiet", "--hard", base]); } catch {}
@@ -380,7 +407,7 @@ export function openTree(seat, branch, { doing = false, job = "read" } = {}) {
380
407
  const NL = String.fromCharCode(10);
381
408
  if (!now.split(/\r?\n/).includes(".longtable-yours/")) writeFileSync(exclude, `${now}${now && !now.endsWith(NL) ? NL : ""}.longtable-yours/${NL}`);
382
409
  if (fresh && realRepo(seat)) copyIncluded(repo, dir);
383
- return { dir, repo, base: tgit(dir, ["rev-parse", "HEAD"]), continued: onRemote, tree: true };
410
+ return { dir, repo, url, base: tgit(dir, ["rev-parse", "HEAD"]), continued: onRemote, tree: true };
384
411
  }
385
412
 
386
413
  // What changed in the worktree since it was opened, committed or not.
@@ -410,13 +437,15 @@ export function landTree(tree, branch, message, who) {
410
437
  const commit = land(["rev-parse", "--short", "HEAD"]);
411
438
  let pushed = false;
412
439
  let landed = branch;
413
- const push = (to) => land(["push", "--quiet", "--no-verify", "origin", `HEAD:refs/heads/${to}`]);
440
+ // Work on the table's own repository is already on its branch there: nothing is pushed anywhere.
441
+ if (!tree.url) return { files, commit, branch, pushed: true, apart: false };
442
+ const push = (to) => land(["push", "--quiet", "--no-verify", tree.url, `HEAD:refs/heads/${to}`]);
414
443
  try { push(branch); pushed = true; } catch (e) {
415
444
  log(`push of ${branch} failed: ${String(e.message).split(/\r?\n/)[0]}`);
416
445
  // Another part landed on the branch first (two people's work on one task): put the two together and try again;
417
446
  // when they touch the same lines, this part goes on a branch of its own beside it, as the other work does.
418
447
  try {
419
- land(["fetch", "--quiet", "origin", branch]);
448
+ land(["fetch", "--quiet", "--no-tags", tree.url, `refs/heads/${branch}`]);
420
449
  land(["merge", "--quiet", "--no-edit", "--no-verify", "FETCH_HEAD"]);
421
450
  push(branch);
422
451
  pushed = true;
package/src/run.mjs CHANGED
@@ -5,7 +5,8 @@
5
5
 
6
6
  import { layPointed, pointedPaths, pointedSystem } from "./pointed.mjs";
7
7
  import { PAGE, PAGE_KINDS, PAGE_SYSTEM, pageOut, pagesPrompt } from "./pages.mjs";
8
- import { newer, ownVersion, restartOnNew, updateTo } from "./update.mjs";
8
+ import { newer, ownDir, ownVersion, restartOnNew, updateTo } from "./update.mjs";
9
+ import { keepStartupCurrent } from "./autostart.mjs";
9
10
  import { attachedPrompt, commandPrompt, fetchAttachments, loadCommand, materialsPrompt, scanCommands, shareable } from "./extras.mjs";
10
11
  import { spawnSync } from "node:child_process";
11
12
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -1079,6 +1080,12 @@ export async function runLoop({ pollMs = 2000, backup = false } = {}) {
1079
1080
  writeFileSync(lock, `${process.pid} ${Date.now()}`);
1080
1081
  const unlock = () => { try { if (runningConnection() === process.pid) rmSync(lock, { force: true }); } catch {} };
1081
1082
  process.on("exit", () => { stopAll(); unlock(); });
1083
+ // Something nobody foresaw (a timer, a stream, a promise nobody waited on) is written down and the connection keeps
1084
+ // running: a connection that quietly stops is worse than one that logged a fault and carried on.
1085
+ process.on("uncaughtException", (e) => log(`tripwire: uncaught ${e?.stack?.split(String.fromCharCode(10)).slice(0, 3).join(" | ") || e}`));
1086
+ process.on("unhandledRejection", (e) => log(`tripwire: unhandled ${e?.stack?.split(String.fromCharCode(10)).slice(0, 3).join(" | ") || e}`));
1087
+ // The computer's start-up entry as this version writes it (with its watchdog), once per version.
1088
+ try { keepStartupCurrent(process.execPath, join(ownDir(), "bin", "longtable.mjs"), ownVersion()); } catch (e) { log(`start-up entry not refreshed: ${e.message}`); }
1082
1089
  for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(sig, () => { stopAll(); unlock(); process.exit(0); });
1083
1090
  // Starting with no network yet (right after sign-in) is normal: keep trying. A table that took this connection
1084
1091
  // off is skipped, and the others carry on.