Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

14.0 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// What the Deck's Agents, Usage and Build widgets show (shared/deck-model.js widget agents|quota|build):
//   agents()  the coding agents' sessions on this computer, from their own session logs: Claude Code
//             (~/.claude/projects/<project>/<session>.jsonl, or $CLAUDE_CONFIG_DIR) and Codex
//             (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl, or $CODEX_HOME). Files are only read:
//             no process is started, nothing is sent anywhere but to the paired device.
//             → {sessions: [{tool, project, branch, title, state, ago}], usage: [{tool, label, used, left, limited}]}
//             state: 'working' (a turn is running), 'waiting' (the agent answered, your turn), 'idle'
//             (a turn that stopped moving 10 minutes ago). ago, left: ms before and after now.
//             Claude Code's usage: its five-hour window, counted from the first message of the window
//             as Claude Code counts it, and the reset time it gives when its limit is reached. Codex's:
//             the used share and resets its logs report.
//   build(repo, branch, token)  a GitHub repository's latest workflow runs (api.github.com; the token,
//             kept sealed on this computer, only for private repositories)
//             → {repo, branch, name, title, status, conclusion, ago, url, runs: [conclusion|status]}
// Both cache: the device asks every few seconds, the logs are read again only when they change and
// GitHub at most every 90 s (30 s with a token, which has a higher limit).
'use strict';

const fs = require('fs');
const path = require('path');
const os = require('os');

const RECENT_MS = 6 * 3600e3; // sessions touched in the last six hours
const STALL_MS = 10 * 60e3; // a running turn quiet this long: idle
const WINDOW_MS = 5 * 3600e3; // Claude Code's usage window
const TAIL = 192 * 1024; // the end of a log, where its state is
const MAX_SESSIONS = 12;

const claudeDir = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
const codexDir = () => path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'sessions');

// The last bytes of a file, as whole lines.
async function tail(file, size, bytes = TAIL) {
  const fh = await fs.promises.open(file, 'r');
  try {
    const n = Math.min(size, bytes);
    const b = Buffer.alloc(n);
    await fh.read(b, 0, n, size - n);
    let s = b.toString('utf8');
    if (n < size) s = s.slice(s.indexOf('\n') + 1);
    return s.split('\n');
  } finally { await fh.close(); }
}
async function head(file, bytes = 16 * 1024) {
  const fh = await fs.promises.open(file, 'r');
  try {
    const b = Buffer.alloc(bytes);
    const { bytesRead } = await fh.read(b, 0, bytes, 0);
    return b.subarray(0, bytesRead).toString('utf8').split('\n');
  } finally { await fh.close(); }
}
const json = (l) => { if (!l || l[0] !== '{') return null; try { return JSON.parse(l); } catch (_) { return null; } };
const ts = (v) => { const t = Date.parse(v); return Number.isFinite(t) ? t : 0; };
const short = (v, n = 80) => String(v || '').replace(/\s+/g, ' ').trim().slice(0, n);

async function ls(dir) { try { return await fs.promises.readdir(dir, { withFileTypes: true }); } catch (_) { return []; } }
async function stat(f) { try { return await fs.promises.stat(f); } catch (_) { return null; } }

// The session logs changed in the last `ms`: [{file, mtime, size}], newest first.
async function claudeFiles(ms) {
  const out = [];
  const now = Date.now();
  for (const d of await ls(claudeDir())) {
    if (!d.isDirectory()) continue;
    const dir = path.join(claudeDir(), d.name);
    for (const f of await ls(dir)) {
      if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
      const file = path.join(dir, f.name);
      const st = await stat(file);
      if (st && now - st.mtimeMs < ms) out.push({ file, mtime: st.mtimeMs, size: st.size });
    }
  }
  return out.sort((a, b) => b.mtime - a.mtime);
}
async function codexFiles(ms) {
  const out = [];
  const now = Date.now();
  const pad = (n) => String(n).padStart(2, '0');
  for (let back = 0; back <= Math.ceil(ms / 86400e3); back++) {
    const d = new Date(now - back * 86400e3);
    const dir = path.join(codexDir(), String(d.getFullYear()), pad(d.getMonth() + 1), pad(d.getDate()));
    for (const f of await ls(dir)) {
      if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
      const file = path.join(dir, f.name);
      const st = await stat(file);
      if (st && now - st.mtimeMs < ms) out.push({ file, mtime: st.mtimeMs, size: st.size });
    }
  }
  return out.sort((a, b) => b.mtime - a.mtime);
}

