topside-arch 0.0.0-stage → 0.1.1

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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +213 -2
  3. package/contrib/aur/PKGBUILD +35 -0
  4. package/contrib/aur/topside-arch.install +25 -0
  5. package/contrib/icons/hicolor/scalable/apps/topside.svg +28 -0
  6. package/contrib/systemd/topside.service +10 -0
  7. package/contrib/themes/sakura.json +31 -0
  8. package/dist/adapters/claude/attach.js +92 -0
  9. package/dist/adapters/claude/hook-event.js +173 -0
  10. package/dist/adapters/claude/one-shot.js +30 -0
  11. package/dist/adapters/claude/settings.js +78 -0
  12. package/dist/adapters/claude/usage.js +76 -0
  13. package/dist/adapters/codex/codex.js +73 -0
  14. package/dist/adapters/codex/patch.js +39 -0
  15. package/dist/adapters/codex/usage.js +77 -0
  16. package/dist/adapters/pi/extension.js +271 -0
  17. package/dist/adapters/pi/risk-gate.js +256 -0
  18. package/dist/cli/commands.js +563 -0
  19. package/dist/cli/hook-log.js +32 -0
  20. package/dist/cli/main.js +100 -0
  21. package/dist/daemon/preview.js +70 -0
  22. package/dist/daemon/processes.js +105 -0
  23. package/dist/daemon/server.js +437 -0
  24. package/dist/daemon/session-state.js +173 -0
  25. package/dist/daemon/store.js +176 -0
  26. package/dist/dms/setup.js +126 -0
  27. package/dist/hosts/hosts.js +39 -0
  28. package/dist/jump/jump.js +199 -0
  29. package/dist/pill/config.js +92 -0
  30. package/dist/pill/launch.js +38 -0
  31. package/dist/sekaipop/setup.js +210 -0
  32. package/dist/shared/ancestry.js +27 -0
  33. package/dist/shared/client.js +29 -0
  34. package/dist/shared/package.js +25 -0
  35. package/dist/shared/paths.js +69 -0
  36. package/dist/shared/protocol.js +35 -0
  37. package/dist/shared/qml-lib.js +32 -0
  38. package/dist/shared/result.js +6 -0
  39. package/dist/shared/terminal.js +42 -0
  40. package/dist/themes/themes.js +84 -0
  41. package/package.json +49 -4
  42. package/shell/core/AgentIcon.qml +24 -0
  43. package/shell/core/AppLogo.qml +48 -0
  44. package/shell/core/ApprovalRow.qml +197 -0
  45. package/shell/core/BoardDetail.qml +296 -0
  46. package/shell/core/BoardList.qml +433 -0
  47. package/shell/core/BoardNotice.qml +187 -0
  48. package/shell/core/CardButton.qml +55 -0
  49. package/shell/core/CardHeader.qml +46 -0
  50. package/shell/core/ChalkBoard.qml +99 -0
  51. package/shell/core/CompletionCard.qml +106 -0
  52. package/shell/core/FlapText.qml +95 -0
  53. package/shell/core/KeyCap.qml +72 -0
  54. package/shell/core/Mascot.qml +13 -0
  55. package/shell/core/MascotBadge.qml +40 -0
  56. package/shell/core/MascotEffect.qml +40 -0
  57. package/shell/core/Paper.qml +54 -0
  58. package/shell/core/PixelGrid.qml +40 -0
  59. package/shell/core/QuestionRow.qml +161 -0
  60. package/shell/core/SessionRow.qml +220 -0
  61. package/shell/core/Stamp.qml +62 -0
  62. package/shell/core/StatusDots.qml +33 -0
  63. package/shell/core/Surface.qml +32 -0
  64. package/shell/core/Tag.qml +22 -0
  65. package/shell/core/TerminalIcon.qml +34 -0
  66. package/shell/core/Theme.qml +100 -0
  67. package/shell/core/TicketDetail.qml +588 -0
  68. package/shell/core/TicketList.qml +639 -0
  69. package/shell/core/TicketNotice.qml +198 -0
  70. package/shell/core/TopsideClient.qml +198 -0
  71. package/shell/core/UsageLine.qml +106 -0
  72. package/shell/core/agents.js +79 -0
  73. package/shell/core/board.js +138 -0
  74. package/shell/core/hiding.js +29 -0
  75. package/shell/core/pixels.js +542 -0
  76. package/shell/core/qmldir +30 -0
  77. package/shell/core/sounds.js +31 -0
  78. package/shell/core/themes.js +195 -0
  79. package/shell/core/ticket.js +131 -0
  80. package/shell/dms-plugin/TopsideSettings.qml +696 -0
  81. package/shell/dms-plugin/TopsideWidget.qml +572 -0
  82. package/shell/dms-plugin/plugin.json +14 -0
  83. package/shell/pill.qml +279 -0
  84. package/shell/sekaipop-plugin/Bar.qml +151 -0
  85. package/shell/sekaipop-plugin/Card.qml +291 -0
  86. package/shell/sekaipop-plugin/Floating.qml +83 -0
  87. package/shell/sekaipop-plugin/ListWindow.qml +156 -0
  88. package/shell/sekaipop-plugin/Popup.qml +70 -0
  89. package/shell/sekaipop-plugin/Service.qml +414 -0
  90. package/shell/sekaipop-plugin/ShellLook.qml +43 -0
  91. package/shell/sekaipop-plugin/StyledCard.qml +179 -0
  92. package/shell/sekaipop-plugin/plugin.json +109 -0
