tring-chat 0.1.12 → 0.1.13

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/README.md CHANGED
@@ -267,9 +267,18 @@ Browsers reserve `Ctrl+1`–`Ctrl+8` for tab switching, so `Shift+digit` is the
267
267
  fallback that always works in an ordinary tab. Clicking a thumbnail also focuses it,
268
268
  and right-clicking one opens the same dialog `r` does.
269
269
 
270
+ Those are picker keys. Everything else you type goes to the focused session, with one
271
+ exception: **`Ctrl+Enter` and `Shift+Enter` insert a newline** instead of submitting.
272
+ A terminal has no modifier bits for Enter — every variant is a bare `\r` on the wire —
273
+ so tring sends `ESC`+`CR` for those two chords, which is what Claude Code and other
274
+ agent CLIs read as "break the line". Native terminals need `/terminal-setup` to do the
275
+ same thing; here it works out of the box.
276
+
270
277
  ## Naming and colouring tiles
271
278
 
272
279
  Right-click a tile — or press `r` in the picker — to give it a name and a colour.
280
+ The same dialog has a **Delete** button, which kills the session and frees the slot
281
+ back to empty; `x` in the picker does the same thing.
273
282
 
274
283
  The colour is a ring *outside* the status border, never instead of it, so a tile you
275
284
  have tinted still reports whether it is busy, finished or dead. Twenty-four choices:
@@ -409,9 +418,9 @@ Two things are deliberate:
409
418
  Auto-executing whatever was there last time is how four dev servers end up fighting
410
419
  over a port.
411
420
 
412
- ## Dropping images on a terminal
421
+ ## Dropping files on a terminal
413
422
 
414
- Drag a screenshot onto the centre terminal and its path is typed into the prompt,
423
+ Drag a screenshot, a spreadsheet or any other file onto the centre terminal and its path is typed into the prompt,
415
424
  the way dropping a file on any other terminal types one. Claude Code reads the
416
425
  path from there.
417
426
 
@@ -421,10 +430,12 @@ the wrong machine's anyway whenever you have the deck open on a phone or a lapto
421
430
  across the room. So the bytes go to the daemon, which writes them down on the
422
431
  machine the shell is actually running on and answers with the path it chose.
423
432
 
424
- - PNG, JPEG, GIF and WebP, up to 10MB. The type is read from the file's first
425
- bytes, not from what the browser called it.
426
- - The daemon names every file itself, under `~/.config/tring/uploads`. Nothing
427
- a client sends reaches a filesystem path.
433
+ - Any file up to 10MB. An image (PNG, JPEG, GIF, WebP) is named by its first
434
+ bytes, not by what the browser called it; anything else keeps its own name,
435
+ cut down to letters, digits, `.`, `-` and `_`, so Claude can tell a `.xlsx`
436
+ from a `.csv`.
437
+ - Every file lands under `~/.config/tring/uploads` behind a random prefix, so
438
+ no name a client sends can point anywhere else.
428
439
  - The last 20 are kept. The directory is emptied when the daemon stops.
429
440
  - The upload goes through the same token as the rest of the API.
430
441
 
package/dist/tring.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createServer as createSecureServer } from "node:https";
7
- import path8 from "node:path";
7
+ import path9 from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { WebSocketServer } from "ws";
10
10
 