// One Claude Code session from the end of its log.
function claudeSession(lines, mtime) {
  let cwd = '', branch = '', title = '', prompt = '', last = null, limit = null;
  for (const l of lines) {
    const e = json(l);
    if (!e) continue;
    if (e.cwd) cwd = e.cwd;
    if (e.gitBranch) branch = e.gitBranch;
    if (e.type === 'summary' && e.summary) title = e.summary;
    if (e.type === 'custom-title' && e.customTitle) title = e.customTitle;
    if (e.type !== 'user' && e.type !== 'assistant') continue;
    if (e.isMeta) continue;
    last = e;
    const c = e.message && e.message.content;
    if (e.type === 'user' && !e.isSidechain) {
      const text = typeof c === 'string' ? c : Array.isArray(c) ? (c.find((x) => x && x.type === 'text') || {}).text : '';
      if (text && !/^\s*</.test(text) && !/^This session is being continued/.test(text)) prompt = text;
    }
    if (e.type === 'assistant' && Array.isArray(c)) {
      for (const x of c) {
        const m = x && x.type === 'text' && /usage limit|limit reached/i.test(x.text || '') ? x.text : '';
        if (!m) continue;
        const at = /\|(\d{10})\b/.exec(m);
        limit = { at: ts(e.timestamp), resets: at ? Number(at[1]) * 1000 : 0 };
      }
    }
  }
  if (!last) return null;
  const c = last.message && last.message.content;
  const tool = Array.isArray(c) && c.some((x) => x && x.type === 'tool_use');
  const ended = last.type === 'assistant' && !tool && (!last.message.stop_reason || last.message.stop_reason === 'end_turn');
  const quiet = Date.now() - mtime;
  const state = ended ? 'waiting' : quiet > STALL_MS ? 'idle' : 'working';
  return {
    tool: 'claude', project: path.basename(cwd || '') || '', branch: short(branch, 60),
    title: short(title || prompt), state, ago: Math.max(0, quiet), limit,
  };
}

// One Codex session: its folder from the first line, its state and usage from the end.
function codexSession(first, lines, mtime) {
  let cwd = '', title = '', state = '', limits = null, at = 0;
  for (const l of first) { const e = json(l); if (e && e.type === 'session_meta' && e.payload) { cwd = e.payload.cwd || ''; break; } }
  for (const l of lines) {
    const e = json(l);
    if (!e || !e.payload) continue;
    const p = e.payload;
    if (e.type === 'turn_context' && p.cwd) cwd = p.cwd;
    if (e.type !== 'event_msg') continue;
    if (p.type === 'user_message' && p.message) title = p.message;
    if (p.type === 'task_started') state = 'working';
    if (p.type === 'task_complete' || p.type === 'turn_aborted') state = 'waiting';
    if (p.type === 'agent_message' && !state) state = 'waiting';
    if (p.type === 'token_count' && p.rate_limits) { limits = p.rate_limits; at = ts(e.timestamp); }
  }
  if (!cwd && !title) return null;
  const quiet = Date.now() - mtime;
  if (state !== 'waiting') state = quiet > STALL_MS ? 'idle' : 'working';
  return { tool: 'codex', project: path.basename(cwd), branch: '', title: short(title), state, ago: Math.max(0, quiet), limits, limitsAt: at };
}

// Claude Code's five-hour windows: one starts at the hour of a message after the last one ended.
function claudeWindow(times) {
  times.sort((a, b) => a - b);
  let start = 0;
  for (const t of times) {
    if (!start || t >= start + WINDOW_MS) start = Math.floor(t / 3600e3) * 3600e3;
  }
  return start && Date.now() < start + WINDOW_MS ? start : 0;
}

function codexUsage(limits, at) {
  const out = [];
  const now = Date.now();
  for (const [key, label] of [['primary', '5-hour'], ['secondary', 'Weekly']]) {
    const r = limits && limits[key];
    if (!r || typeof r !== 'object') continue;
    const mins = Number(r.window_minutes) || 0;
    const name = mins ? (mins <= 360 ? `${Math.round(mins / 60)}-hour` : mins >= 10000 ? 'Weekly' : `${Math.round(mins / 1440)}-day`) : label;
    const resets = r.resets_at ? Number(r.resets_at) * 1000 : r.resets_in_seconds !== undefined ? at + Number(r.resets_in_seconds) * 1000 : 0;
    const used = Number.isFinite(Number(r.used_percent)) ? Math.max(0, Math.min(1, Number(r.used_percent) / 100)) : null;
    if (resets && resets < now) continue; // that window is over
    out.push({ tool: 'codex', label: name, used, left: resets ? resets - now : null, limited: used !== null && used >= 1 });
  }
  return out;
}