@@ -0,0 +1,176 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { isAgentName } from "../shared/protocol.js";
5
+ import { err, ok } from "../shared/result.js";
6
+ import { toTerminalHint } from "../shared/terminal.js";
7
+ const schema = `
8
+ CREATE TABLE IF NOT EXISTS sessions (
9
+ id TEXT PRIMARY KEY,
10
+ agent TEXT NOT NULL,
11
+ cwd TEXT NOT NULL,
12
+ title TEXT NOT NULL,
13
+ status TEXT NOT NULL,
14
+ updated_at INTEGER NOT NULL,
15
+ pids TEXT NOT NULL,
16
+ terminal TEXT NOT NULL DEFAULT '{}',
17
+ last_prompt TEXT NOT NULL DEFAULT '',
18
+ activity TEXT NOT NULL DEFAULT '',
19
+ started_at INTEGER NOT NULL DEFAULT 0,
20
+ last_message TEXT NOT NULL DEFAULT '',
21
+ ended_in_front INTEGER NOT NULL DEFAULT 0,
22
+ name TEXT NOT NULL DEFAULT '',
23
+ agent_pid INTEGER NOT NULL DEFAULT 0
24
+ );
25
+ CREATE TABLE IF NOT EXISTS events (
26
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
27
+ session_id TEXT NOT NULL,
28
+ type TEXT NOT NULL,
29
+ at INTEGER NOT NULL,
30
+ body TEXT NOT NULL
31
+ );
32
+ CREATE INDEX IF NOT EXISTS events_session ON events (session_id, at);
33
+ CREATE TABLE IF NOT EXISTS usage (
34
+ agent TEXT PRIMARY KEY,
35
+ body TEXT NOT NULL
36
+ );
37
+ CREATE TABLE IF NOT EXISTS approvals (
38
+ id TEXT PRIMARY KEY,
39
+ session_id TEXT NOT NULL,
40
+ tool_name TEXT NOT NULL,
41
+ summary TEXT NOT NULL,
42
+ preview TEXT NOT NULL DEFAULT '[]',
43
+ file TEXT NOT NULL DEFAULT '',
44
+ always TEXT NOT NULL DEFAULT '',
45
+ tool_use_id TEXT,
46
+ created_at INTEGER NOT NULL,
47
+ status TEXT NOT NULL
48
+ );
49
+ `;
50
+ function toSession(row) {
51
+ return {
52
+ id: String(row.id),
53
+ agent: isAgentName(row.agent) ? row.agent : "claude",
54
+ cwd: String(row.cwd),
55
+ title: String(row.title),
56
+ status: row.status,
57
+ updatedAt: Number(row.updated_at),
58
+ pids: JSON.parse(String(row.pids)),
59
+ terminal: toTerminalHint(JSON.parse(String(row.terminal))),
60
+ lastPrompt: String(row.last_prompt),
61
+ activity: String(row.activity),
62
+ // Rows from before started_at existed fall back to their last update.
63
+ startedAt: Number(row.started_at) || Number(row.updated_at),
64
+ lastMessage: String(row.last_message ?? ""),
65
+ endedInFront: Number(row.ended_in_front) === 1,
66
+ name: String(row.name ?? ""),
67
+ agentPid: Number(row.agent_pid ?? 0),
68
+ };
69
+ }
70
+ function toApproval(row) {
71
+ return {
72
+ id: String(row.id),
73
+ sessionId: String(row.session_id),
74
+ toolName: String(row.tool_name),
75
+ summary: String(row.summary),
76
+ preview: JSON.parse(String(row.preview)),
77
+ file: String(row.file ?? ""),
78
+ always: String(row.always ?? ""),
79
+ toolUseId: row.tool_use_id === null ? null : String(row.tool_use_id),
80
+ createdAt: Number(row.created_at),
81
+ status: row.status,
82
+ };
83
+ }
84
+ // `path` is a file path or ":memory:".
85
+ export function openStore(path) {
86
+ try {
87
+ if (path !== ":memory:")
88
+ mkdirSync(dirname(path), { recursive: true });
89
+ const db = new DatabaseSync(path);
90
+ db.exec(schema);
91
+ migrate(db);
92
+ return ok(createStore(db));
93
+ }
94
+ catch (error) {
95
+ return err(`cannot open database ${path}: ${String(error)}`);
96
+ }
97
+ }
98
+ // Columns added after the first release, for databases created before them.
99
+ const addedColumns = {
100
+ sessions: {
101
+ terminal: "TEXT NOT NULL DEFAULT '{}'",
102
+ last_prompt: "TEXT NOT NULL DEFAULT ''",
103
+ activity: "TEXT NOT NULL DEFAULT ''",
104
+ started_at: "INTEGER NOT NULL DEFAULT 0",
105
+ last_message: "TEXT NOT NULL DEFAULT ''",
106
+ ended_in_front: "INTEGER NOT NULL DEFAULT 0",
107
+ name: "TEXT NOT NULL DEFAULT ''",
108
+ agent_pid: "INTEGER NOT NULL DEFAULT 0",
109
+ },
110
+ approvals: {
111
+ preview: "TEXT NOT NULL DEFAULT '[]'",
112
+ file: "TEXT NOT NULL DEFAULT ''",
113
+ always: "TEXT NOT NULL DEFAULT ''",
114
+ },
115
+ };
116
+ function migrate(db) {
117
+ for (const [table, added] of Object.entries(addedColumns)) {
118
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((row) => String(row.name));
119
+ for (const [name, type] of Object.entries(added)) {
120
+ if (!columns.includes(name))
121
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`);
122
+ }
123
+ }
124
+ }
125
+ function createStore(db) {
126
+ const upsertSession = db.prepare(`
127
+ INSERT INTO sessions (id, agent, cwd, title, status, updated_at, pids, terminal, last_prompt, activity, started_at, last_message, ended_in_front, name, agent_pid)
128
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
129
+ ON CONFLICT (id) DO UPDATE SET
130
+ cwd = excluded.cwd, title = excluded.title, status = excluded.status,
131
+ updated_at = excluded.updated_at, pids = excluded.pids, terminal = excluded.terminal,
132
+ last_prompt = excluded.last_prompt, activity = excluded.activity, started_at = excluded.started_at,
133
+ last_message = excluded.last_message, ended_in_front = excluded.ended_in_front,
134
+ name = excluded.name, agent_pid = excluded.agent_pid`);
135
+ const insertEvent = db.prepare("INSERT INTO events (session_id, type, at, body) VALUES (?, ?, ?, ?)");
136
+ const upsertApproval = db.prepare(`
137
+ INSERT INTO approvals (id, session_id, tool_name, summary, preview, file, always, tool_use_id, created_at, status)
138
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
139
+ ON CONFLICT (id) DO UPDATE SET status = excluded.status`);
140
+ return {
141
+ saveSession(session) {
142
+ upsertSession.run(session.id, session.agent, session.cwd, session.title, session.status, session.updatedAt, JSON.stringify(session.pids), JSON.stringify(session.terminal), session.lastPrompt, session.activity, session.startedAt, session.lastMessage, session.endedInFront ? 1 : 0, session.name, session.agentPid);
143
+ },
144
+ logEvent(event) {
145
+ insertEvent.run(event.sessionId, event.type, event.at, JSON.stringify(event));
146
+ },
147
+ saveApproval(approval) {
148
+ upsertApproval.run(approval.id, approval.sessionId, approval.toolName, approval.summary, JSON.stringify(approval.preview), approval.file, approval.always, approval.toolUseId, approval.createdAt, approval.status);
149
+ },
150
+ // The last usage each agent reported, so the header isn't empty after a restart.
151
+ saveUsage(agent, usage) {
152
+ db.prepare("INSERT INTO usage (agent, body) VALUES (?, ?) ON CONFLICT (agent) DO UPDATE SET body = excluded.body").run(agent, JSON.stringify(usage));
153
+ },
154
+ usage() {
155
+ const rows = db.prepare("SELECT agent, body FROM usage").all();
156
+ return Object.fromEntries(rows.map((row) => [String(row.agent), JSON.parse(String(row.body))]));
157
+ },
158
+ liveSessions() {
159
+ return db.prepare("SELECT * FROM sessions WHERE status != 'ended' ORDER BY updated_at DESC").all().map(toSession);
160
+ },
161
+ pendingApprovals() {
162
+ return db.prepare("SELECT * FROM approvals WHERE status = 'pending' ORDER BY created_at").all().map(toApproval);
163
+ },
164
+ // A hook waiting on a pending approval dies with the daemon, so it can't be answered anymore.
165
+ expirePending() {
166
+ db.exec("UPDATE approvals SET status = 'expired' WHERE status = 'pending'");
167
+ },
168
+ eventCount(sessionId) {
169
+ const row = db.prepare("SELECT COUNT(*) AS n FROM events WHERE session_id = ?").get(sessionId);
170
+ return Number(row?.n ?? 0);
171
+ },
172
+ close() {
173
+ db.close();
174
+ },
175
+ };
176
+ }
@@ -0,0 +1,126 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { env } from "node:process";
6
+ import { fileURLToPath } from "node:url";
7
+ import { configDir, topsideCommand } from "../shared/paths.js";
8
+ import { err, ok } from "../shared/result.js";
9
+ export const PLUGIN_ID = "topside";
10
+ // The plugin's id before the rename to Topside. Setup switches it off and
11
+ // removes its folder, so the bar doesn't run both.
12
+ export const LEGACY_PLUGIN_ID = "via";
13
+ export const realHost = {
14
+ dmsRunning: () => spawnSync("pgrep", ["-x", "dms"], { stdio: "ignore" }).status === 0,
15
+ // DMS only watches the plugin folder if it existed at startup, so ask for a rescan.
16
+ scanPlugins: () => void spawnSync("dms", ["ipc", "call", "plugin-scan", "scan"], { stdio: "ignore" }),
17
+ enablePlugin: (id) => {
18
+ const run = spawnSync("dms", ["ipc", "call", "plugins", "enable", id], { encoding: "utf8" });
19
+ if (run.error)
20
+ return err(`can't run dms: ${run.error.message}`);
21
+ const out = run.stdout.trim();
22
+ return out.startsWith("PLUGIN_ENABLE_SUCCESS") ? ok(out) : err(out || run.stderr.trim() || `dms exited with ${run.status}`);
23
+ },
24
+ disablePlugin: (id) => void spawnSync("dms", ["ipc", "call", "plugins", "disable", id], { stdio: "ignore" }),
25
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
26
+ };
27
+ export function dmsPluginsDir() {
28
+ const config = env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
29
+ return join(config, "dms", "plugins");
30
+ }
31
+ export function pluginSourceDir() {
32
+ return fileURLToPath(new URL("../../shell/dms-plugin/", import.meta.url));
33
+ }
34
+ export function coreSourceDir() {
35
+ return fileURLToPath(new URL("../../shell/core/", import.meta.url));
36
+ }
37
+ // Copies the plugin and the shared QML into <pluginsDir>/topside. Overwrites,
38
+ // so running it again after an upgrade refreshes the files. cli.json holds the
39
+ // command the widget runs for `topside jump`, since DMS's PATH may not have `topside`.
40
+ export function installPlugin(pluginsDir, cli, pluginSrc = pluginSourceDir(), coreSrc = coreSourceDir()) {
41
+ for (const dir of [pluginSrc, coreSrc]) {
42
+ if (!existsSync(dir) || readdirSync(dir).length === 0)
43
+ return err(`plugin files missing at ${dir}`);
44
+ }
45
+ const target = join(pluginsDir, PLUGIN_ID);
46
+ try {
47
+ mkdirSync(target, { recursive: true });
48
+ cpSync(pluginSrc, target, { recursive: true });
49
+ cpSync(coreSrc, join(target, "core"), { recursive: true });
50
+ writeFileSync(join(target, "cli.json"), `${JSON.stringify(cli)}\n`);
51
+ }
52
+ catch (error) {
53
+ return err(`can't write ${target}: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
55
+ return ok(target);
56
+ }
57
+ // The rescan is debounced inside DMS, so enabling right away says "not found".
58
+ // Retry for a couple of seconds before giving up.
59
+ async function enableWithRetry(host, attempts = 10, gapMs = 250) {
60
+ let last = err("never tried");
61
+ for (let i = 0; i < attempts; i++) {
62
+ last = host.enablePlugin(PLUGIN_ID);
63
+ if (last.ok || !last.error.startsWith("PLUGIN_NOT_FOUND"))
64
+ return last;
65
+ await host.wait(gapMs);
66
+ }
67
+ return last;
68
+ }
69
+ export async function setup(host, pluginsDir = dmsPluginsDir(), cli = topsideCommand()) {
70
+ if (!host.dmsRunning()) {
71
+ return ok("DMS isn't running, so there's no bar to join.\nStart the standalone pill instead: topside pill\n");
72
+ }
73
+ const legacy = join(pluginsDir, LEGACY_PLUGIN_ID);
74
+ const renamed = existsSync(legacy);
75
+ if (renamed) {
76
+ host.disablePlugin(LEGACY_PLUGIN_ID);
77
+ try {
78
+ rmSync(legacy, { recursive: true, force: true });
79
+ }
80
+ catch (error) {
81
+ return err(`can't remove the old via widget at ${legacy}: ${error instanceof Error ? error.message : String(error)}`);
82
+ }
83
+ }
84
+ // A running DMS keeps the old core/ types cached; only a restart drops them.
85
+ const upgrade = renamed || existsSync(join(pluginsDir, PLUGIN_ID, "core"));
86
+ const installed = installPlugin(pluginsDir, cli);
87
+ if (!installed.ok)
88
+ return installed;
89
+ host.scanPlugins();
90
+ const enabled = await enableWithRetry(host);
91
+ // Enabling can fail on an upgrade too, because the cached old files break the
92
+ // new widget. The restart fixes both.
93
+ if (renamed) {
94
+ return ok(`Replaced the via widget with Topside in ${installed.value}.\n` +
95
+ "1. Restart DMS so it drops the old files: systemctl --user restart dms\n" +
96
+ '2. Open DMS Settings → Bar → Widgets and add "Topside" where "via" sat.\n');
97
+ }
98
+ if (upgrade) {
99
+ return ok(`Updated the Topside widget in ${installed.value}.\n` +
100
+ "DMS caches the old files until it restarts: systemctl --user restart dms\n");
101
+ }
102
+ if (!enabled.ok) {
103
+ return ok(`Plugin files are in ${installed.value}, but enabling it failed: ${enabled.error}\n` +
104
+ "Open DMS Settings → Plugins and switch Topside on by hand.\n");
105
+ }
106
+ return ok(`Installed the Topside widget into ${installed.value} and enabled it.\n` +
107
+ "Next: open DMS Settings → Bar → Widgets and add \"Topside\" to the left, center or right zone.\n");
108
+ }
109
+ // Folders hidden on the DMS widget: savePluginData keeps them in DMS's plugin_settings.json.
110
+ export function dmsHiddenFolders(path = join(configDir(), "DankMaterialShell", "plugin_settings.json")) {
111
+ try {
112
+ const all = JSON.parse(readFileSync(path, "utf8"));
113
+ const folders = all?.topside?.hiddenFolders;
114
+ return Array.isArray(folders) ? folders.filter((f) => typeof f === "string") : [];
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ }
120
+ // DMS as a shell Topside can live in (src/hosts/hosts.ts).
121
+ export const dmsShell = {
122
+ name: "DMS",
123
+ running: () => realHost.dmsRunning(),
124
+ setup: () => setup(realHost),
125
+ hiddenFolders: () => dmsHiddenFolders(),
126
+ };
@@ -0,0 +1,39 @@
1
+ import { dmsShell } from "../dms/setup.js";
2
+ import { err, ok } from "../shared/result.js";
3
+ import { sekaipopShell } from "../sekaipop/setup.js";
4
+ export const shellHosts = [sekaipopShell, dmsShell];
5
+ export const noShellMessage = "Neither SekaiPop nor DMS is running, so there's no bar to join.\nStart the standalone pill instead: topside pill\n";
6
+ // `topside setup`: installs into every running shell; with none, points at the pill.
7
+ export async function setupShells(hosts = shellHosts) {
8
+ const running = hosts.filter((host) => host.running());
9
+ if (running.length === 0)
10
+ return ok(noShellMessage);
11
+ const parts = [];
12
+ for (const host of running) {
13
+ const result = await host.setup();
14
+ if (!result.ok)
15
+ return err(`${host.name}: ${result.error}`);
16
+ parts.push(result.value);
17
+ }
18
+ return ok(parts.join("\n"));
19
+ }
20
+ // `topside theme sync`: every shell that keeps its own list of themes gets
21
+ // the current files, whether it runs or not (the list waits in its config).
22
+ export function syncThemesOfShells(hosts = shellHosts) {
23
+ const said = [];
24
+ for (const host of hosts) {
25
+ if (!host.syncThemes)
26
+ continue;
27
+ const result = host.syncThemes();
28
+ if (!result.ok)
29
+ return err(`${host.name}: ${result.error}`);
30
+ if (result.value !== "")
31
+ said.push(result.value);
32
+ }
33
+ return ok(said.length > 0 ? `${said.join("\n")}\n` : "Every shell already lists your themes.\n");
34
+ }
35
+ // Hidden folders from every shell, whether it runs or not: the user's
36
+ // choice stands while they switch shells.
37
+ export function hiddenFoldersOfShells(hosts = shellHosts) {
38
+ return hosts.flatMap((host) => host.hiddenFolders());
39
+ }
@@ -0,0 +1,199 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { env } from "node:process";
4
+ import { ancestry } from "../shared/ancestry.js";
5
+ import { err, ok } from "../shared/result.js";
6
+ import { noTerminal, terminalHint } from "../shared/terminal.js";
7
+ // Terminals whose shells don't descend from the window process.
8
+ const classByProgram = {
9
+ Orca: "orca",
10
+ WezTerm: "org.wezfurlong.wezterm",
11
+ };
12
+ // Nearest ancestor that owns a window wins; the terminal's class is the fallback.
13
+ export function findWindow(chain, windows, program) {
14
+ for (const pid of chain) {
15
+ const match = windows.find((w) => w.pid === pid);
16
+ if (match)
17
+ return match;
18
+ }
19
+ const className = classByProgram[program];
20
+ return className === undefined ? null : (windows.find((w) => w.className === className) ?? null);
21
+ }
22
+ // Hyprland 0.57 with a Lua config only takes Lua dispatch calls; a hyprlang
23
+ // config takes the old dispatcher syntax. Try Lua first.
24
+ export function focusStep(window) {
25
+ const target = `address:${window.address}`;
26
+ return {
27
+ command: "hyprctl",
28
+ args: ["dispatch", `hl.dsp.focus({ window = "${target}" })`],
29
+ expect: "ok",
30
+ fallback: { command: "hyprctl", args: ["dispatch", "focuswindow", target], expect: "ok" },
31
+ };
32
+ }
33
+ // Brings the right tab or pane forward inside a terminal window.
34
+ function tabStep(terminal) {
35
+ if (terminal.weztermPane !== "") {
36
+ return [
37
+ {
38
+ command: "wezterm",
39
+ args: ["cli", "activate-pane", "--pane-id", terminal.weztermPane],
40
+ ...(terminal.weztermSocket === "" ? {} : { env: { WEZTERM_UNIX_SOCKET: terminal.weztermSocket } }),
41
+ },
42
+ ];
43
+ }
44
+ if (terminal.orcaTerminal !== "") {
45
+ return [{ command: terminal.orcaCli || "orca", args: ["terminal", "switch", "--terminal", terminal.orcaTerminal] }];
46
+ }
47
+ return [];
48
+ }
49
+ export function planJump(terminal, window, tmux) {
50
+ if (tmux === null)
51
+ return [focusStep(window), ...tabStep(terminal)];
52
+ const tmuxArgs = (...args) => ({ command: "tmux", args: ["-S", terminal.tmuxSocket, ...args] });
53
+ return [
54
+ focusStep(window),
55
+ ...tabStep(tmux.terminal),
56
+ tmuxArgs("switch-client", "-c", tmux.tty, "-t", terminal.tmuxPane),
57
+ tmuxArgs("select-window", "-t", terminal.tmuxPane),
58
+ tmuxArgs("select-pane", "-t", terminal.tmuxPane),
59
+ ];
60
+ }
61
+ function locate(session, host) {
62
+ const windows = host.windows();
63
+ if (!windows.ok)
64
+ return windows;
65
+ const { terminal } = session;
66
+ let chain = session.pids;
67
+ let tmux = null;
68
+ if (terminal.tmuxSocket !== "" && terminal.tmuxPane !== "") {
69
+ const client = host.tmuxClient(terminal.tmuxSocket, terminal.tmuxPane);
70
+ if (!client.ok)
71
+ return client;
72
+ if (client.value === null)
73
+ return err(`"${session.title}" runs in a tmux session nobody is attached to. Attach it with: tmux attach`);
74
+ tmux = client.value;
75
+ chain = host.ancestry(tmux.pid);
76
+ }
77
+ const window = findWindow(chain, windows.value, tmux === null ? terminal.program : "");
78
+ if (window === null) {
79
+ return err(`Can't find the terminal window for "${session.title}". If it started before Topside recorded terminals, send it a prompt and try again.`);
80
+ }
81
+ return ok({ window, tmux });
82
+ }
83
+ export function jump(session, host) {
84
+ const located = locate(session, host);
85
+ if (!located.ok)
86
+ return located;
87
+ const { window, tmux } = located.value;
88
+ for (const step of planJump(session.terminal, window, tmux)) {
89
+ const result = host.run(step);
90
+ if (!result.ok)
91
+ return result;
92
+ }
93
+ return ok(`Jumped to "${session.title}" on workspace ${window.workspace}\n`);
94
+ }
95
+ // Whether the session's terminal window has the focus, so the user already
96
+ // sees it. Window, not tab: a terminal in front showing another tab counts.
97
+ // Anything unknown counts as not in front.
98
+ export function isInFront(session, host) {
99
+ const located = locate(session, host);
100
+ const active = host.activeWindow();
101
+ return located.ok && active.ok && active.value !== "" && active.value === located.value.window.address;
102
+ }
103
+ function exec(command, args, extraEnv = {}) {
104
+ const result = spawnSync(command, args, { encoding: "utf8", env: { ...env, ...extraEnv }, timeout: 5000 });
105
+ if (result.error) {
106
+ const code = result.error.code;
107
+ return err(code === "ENOENT" ? `${command} is not installed` : `${command} failed: ${result.error.message}`);
108
+ }
109
+ if (result.status !== 0)
110
+ return err(`${command} ${args.join(" ")} failed: ${result.stderr.trim() || `exit ${result.status}`}`);
111
+ return ok(result.stdout);
112
+ }
113
+ function parseWindows(json) {
114
+ let value;
115
+ try {
116
+ value = JSON.parse(json);
117
+ }
118
+ catch {
119
+ return err("hyprctl clients -j did not return JSON");
120
+ }
121
+ if (!Array.isArray(value))
122
+ return err("hyprctl clients -j did not return a list");
123
+ const windows = [];
124
+ for (const item of value) {
125
+ const workspace = item.workspace;
126
+ if (item.mapped === false)
127
+ continue;
128
+ windows.push({
129
+ address: String(item.address),
130
+ pid: Number(item.pid),
131
+ className: String(item.class),
132
+ workspace: Number(workspace?.id ?? 0),
133
+ });
134
+ }
135
+ return ok(windows);
136
+ }
137
+ // The terminal hint of another process, from its environment.
138
+ function processTerminal(pid) {
139
+ try {
140
+ const pairs = readFileSync(`/proc/${pid}/environ`, "utf8")
141
+ .split("\0")
142
+ .map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]);
143
+ return terminalHint(Object.fromEntries(pairs));
144
+ }
145
+ catch {
146
+ return noTerminal;
147
+ }
148
+ }
149
+ function runStep(step) {
150
+ const out = exec(step.command, step.args, step.env);
151
+ const result = !out.ok
152
+ ? out
153
+ : step.expect !== undefined && out.value.trim() !== step.expect
154
+ ? err(`${step.command} ${step.args.join(" ")} said: ${out.value.trim()}`)
155
+ : ok(undefined);
156
+ if (result.ok || step.fallback === undefined)
157
+ return result;
158
+ const second = runStep(step.fallback);
159
+ return second.ok ? second : err(`${result.error}\n${second.error}`);
160
+ }
161
+ export const realHost = {
162
+ windows() {
163
+ const out = exec("hyprctl", ["clients", "-j"]);
164
+ return out.ok ? parseWindows(out.value) : err(`${out.error} (jump needs Hyprland)`);
165
+ },
166
+ ancestry,
167
+ tmuxClient(socket, pane) {
168
+ const session = exec("tmux", ["-S", socket, "display-message", "-p", "-t", pane, "#{session_name}"]);
169
+ if (!session.ok)
170
+ return session;
171
+ const clients = exec("tmux", ["-S", socket, "list-clients", "-t", session.value.trim(), "-F", "#{client_activity} #{client_pid} #{client_tty}"]);
172
+ if (!clients.ok)
173
+ return clients;
174
+ // Most recently active client first.
175
+ const rows = clients.value
176
+ .split("\n")
177
+ .filter(Boolean)
178
+ .map((line) => line.split(" "))
179
+ .sort((a, b) => Number(b[0]) - Number(a[0]));
180
+ const [, pid, tty] = rows[0] ?? [];
181
+ return ok(pid && tty ? { pid: Number(pid), tty, terminal: processTerminal(Number(pid)) } : null);
182
+ },
183
+ run(step) {
184
+ return runStep(step);
185
+ },
186
+ activeWindow() {
187
+ const out = exec("hyprctl", ["activewindow", "-j"]);
188
+ if (!out.ok)
189
+ return out;
190
+ try {
191
+ const value = JSON.parse(out.value);
192
+ const address = typeof value === "object" && value !== null && "address" in value ? value.address : "";
193
+ return ok(typeof address === "string" ? address : "");
194
+ }
195
+ catch {
196
+ return ok("");
197
+ }
198
+ },
199
+ };
@@ -0,0 +1,92 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { env } from "node:process";
4
+ import { configDir } from "../shared/paths.js";
5
+ import { err, ok } from "../shared/result.js";
6
+ import { themesDir, userThemes } from "../themes/themes.js";
7
+ export const PILL_POSITIONS = [
8
+ "top-left",
9
+ "top-center",
10
+ "top-right",
11
+ "middle-left",
12
+ "middle-center",
13
+ "middle-right",
14
+ "bottom-left",
15
+ "bottom-center",
16
+ "bottom-right",
17
+ ];
18
+ // Topside's themes; shell/core/themes.js holds their colors.
19
+ export const THEMES = ["topsideBlack", "tokyoNight", "monokai", "catppuccin", "dracula", "nord", "gruvbox", "solarized", "one"];
20
+ export const APPEARANCES = ["light", "dark", "system"];
21
+ export const FONT_SIZES = { min: 10, max: 14 };
22
+ export const DEFAULT_CONFIG = {
23
+ pill: { position: "top-center" },
24
+ theme: "topsideBlack",
25
+ appearance: "dark",
26
+ fontSize: 11,
27
+ gate: false,
28
+ };
29
+ export function configPath() {
30
+ const explicit = env.TOPSIDE_CONFIG ?? env.VIA_CONFIG;
31
+ if (explicit)
32
+ return explicit;
33
+ return join(configDir(), "topside", "config.json");
34
+ }
35
+ export function parseTheme(value, dir = themesDir()) {
36
+ const found = THEMES.find((t) => t === value);
37
+ if (found !== undefined)
38
+ return ok(found);
39
+ const yours = userThemes(dir).filter((t) => t.usable);
40
+ const mine = yours.find((t) => t.id === value);
41
+ if (mine !== undefined)
42
+ return ok(mine.id);
43
+ return err(`unknown theme "${String(value)}"; expected one of ${[...THEMES, ...yours.map((t) => t.id)].join(", ")}`);
44
+ }
45
+ export function parseAppearance(value) {
46
+ const found = APPEARANCES.find((a) => a === value);
47
+ return found === undefined ? err(`unknown mode "${String(value)}"; expected light, dark or system`) : ok(found);
48
+ }
49
+ export function parseFontSize(value) {
50
+ const size = typeof value === "string" ? Number(value) : value;
51
+ if (typeof size !== "number" || !Number.isInteger(size) || size < FONT_SIZES.min || size > FONT_SIZES.max) {
52
+ return err(`text size must be a whole number from ${FONT_SIZES.min} to ${FONT_SIZES.max}`);
53
+ }
54
+ return ok(size);
55
+ }
56
+ export function parsePillPosition(value) {
57
+ const found = PILL_POSITIONS.find((p) => p === value);
58
+ if (found === undefined)
59
+ return err(`unknown position "${String(value)}"; expected one of ${PILL_POSITIONS.join(", ")}`);
60
+ return ok(found);
61
+ }
62
+ // A missing or broken file reads as the defaults, so the pill always has
63
+ // somewhere to sit; a bad value reads as its default and the rest still count.
64
+ export function readConfig(path) {
65
+ let raw;
66
+ try {
67
+ raw = JSON.parse(readFileSync(path, "utf8"));
68
+ }
69
+ catch {
70
+ return DEFAULT_CONFIG;
71
+ }
72
+ const record = raw !== null && typeof raw === "object" ? raw : {};
73
+ const pill = record.pill !== null && typeof record.pill === "object" ? record.pill : {};
74
+ const or = (parsed, fallback) => (parsed.ok ? parsed.value : fallback);
75
+ return {
76
+ pill: { position: or(parsePillPosition(pill.position), DEFAULT_CONFIG.pill.position) },
77
+ theme: or(parseTheme(record.theme), DEFAULT_CONFIG.theme),
78
+ appearance: or(parseAppearance(record.appearance), DEFAULT_CONFIG.appearance),
79
+ fontSize: or(parseFontSize(record.fontSize), DEFAULT_CONFIG.fontSize),
80
+ gate: record.gate === true,
81
+ };
82
+ }
83
+ export function writeConfig(path, config) {
84
+ try {
85
+ mkdirSync(dirname(path), { recursive: true });
86
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
87
+ return ok(undefined);
88
+ }
89
+ catch (error) {
90
+ return err(`can't write ${path}: ${error instanceof Error ? error.message : String(error)}`);
91
+ }
92
+ }
@@ -0,0 +1,38 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { env } from "node:process";
4
+ import { fileURLToPath } from "node:url";
5
+ import { socketPath, topsideCommand } from "../shared/paths.js";
6
+ import { err, ok } from "../shared/result.js";
7
+ import { configPath, readConfig, writeConfig } from "./config.js";
8
+ // shell/ ships next to dist/ in the package, so derive it from this file.
9
+ // Quickshell confines a config to the root file's directory, so the pill root
10
+ // sits in shell/ itself and imports "core" from there.
11
+ export function pillShellFile() {
12
+ return fileURLToPath(new URL("../../shell/pill.qml", import.meta.url));
13
+ }
14
+ // Runs quickshell with the pill until it exits. The config file is written
15
+ // first so the pill has a file to watch for position changes.
16
+ export async function launchPill() {
17
+ const shellFile = pillShellFile();
18
+ if (!existsSync(shellFile))
19
+ return err(`pill shell not found at ${shellFile}`);
20
+ const config = configPath();
21
+ if (!existsSync(config)) {
22
+ const written = writeConfig(config, readConfig(config));
23
+ if (!written.ok)
24
+ return written;
25
+ }
26
+ return new Promise((resolve) => {
27
+ const child = spawn("quickshell", ["-p", shellFile], {
28
+ stdio: "inherit",
29
+ // TOPSIDE_CLI lets the pill run `topside jump` without `topside` on PATH.
30
+ env: { ...env, TOPSIDE_SOCKET: socketPath(), TOPSIDE_CONFIG: config, TOPSIDE_CLI: JSON.stringify(topsideCommand()) },
31
+ });
32
+ child.once("error", (error) => {
33
+ const reason = "code" in error && error.code === "ENOENT" ? "quickshell is not installed" : error.message;
34
+ resolve(err(`can't start the pill: ${reason}`));
35
+ });
36
+ child.once("exit", (code) => resolve(code === 0 || code === null ? ok(undefined) : err(`quickshell exited with ${code}`)));
37
+ });
38
+ }