@@ -436,7 +436,7 @@ function snapshot(term) {
436
436
  const line = buf.getLine(buf.viewportY + y);
437
437
  const out = [];
438
438
  if (line) {
439
- let run = null;
439
+ let run2 = null;
440
440
  for (let x = 0; x < term.cols; x++) {
441
441
  const cell = line.getCell(x);
442
442
  if (!cell) break;
@@ -445,11 +445,11 @@ function snapshot(term) {
445
445
  const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
446
446
  const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
447
447
  const bold = cell.isBold() !== 0;
448
- if (run && run.fg === fg && run.bg === bg && run.bold === bold) {
449
- run.text += text2;
448
+ if (run2 && run2.fg === fg && run2.bg === bg && run2.bold === bold) {
449
+ run2.text += text2;
450
450
  } else {
451
- run = { text: text2, fg, bg, bold };
452
- out.push(run);
451
+ run2 = { text: text2, fg, bg, bold };
452
+ out.push(run2);
453
453
  }
454
454
  }
455
455
  while (out.length > 0) {
@@ -1068,7 +1068,7 @@ var ProjectManager = class _ProjectManager {
1068
1068
  import { createReadStream } from "node:fs";
1069
1069
  import { readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
1070
1070
  import os4 from "node:os";
1071
- import path6 from "node:path";
1071
+ import path7 from "node:path";
1072
1072
 
1073
1073
  // src/security.ts
1074
1074
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -1290,7 +1290,7 @@ function parseLimits(text2) {
1290
1290
  }
1291
1291
  function readLimits(timeoutMs = 3e4) {
1292
1292
  const args = ["-p", "/usage", "--output-format", "json"];
1293
- const run = (cmd) => new Promise((resolve, reject) => {
1293
+ const run2 = (cmd) => new Promise((resolve, reject) => {
1294
1294
  const child = spawn2(cmd, args, { stdio: ["ignore", "pipe", "ignore"] });
1295
1295
  let out = "";
1296
1296
  let settled = false;
@@ -1320,8 +1320,8 @@ function readLimits(timeoutMs = 3e4) {
1320
1320
  }, 50);
1321
1321
  });
1322
1322
  });
1323
- return run("claude").catch(
1324
- (err) => process.platform === "win32" && err.code === "ENOENT" ? run("claude.cmd") : Promise.reject(err)
1323
+ return run2("claude").catch(
1324
+ (err) => process.platform === "win32" && err.code === "ENOENT" ? run2("claude.cmd") : Promise.reject(err)
1325
1325
  );
1326
1326
  }
1327
1327
  async function collectUsage(dir, now) {
@@ -1356,22 +1356,25 @@ function sniffImage(bytes) {
1356
1356
  if (at(0, [82, 73, 70, 70]) && at(8, [87, 69, 66, 80])) return ".webp";
1357
1357
  return null;
1358
1358
  }
1359
- var NotAnImage = class extends Error {
1360
- constructor() {
1361
- super("only PNG, JPEG, GIF and WebP images can be dropped on a terminal");
1362
- }
1363
- };
1364
1359
  var UploadStore = class {
1365
1360
  constructor(dir, keep = KEEP) {
1366
1361
  this.dir = dir;
1367
1362
  this.keep = keep;
1368
1363
  }
1369
- /** Writes the bytes and returns the absolute path to type into the prompt. */
1370
- async save(bytes) {
1364
+ /**
1365
+ * Writes the bytes and returns the absolute path to type into the prompt.
1366
+ *
1367
+ * An image is named by its bytes. Anything else — a spreadsheet, a PDF, a
1368
+ * log — keeps its own name, since that is how Claude tells a .xlsx from a
1369
+ * .csv, cut down to word characters, dots and dashes: no separator survives,
1370
+ * so the random prefix always stays the first segment and traversal has
1371
+ * nothing to work with.
1372
+ */
1373
+ async save(bytes, name = "") {
1371
1374
  const ext = sniffImage(bytes);
1372
- if (!ext) throw new NotAnImage();
1375
+ const tail = ext ?? "-" + (name.replace(/[^\w.-]+/g, "_").slice(-80) || "file");
1373
1376
  await mkdir3(this.dir, { recursive: true, mode: 448 });
1374
- const file = path5.join(this.dir, randomBytes2(8).toString("hex") + ext);
1377
+ const file = path5.join(this.dir, randomBytes2(8).toString("hex") + tail);
1375
1378
  await writeFile3(file, bytes, { mode: 384 });
1376
1379
  await this.prune();
1377
1380
  return file;
@@ -1400,6 +1403,134 @@ var UploadStore = class {
1400
1403
  }
1401
1404
  };
1402
1405
 
1406
+ // src/git-diff.ts
1407
+ import { execFile } from "node:child_process";
1408
+ import { lstat, readFile as readFile4 } from "node:fs/promises";
1409
+ import path6 from "node:path";
1410
+ import { promisify } from "node:util";
1411
+ var run = promisify(execFile);
1412
+ var MAX_PATCH_BYTES = 1 << 20;
1413
+ var EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
1414
+ var SAFE = ["-c", "core.fsmonitor=false", "-c", "core.quotePath=false"];
1415
+ async function git(cwd, args) {
1416
+ const { stdout } = await run("git", [...SAFE, ...args], {
1417
+ cwd,
1418
+ encoding: "utf8",
1419
+ maxBuffer: 64 << 20
1420
+ });
1421
+ return stdout;
1422
+ }
1423
+ async function filtersOff(root) {
1424
+ const keys = await git(root, ["config", "--name-only", "--get-regexp", "^filter\\."]).catch(() => "");
1425
+ const drivers = new Set(keys.split("\n").filter(Boolean).map((k) => k.slice(0, k.lastIndexOf("."))));
1426
+ return [...drivers].flatMap((d) => [
1427
+ "-c",
1428
+ `${d}.clean=`,
1429
+ "-c",
1430
+ `${d}.smudge=`,
1431
+ "-c",
1432
+ `${d}.process=`,
1433
+ "-c",
1434
+ `${d}.required=false`
1435
+ ]);
1436
+ }
1437
+ var pathOf = (line) => line.slice(6).replace(/\t$/, "");
1438
+ function splitPatch(text2) {
1439
+ const out = [];
1440
+ for (const chunk of text2.split(/^(?=diff --git )/m)) {
1441
+ if (!chunk.startsWith("diff --git ")) continue;
1442
+ const lines = chunk.replace(/\n$/, "").split("\n");
1443
+ const plus = lines.find((l) => l.startsWith("+++ "));
1444
+ const minus = lines.find((l) => l.startsWith("--- "));
1445
+ const header = /^diff --git a\/(.*) b\/(.*)$/.exec(lines[0]);
1446
+ const file = plus && plus !== "+++ /dev/null" ? pathOf(plus) : minus && minus !== "--- /dev/null" ? pathOf(minus) : header?.[2] ?? lines[0];
1447
+ if (lines.some((l) => l.startsWith("Binary files "))) {
1448
+ out.push({ path: file, added: 0, removed: 0, patch: "", note: "binary" });
1449
+ continue;
1450
+ }
1451
+ const start = lines.findIndex((l) => l.startsWith("@@"));
1452
+ const hunks = start < 0 ? [] : lines.slice(start);
1453
+ let added = 0;
1454
+ let removed = 0;
1455
+ for (const l of hunks) {
1456
+ if (l.startsWith("+")) added++;
1457
+ else if (l.startsWith("-")) removed++;
1458
+ }
1459
+ out.push({ path: file, added, removed, patch: hunks.join("\n") });
1460
+ }
1461
+ return out;
1462
+ }
1463
+ async function untracked(root, rel, budget) {
1464
+ const full = path6.join(root, rel);
1465
+ let bytes;
1466
+ try {
1467
+ const st = await lstat(full);
1468
+ if (!st.isFile()) return { path: rel, added: 0, removed: 0, patch: "", note: "not a regular file" };
1469
+ if (st.size > budget) return { path: rel, added: 0, removed: 0, patch: "", note: "too large" };
1470
+ bytes = await readFile4(full);
1471
+ } catch (err) {
1472
+ if (err.code === "ENOENT") return null;
1473
+ return { path: rel, added: 0, removed: 0, patch: "", note: "unreadable" };
1474
+ }
1475
+ if (bytes.length === 0) return { path: rel, added: 0, removed: 0, patch: "" };
1476
+ if (bytes.subarray(0, 8e3).includes(0)) return { path: rel, added: 0, removed: 0, patch: "", note: "binary" };
1477
+ const lines = bytes.toString("utf8").replace(/\n$/, "").split("\n");
1478
+ return {
1479
+ path: rel,
1480
+ added: lines.length,
1481
+ removed: 0,
1482
+ patch: [`@@ -0,0 +1,${lines.length} @@`, ...lines.map((l) => `+${l}`)].join("\n")
1483
+ };
1484
+ }
1485
+ async function gitDiff(cwd) {
1486
+ let root;
1487
+ try {
1488
+ root = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
1489
+ } catch {
1490
+ return { cwd, error: "not a git repository" };
1491
+ }
1492
+ try {
1493
+ const base2 = await git(root, ["rev-parse", "--verify", "-q", "HEAD"]).then(() => "HEAD", () => EMPTY_TREE);
1494
+ const tracked = splitPatch(await git(root, [
1495
+ ...await filtersOff(root),
1496
+ "diff",
1497
+ base2,
1498
+ "--no-ext-diff",
1499
+ "--no-textconv",
1500
+ "--no-color",
1501
+ "--no-renames",
1502
+ // Whatever diff.noprefix / diff.mnemonicPrefix the user has set.
1503
+ "--src-prefix=a/",
1504
+ "--dst-prefix=b/"
1505
+ ]));
1506
+ const names = (await git(root, ["ls-files", "--others", "--exclude-standard", "-z"])).split("\0").filter(Boolean).sort();
1507
+ const loose = [];
1508
+ let readBudget = MAX_PATCH_BYTES;
1509
+ for (const n of names) {
1510
+ const f = await untracked(root, n, readBudget);
1511
+ if (!f) continue;
1512
+ readBudget = Math.max(0, readBudget - Buffer.byteLength(f.patch));
1513
+ loose.push(f);
1514
+ }
1515
+ const files = [...tracked, ...loose].sort((a, b) => a.path.localeCompare(b.path));
1516
+ let budget = MAX_PATCH_BYTES;
1517
+ let truncated = files.some((f) => f.note === "too large");
1518
+ for (const f of files) {
1519
+ const size = Buffer.byteLength(f.patch);
1520
+ if (size <= budget) {
1521
+ budget -= size;
1522
+ continue;
1523
+ }
1524
+ f.patch = "";
1525
+ f.note = "too large";
1526
+ truncated = true;
1527
+ }
1528
+ return { cwd, files, truncated };
1529
+ } catch (err) {
1530
+ return { cwd, error: `cannot read the changes: ${err.message.split("\n")[0]}` };
1531
+ }
1532
+ }
1533
+
1403
1534
  // src/http.ts
1404
1535
  var MIME = {
1405
1536
  ".html": "text/html; charset=utf-8",
@@ -1472,14 +1603,14 @@ function createHandler(opts) {
1472
1603
  let usage = null;
1473
1604
  const homeDir = () => process.env["HOME"] ?? os4.homedir();
1474
1605
  const within = (root, dir) => {
1475
- const rel = path6.relative(path6.resolve(root), dir);
1476
- return rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel);
1606
+ const rel = path7.relative(path7.resolve(root), dir);
1607
+ return rel === "" || !rel.startsWith("..") && !path7.isAbsolute(rel);
1477
1608
  };
1478
1609
  const real = async (p) => {
1479
1610
  try {
1480
1611
  return await realpath(p);
1481
1612
  } catch {
1482
- return path6.resolve(p);
1613
+ return path7.resolve(p);
1483
1614
  }
1484
1615
  };
1485
1616
  const browsable = async (dir) => {
@@ -1523,14 +1654,20 @@ function createHandler(opts) {
1523
1654
  else return json(res, 400, { error: 'status must be "busy" or "done"' });
1524
1655
  return json(res, 200, { ok: true });
1525
1656
  }
1657
+ const diff = url.pathname.match(/^\/api\/sessions\/([^/]+)\/diff$/);
1658
+ if (diff && req.method === "GET") {
1659
+ const s = pm.findSession(decodeURIComponent(diff[1]));
1660
+ if (!s) return json(res, 404, { error: "no such session" });
1661
+ return json(res, 200, await gitDiff(s.cwd));
1662
+ }
1526
1663
  if (url.pathname === "/api/fs" && req.method === "GET") {
1527
1664
  const raw = url.searchParams.get("path")?.trim();
1528
- const dir = raw ? path6.resolve(raw) : homeDir();
1665
+ const dir = raw ? path7.resolve(raw) : homeDir();
1529
1666
  if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
1530
1667
  try {
1531
1668
  const found = await readdir3(dir, { withFileTypes: true });
1532
- const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path6.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
1533
- const parent = path6.dirname(dir);
1669
+ const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path7.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
1670
+ const parent = path7.dirname(dir);
1534
1671
  const up = parent !== dir && await browsable(parent) ? parent : null;
1535
1672
  return json(res, 200, { path: dir, parent: up, entries });
1536
1673
  } catch {
@@ -1554,18 +1691,17 @@ function createHandler(opts) {
1554
1691
  if (!store) return json(res, 503, { error: "uploads are not configured" });
1555
1692
  const declared = Number(req.headers["content-length"] ?? "0");
1556
1693
  if (declared > MAX_UPLOAD_BYTES) {
1557
- return json(res, 413, { error: `images are limited to ${MAX_UPLOAD_BYTES >> 20}MB` });
1694
+ return json(res, 413, { error: `uploads are limited to ${MAX_UPLOAD_BYTES >> 20}MB` });
1558
1695
  }
1559
1696
  const bytes = await readBytes(req, MAX_UPLOAD_BYTES);
1560
1697
  if (bytes === null) {
1561
- return tooLarge(req, res, `images are limited to ${MAX_UPLOAD_BYTES >> 20}MB`);
1698
+ return tooLarge(req, res, `uploads are limited to ${MAX_UPLOAD_BYTES >> 20}MB`);
1562
1699
  }
1563
1700
  if (bytes.length === 0) return json(res, 400, { error: "empty upload" });
1564
1701
  try {
1565
- return json(res, 200, { path: await store.save(bytes) });
1566
- } catch (err) {
1567
- if (err instanceof NotAnImage) return json(res, 415, { error: err.message });
1568
- return json(res, 500, { error: "cannot write the dropped image" });
1702
+ return json(res, 200, { path: await store.save(bytes, url.searchParams.get("name") ?? "") });
1703
+ } catch {
1704
+ return json(res, 500, { error: "cannot write the dropped file" });
1569
1705
  }
1570
1706
  }
1571
1707
  if (url.pathname === "/api/sessions" && req.method === "GET") {
@@ -1578,15 +1714,15 @@ function createHandler(opts) {
1578
1714
  }
1579
1715
  async function serveStatic(res, pathname) {
1580
1716
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
1581
- const file = path6.resolve(webRoot, rel);
1582
- if (file !== webRoot && !file.startsWith(webRoot + path6.sep)) {
1717
+ const file = path7.resolve(webRoot, rel);
1718
+ if (file !== webRoot && !file.startsWith(webRoot + path7.sep)) {
1583
1719
  text(res, 403, "forbidden");
1584
1720
  return;
1585
1721
  }
1586
1722
  try {
1587
1723
  const info = await stat3(file);
1588
1724
  if (!info.isFile()) throw new Error("not a file");
1589
- head(res, 200, MIME[path6.extname(file)] ?? "application/octet-stream");
1725
+ head(res, 200, MIME[path7.extname(file)] ?? "application/octet-stream");
1590
1726
  createReadStream(file).pipe(res);
1591
1727
  } catch {
1592
1728
  if (rel === "index.html") {
@@ -1926,25 +2062,25 @@ import {
1926
2062
  readdirSync
1927
2063
  } from "node:fs";
1928
2064
  import { createRequire as createRequire3 } from "node:module";
1929
- import path7 from "node:path";
2065
+ import path8 from "node:path";
1930
2066
  var EXEC = 73;
1931
2067
  function nodePtyRoot() {
1932
2068
  try {
1933
- return path7.dirname(createRequire3(import.meta.url).resolve("node-pty/package.json"));
2069
+ return path8.dirname(createRequire3(import.meta.url).resolve("node-pty/package.json"));
1934
2070
  } catch {
1935
2071
  return null;
1936
2072
  }
1937
2073
  }
1938
2074
  function spawnHelperPaths(root) {
1939
- const found = [path7.join(root, "build", "Release", "spawn-helper")];
2075
+ const found = [path8.join(root, "build", "Release", "spawn-helper")];
1940
2076
  let prebuilds;
1941
2077
  try {
1942
- prebuilds = readdirSync(path7.join(root, "prebuilds"), { withFileTypes: true });
2078
+ prebuilds = readdirSync(path8.join(root, "prebuilds"), { withFileTypes: true });
1943
2079
  } catch {
1944
2080
  return found;
1945
2081
  }
1946
2082
  for (const entry of prebuilds) {
1947
- if (entry.isDirectory()) found.push(path7.join(root, "prebuilds", entry.name, "spawn-helper"));
2083
+ if (entry.isDirectory()) found.push(path8.join(root, "prebuilds", entry.name, "spawn-helper"));
1948
2084
  }
1949
2085
  return found;
1950
2086
  }
@@ -2007,11 +2143,11 @@ async function main() {
2007
2143
  const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
2008
2144
  const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
2009
2145
  const cleartextOffBox = !tls && !isLoopbackBind(args.host);
2010
- const here = path8.dirname(fileURLToPath(import.meta.url));
2146
+ const here = path9.dirname(fileURLToPath(import.meta.url));
2011
2147
  const webRoot = [
2012
- path8.resolve(here, "web"),
2013
- path8.resolve(here, "../../web/dist")
2014
- ].find((p) => existsSync2(p)) ?? path8.resolve(here, "web");
2148
+ path9.resolve(here, "web"),
2149
+ path9.resolve(here, "../../web/dist")
2150
+ ].find((p) => existsSync2(p)) ?? path9.resolve(here, "web");
2015
2151
  for (const file of fixSpawnHelper()) console.log(`made ${file} executable`);
2016
2152
  const pm = await ProjectManager.open({
2017
2153
  url,
@@ -2023,7 +2159,7 @@ async function main() {
2023
2159
  ...args.shell ? { shell: args.shell } : {}
2024
2160
  });
2025
2161
  const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
2026
- const uploads = new UploadStore(path8.join(path8.dirname(pm.statePath), "uploads"));
2162
+ const uploads = new UploadStore(path9.join(path9.dirname(pm.statePath), "uploads"));
2027
2163
  const handle = createHandler({
2028
2164
  pm,
2029
2165
  webRoot,
@@ -2052,7 +2188,7 @@ async function main() {
2052
2188
  console.warn(`warning: ${url} is plain http \u2014 the token, every keystroke and all terminal output cross the network in clear. Use an encrypted overlay (Tailscale, WireGuard) or pass --tls-cert/--tls-key.`);
2053
2189
  }
2054
2190
  if (args.updateCheck) {
2055
- void checkForUpdate(path8.join(path8.dirname(pm.statePath), "update-check.json")).then((latest) => {
2191
+ void checkForUpdate(path9.join(path9.dirname(pm.statePath), "update-check.json")).then((latest) => {
2056
2192
  if (!latest) return;
2057
2193
  hub.setUpdate({ current: currentVersion(), latest });
2058
2194
  console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);