function Agents() {
  const seen = new Map(); // file → {mtime, size, s}
  let usageAt = 0, usageClaude = null;
  async function read(f, parse) {
    const c = seen.get(f.file);
    if (c && c.mtime === f.mtime && c.size === f.size) return c.s && { ...c.s, ago: Math.max(0, Date.now() - f.mtime), state: c.s.state === 'working' && Date.now() - f.mtime > STALL_MS ? 'idle' : c.s.state };
    let s = null;
    try { s = await parse(f); } catch (_) { s = null; }
    seen.set(f.file, { mtime: f.mtime, size: f.size, s });
    return s;
  }
  // Claude Code's window from every log of the last five hours (the assistant's messages' times):
  // read again at most once a minute.
  async function claudeUsage(files, limit) {
    if (Date.now() - usageAt > 60e3) {
      usageAt = Date.now();
      const times = [];
      const since = Date.now() - WINDOW_MS * 2;
      for (const f of files.filter((x) => Date.now() - x.mtime < WINDOW_MS * 2).slice(0, 30)) {
        try {
          for (const l of await tail(f.file, f.size, 2 * 1024 * 1024)) {
            if (!l.includes('"assistant"')) continue;
            const e = json(l);
            const t = e && e.type === 'assistant' && ts(e.timestamp);
            if (t && t > since) times.push(t);
          }
        } catch (_) { /* gone */ }
      }
      usageClaude = claudeWindow(times);
    }
    const now = Date.now();
    if (limit && limit.resets > now) return [{ tool: 'claude', label: '5-hour', used: 1, left: limit.resets - now, limited: true }];
    if (!usageClaude) return [];
    return [{ tool: 'claude', label: '5-hour', used: null, left: usageClaude + WINDOW_MS - now, limited: !!(limit && limit.at > usageClaude) }];
  }

  return async function agents(want = {}) {
    const [cf, xf] = await Promise.all([claudeFiles(RECENT_MS * 2), codexFiles(RECENT_MS)]);
    const recent = cf.filter((f) => Date.now() - f.mtime < RECENT_MS).slice(0, MAX_SESSIONS);
    const cs = (await Promise.all(recent.map((f) => read(f, async (x) => claudeSession(await tail(x.file, x.size), x.mtime))))).filter(Boolean);
    const xs = (await Promise.all(xf.slice(0, MAX_SESSIONS).map((f) => read(f, async (x) => codexSession(await head(x.file), await tail(x.file, x.size), x.mtime))))).filter(Boolean);
    const sessions = [...cs, ...xs].sort((a, b) => a.ago - b.ago).slice(0, MAX_SESSIONS);
    const usage = [];
    if (want.quota !== false) {
      const limit = cs.map((s) => s.limit).filter(Boolean).sort((a, b) => b.at - a.at)[0];
      if (cf.length) usage.push(...await claudeUsage(cf, limit));
      const lx = xs.filter((s) => s.limits).sort((a, b) => b.limitsAt - a.limitsAt)[0];
      if (lx) usage.push(...codexUsage(lx.limits, lx.limitsAt));
    }
    for (const f of seen.keys()) if (!cf.some((x) => x.file === f) && !xf.some((x) => x.file === f)) seen.delete(f);
    return {
      sessions: sessions.map(({ tool, project, branch, title, state, ago }) => ({ tool, project, branch, title, state, ago: Math.round(ago) })),
      usage: usage.map((u) => ({ ...u, left: u.left === null ? null : Math.round(u.left) })),
    };
  };
}

// ---- GitHub Actions ----
const builds = new Map(); // repo#branch → {at, v, p}
function build(repo, branch, token) {
  const key = `${repo}#${branch || ''}`;
  const c = builds.get(key);
  const every = token ? 30e3 : 90e3;
  if (c && (c.p || Date.now() - c.at < every)) return c.p || Promise.resolve(c.v);
  const q = new URLSearchParams({ per_page: '6', ...(branch ? { branch } : {}) });
  const p = fetch(`https://api.github.com/repos/${repo}/actions/runs?${q}`, {
    headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'TwinDesk', 'X-GitHub-Api-Version': '2022-11-28', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
    signal: AbortSignal.timeout(10000),
  }).then(async (r) => {
    if (r.status === 404) return { repo, branch, error: token ? 'Repository not found' : 'Not found. A private repository needs a token' };
    if (r.status === 403 || r.status === 429) return { ...(c && c.v), repo, branch, error: 'GitHub’s limit for now, trying again soon' };
    if (!r.ok) return { repo, branch, error: `GitHub answered ${r.status}` };
    const runs = ((await r.json()).workflow_runs || []);
    const x = runs[0];
    if (!x) return { repo, branch, error: 'No workflow runs yet' };
    return {
      repo, branch: x.head_branch || branch, name: short(x.name, 60), title: short(x.display_title || (x.head_commit && x.head_commit.message), 100),
      status: x.status, conclusion: x.conclusion || '', at: ts(x.run_started_at || x.created_at), url: /^https:\/\/github\.com\//.test(x.html_url || '') ? x.html_url : '',
      runs: runs.map((y) => y.conclusion || y.status),
    };
  }).catch(() => ({ ...(c && c.v), repo, branch, error: 'GitHub can’t be reached' }))
    .then((v) => { builds.set(key, { at: Date.now(), v }); return v; });
  builds.set(key, { at: c ? c.at : 0, v: c && c.v, p });
  return p;
}
// ago from now (the device's clock may differ from this computer's).
const forDevice = (v) => { if (!v || !v.at) return v; const { at, ...rest } = v; return { ...rest, ago: Math.max(0, Date.now() - at) }; };

module.exports = { Agents, build: async (...a) => forDevice(await build(...a)), claudeSession, codexSession, claudeWindow, codexUsage };