CoreDesktop GNOME extension

This commit is contained in:
2026-11-27 12:28:07 -07:00
commit 7d9d2d6239
15 changed files with 1742 additions and 0 deletions
@@ -0,0 +1,49 @@
#!/bin/bash
#
# Purpose : Run a CoreDesktop command in the terminal the extension opened, and
# record whether it's running or how it ended, so the top bar menu
# can show it and notify when it's done.
#
# run-tracked <name> <command> [arguments...]
#
# Writes $XDG_RUNTIME_DIR/coredesktop-extension/<name>.status: "running <pid>"
# while the command runs, then "exit <status>". Closing the window while the
# command runs records 129, like a shell would.
name="$1"
shift
dir="${XDG_RUNTIME_DIR:-/tmp}/coredesktop-extension"
mkdir -p -m 700 "$dir"
status_file="$dir/$name.status"
# The commands live in ~/.local/bin, which GNOME Shell's PATH may not include
export PATH="$HOME/.local/bin:$PATH"
write_status() {
printf '%s\n' "$1" > "$status_file.tmp" && mv -f "$status_file.tmp" "$status_file"
}
finished=""
finish() {
[ -n "$finished" ] && return
finished=1
write_status "exit $1"
}
trap 'finish 129; exit 129' HUP
trap 'finish 130; exit 130' TERM
write_status "running $$"
"$@"
code=$?
finish "$code"
# e.g. "configure core", without ~/.local/bin/
what="${1##*/}${2:+ ${*:2}}"
echo
if [ "$code" -eq 0 ]; then
printf '\e[1;32m✔ %s finished.\e[0m\n' "$what"
else
printf '\e[1;31m✘ %s ended with status %d.\e[0m\n' "$what" "$code"
fi
read -rp "Press Enter to close this window."
+666
View File
@@ -0,0 +1,666 @@
// CoreDesktop: a top bar menu for CoreDesktop's own commands (update, refresh,
// configure, version, audit, report), showing what each does and how it's going.
import Clutter from 'gi://Clutter';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import St from 'gi://St';
import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as MessageTray from 'resource:///org/gnome/shell/ui/messageTray.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
import * as Cli from './lib/cli.js';
import {ConfigureDialog, ConfirmDialog, VersionDialog} from './lib/dialogs.js';
// What each command is called, what it does in a few words, and its icon
const COMMANDS = {
update: {
title: 'Update',
description: 'Get the latest CoreDesktop, system packages, apps and extensions',
icon: 'software-update-available-symbolic',
argv: ['update'],
},
refresh: {
title: 'Refresh',
description: 'Re-run the installer to add apps and services new to CoreDesktop',
icon: 'view-refresh-symbolic',
argv: ['refresh'],
},
configure: {
title: 'Configure',
description: 'Set up your Core, Tailscale, backups, AI agents and more',
icon: 'preferences-system-symbolic',
argv: ['configure'],
},
version: {
title: 'Version',
description: 'See your CoreDesktop, kernel, video driver and sibling versions',
icon: 'help-about-symbolic',
},
audit: {
title: 'Network audit',
description: 'See which ports are open, who can reach them, and why',
icon: 'security-high-symbolic',
argv: ['audit'],
},
report: {
title: 'Report a problem',
description: 'Send the latest update log to the CoreDesktop team',
icon: 'mail-send-symbolic',
argv: ['report'],
},
};
// Icons for configure's items, by name
const CONFIGURE_ICONS = {
'core': 'network-server-symbolic',
'tailscale': 'network-vpn-symbolic',
'backup': 'drive-harddisk-symbolic',
'claude': 'utilities-terminal-symbolic',
'opencode': 'utilities-terminal-symbolic',
'hermes': 'utilities-terminal-symbolic',
'languages': 'applications-engineering-symbolic',
'ai-servers': 'network-workgroup-symbolic',
'printers': 'printer-symbolic',
'storage': 'folder-remote-symbolic',
'sandbox': 'security-medium-symbolic',
'security-key': 'auth-smartcard-symbolic',
'fingerprint': 'auth-fingerprint-symbolic',
};
// A pill-shaped label at the end of a menu item: "New", "Running…", "To do"
const Pill = GObject.registerClass(
class Pill extends St.Label {
_init() {
super._init({style_class: 'coredesktop-pill', y_align: Clutter.ActorAlign.CENTER, visible: false});
}
// kind: accent, success, warning, error, running, or null to hide. (Not
// named set(): that would override GObject.Object.set, which ease() uses.)
setState(text, kind) {
this.remove_all_transitions();
this.opacity = 255;
if (!text) {
this.hide();
return;
}
this.text = text;
for (const k of ['accent', 'success', 'warning', 'error', 'running'])
this.remove_style_class_name(k);
this.add_style_class_name(kind);
this.show();
if (kind === 'running') {
this.ease({
opacity: 110, duration: 800, autoReverse: true, repeatCount: -1,
mode: Clutter.AnimationMode.EASE_IN_OUT_SINE,
});
}
}
});
// A menu item with an icon, a title, a line saying what it does, and a pill
const ActionItem = GObject.registerClass({
Signals: {'keep-open-activate': {}},
}, class ActionItem extends PopupMenu.PopupBaseMenuItem {
_init({icon, title, description, keepOpen = false}) {
super._init({style_class: 'coredesktop-action-item'});
this._keepOpen = keepOpen;
this.icon = new St.Icon({icon_name: icon, style_class: 'popup-menu-icon coredesktop-action-icon'});
this.add_child(this.icon);
const text = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
this.title = new St.Label({text: title, style_class: 'coredesktop-item-title'});
this.description = new St.Label({text: description, style_class: 'coredesktop-item-description'});
text.add_child(this.title);
text.add_child(this.description);
this.add_child(text);
this.label_actor = this.title;
this.pill = new Pill();
this.add_child(this.pill);
}
// Items that only refresh what the menu shows leave it open
activate(event) {
if (this._keepOpen)
this.emit('keep-open-activate');
else
super.activate(event);
}
});
// The status at the top of the menu: logo, version, and how things stand
const HeaderItem = GObject.registerClass(
class HeaderItem extends PopupMenu.PopupBaseMenuItem {
_init(gicon) {
super._init({reactive: false, can_focus: false, style_class: 'coredesktop-header'});
this.add_child(new St.Icon({gicon, style_class: 'coredesktop-header-icon'}));
const text = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
text.add_child(new St.Label({text: 'CoreDesktop', style_class: 'coredesktop-header-title'}));
this.versionLabel = new St.Label({text: '…', style_class: 'coredesktop-header-version'});
this.statusLabel = new St.Label({text: '', style_class: 'coredesktop-header-status'});
text.add_child(this.versionLabel);
text.add_child(this.statusLabel);
this.add_child(text);
}
setStatus(text, kind) {
this.statusLabel.text = text;
for (const k of ['accent', 'success', 'warning', 'error'])
this.statusLabel.remove_style_class_name(k);
if (kind)
this.statusLabel.add_style_class_name(kind);
}
});
const Indicator = GObject.registerClass(
class Indicator extends PanelMenu.Button {
_init(ext) {
super._init(0.5, 'CoreDesktop', false);
this._ext = ext;
this._settings = ext.getSettings();
this._gicon = Gio.FileIcon.new(Gio.File.new_for_path(
GLib.build_filenamev([ext.path, 'icons', 'coredesktop-symbolic.svg'])));
this._update = {state: 'unknown', version: null, checkedAt: null};
this._running = new Map(); // status name -> pid, 0 until run-tracked starts
this._launchedAt = new Map(); // status name -> monotonic time it was launched
this._titles = new Map(); // status name -> title for notifications
this._rebootNeeded = false;
this._configureTodo = 0;
this._checkCancellable = null;
this._timeouts = new Set();
this._buildPanelIcon();
this._buildMenu();
this._settings.connectObject(
'changed::check-interval', () => this._scheduleChecks(),
'changed::show-badge', () => this._updateIndicator(),
this);
this.menu.connect('open-state-changed', (_menu, open) => {
if (open)
this._refreshLocal();
});
this._watchStatusDir();
this._refreshLocal();
this._scheduleChecks();
}
// Top bar: the logo, with a dot in its corner when something needs attention
_buildPanelIcon() {
// The dot overlaps the icon's top right corner: both sit in a bin the
// icon's size, the dot aligned to its corner
const box = new St.Widget({
layout_manager: new Clutter.BinLayout(),
x_align: Clutter.ActorAlign.CENTER,
y_align: Clutter.ActorAlign.CENTER,
});
this._panelIcon = new St.Icon({gicon: this._gicon, style_class: 'system-status-icon'});
this._badge = new St.Widget({
style_class: 'coredesktop-badge',
x_align: Clutter.ActorAlign.END,
y_align: Clutter.ActorAlign.START,
visible: false,
});
box.add_child(this._panelIcon);
box.add_child(this._badge);
this.add_child(box);
}
_buildMenu() {
this.menu.box.add_style_class_name('coredesktop-menu');
this._header = new HeaderItem(this._gicon);
this.menu.addMenuItem(this._header);
// Shown only when an update needs a restart to finish
this._rebootItem = new ActionItem({
icon: 'system-reboot-symbolic',
title: 'Restart to finish updating',
description: 'An update changed the kernel or system services',
});
this._rebootItem.add_style_class_name('coredesktop-attention');
this._rebootItem.pill.setState('Restart', 'warning');
this._rebootItem.connect('activate', () => this._restart());
this.menu.addMenuItem(this._rebootItem);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem('Keep up to date'));
this._items = {};
this._items.update = this._addCommand('update');
this._items.refresh = this._addCommand('refresh');
this._checkItem = new ActionItem({
icon: 'system-search-symbolic',
title: 'Check for updates',
description: 'Not checked yet',
keepOpen: true,
});
this._checkItem.connect('keep-open-activate', () => this._checkNow());
this.menu.addMenuItem(this._checkItem);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem('Set up'));
this._items.configure = new ActionItem(COMMANDS.configure);
this._items.configure.connect('activate', () => this._openConfigure());
this.menu.addMenuItem(this._items.configure);
this._configureItems = [];
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem('Information'));
this._items.version = this._addCommand('version');
this._items.audit = this._addCommand('audit');
this._items.report = this._addCommand('report');
this._logItem = new ActionItem({
icon: 'text-x-generic-symbolic',
title: 'Latest update log',
description: 'Open the output of the last update or install',
});
this._logItem.connect('activate', () => this._openLatestLog());
this.menu.addMenuItem(this._logItem);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
const prefs = new PopupMenu.PopupImageMenuItem('Extension settings', 'emblem-system-symbolic');
prefs.connect('activate', () => this._ext.openPreferences());
this.menu.addMenuItem(prefs);
}
_addCommand(key) {
const cmd = COMMANDS[key];
const item = new ActionItem(cmd);
item.connect('activate', () => this._runCommand(key));
this.menu.addMenuItem(item);
return item;
}
_openConfigure() {
const items = this._configureItems.map(item => ({
...item,
icon: CONFIGURE_ICONS[item.name] ?? 'emblem-system-symbolic',
running: this._running.has(`configure-${item.name}`),
}));
new ConfigureDialog({
items,
onConfigure: item => this._runTracked(`configure-${item.name}`, item.title, ['configure', item.name]),
onOpenAll: () => this._runCommand('configure'),
}).open();
}
// Everything that can be read locally without the network
async _refreshLocal() {
const version = await Cli.localVersion();
if (!this._header)
return;
this._header.versionLabel.text = version ?? (Cli.isInstalled()
? 'Version unknown' : 'CoreDesktop isn\'t installed');
this._rebootNeeded = GLib.file_test(Cli.REBOOT_NEEDED, GLib.FileTest.EXISTS);
this._lastUpdate = Cli.mtime(Cli.PACMAN_UPDATE_LOG);
try {
const items = await Cli.configureItems();
if (!this._header)
return;
this._configureItems = items;
this._configureTodo = items.filter(i => !i.done).length;
} catch (e) {
console.warn(`CoreDesktop: couldn't list configure items: ${e.message}`);
}
this._updateIndicator();
}
_scheduleChecks() {
if (this._checkTimeout) {
GLib.source_remove(this._checkTimeout);
this._timeouts.delete(this._checkTimeout);
this._checkTimeout = 0;
}
const hours = this._settings.get_uint('check-interval');
if (hours === 0)
return;
// A first check soon after login, then every few hours
const first = this._update.checkedAt ? hours * 3600 : 45;
this._checkTimeout = this._addTimeout(first, () => {
this._checkTimeout = 0;
this._checkNow().finally(() => this._scheduleChecks());
});
}
async _checkNow() {
if (this._checkCancellable)
return;
this._checkCancellable = new Gio.Cancellable();
this._checkItem.pill.setState('Checking…', 'running');
try {
const result = await Cli.checkForUpdate(this._checkCancellable);
this._update = {...result, checkedAt: GLib.get_real_time() / 1e6};
} catch {
return; // cancelled: the extension is being disabled
} finally {
this._checkCancellable = null;
}
this._checkItem.pill.setState(null);
this._updateIndicator();
}
// Bring the menu, header and top bar icon in line with what's known
_updateIndicator() {
if (!this._header)
return;
const {state, version, checkedAt} = this._update;
const running = [...this._running.keys()];
const updating = this._running.has('update') || this._running.has('refresh');
// Header status line
if (this._running.has('update'))
this._header.setStatus('Updating…', 'accent');
else if (this._running.has('refresh'))
this._header.setStatus('Refreshing…', 'accent');
else if (this._rebootNeeded)
this._header.setStatus('Restart to finish the last update', 'warning');
else if (state === 'available')
this._header.setStatus(`${version} is available`, 'accent');
else if (state === 'current')
this._header.setStatus('Up to date', 'success');
else if (checkedAt)
this._header.setStatus('Couldn\'t check for updates', 'warning');
else
this._header.setStatus(this._lastUpdate
? `Last updated ${Cli.timeAgo(this._lastUpdate)}` : 'Never updated', null);
// Check item: when it last looked
this._checkItem.description.text = checkedAt
? `Last checked ${Cli.timeAgo(checkedAt)}${this._lastUpdate
? ` · last updated ${Cli.timeAgo(this._lastUpdate)}` : ''}`
: 'See whether a newer CoreDesktop is out';
this._rebootItem.visible = this._rebootNeeded && !updating;
// Pills on the commands
const configuring = running.some(k => k === 'configure' || k.startsWith('configure-'));
for (const [key, item] of Object.entries(this._items)) {
if (this._running.has(key) || (key === 'configure' && configuring))
item.pill.setState('Running…', 'running');
else if (key === 'update' && state === 'available')
item.pill.setState('New version', 'accent');
else if (key === 'configure' && this._configureTodo > 0)
item.pill.setState(`${this._configureTodo} to do`, 'warning');
else if (key === 'configure' && this._configureItems.length > 0)
item.pill.setState('All set', 'success');
else
item.pill.setState(null);
}
// Top bar: pulse while updating, dot for an update or restart
this._panelIcon.remove_all_transitions();
this._panelIcon.opacity = 255;
if (updating) {
this._panelIcon.ease({
opacity: 90, duration: 900, autoReverse: true, repeatCount: -1,
mode: Clutter.AnimationMode.EASE_IN_OUT_SINE,
});
}
const badge = this._settings.get_boolean('show-badge') && !updating &&
(this._rebootNeeded || state === 'available');
this._badge.visible = badge;
this._badge.remove_style_class_name('warning');
if (this._rebootNeeded)
this._badge.add_style_class_name('warning');
let accessible = 'CoreDesktop';
if (updating)
accessible += ', updating';
else if (this._rebootNeeded)
accessible += ', restart needed';
else if (state === 'available')
accessible += ', update available';
this.accessible_name = accessible;
}
_runCommand(key) {
if (key === 'version') {
new VersionDialog({onUpdate: () => this._runCommand('update')}).open();
return;
}
if (key === 'refresh' && this._settings.get_boolean('confirm-refresh')) {
new ConfirmDialog({
title: 'Refresh CoreDesktop?',
description: 'Refresh runs CoreDesktop\'s installer again, so you get apps and services added since you installed.',
details: [
['folder-download-symbolic', 'Downloads the latest CoreDesktop'],
['system-software-install-symbolic', 'Installs anything new, and re-applies CoreDesktop\'s setup'],
['dialog-password-symbolic', 'Asks for your password, and can take several minutes'],
['software-update-available-symbolic', 'Run Update afterwards to bring everything up to date'],
],
confirmLabel: 'Refresh',
onConfirm: () => this._runTracked('refresh', 'Refresh', COMMANDS.refresh.argv),
}).open();
return;
}
const cmd = COMMANDS[key];
this._runTracked(key, cmd.title, cmd.argv);
}
// Run argv in a terminal, tracked under `name`
_runTracked(name, title, argv) {
if (this._running.has(name)) {
this._notify(`${title} is already running`, 'Look for its terminal window.');
return;
}
if ((name === 'update' || name === 'refresh') &&
(this._running.has('update') || this._running.has('refresh'))) {
this._notify('Wait for the current run to finish',
'Update and refresh both change the system, so run one at a time.');
return;
}
const ok = Cli.runInTerminal(this._ext.path, this._settings.get_string('terminal'),
name, [Cli.bin(argv[0]), ...argv.slice(1)]);
if (!ok) {
this._notify('No terminal found',
`Install a terminal, or open one and run: ${argv.join(' ')}`, 'error');
return;
}
// Shown as running right away; the status file confirms it shortly
this._titles.set(name, title);
this._running.set(name, 0);
this._launchedAt.set(name, GLib.get_monotonic_time());
this._updateIndicator();
this._pollWhileRunning();
}
// run-tracked writes <name>.status files: "running <pid>" or "exit <code>"
_watchStatusDir() {
GLib.mkdir_with_parents(Cli.STATUS_DIR, 0o700);
const dir = Gio.File.new_for_path(Cli.STATUS_DIR);
this._monitor = dir.monitor_directory(Gio.FileMonitorFlags.NONE, null);
this._monitor.connect('changed', () => this._scanSoon());
this._scanStatus(true);
}
_scanSoon() {
if (this._scanTimeout)
return;
this._scanTimeout = this._addTimeout(0.3, () => {
this._scanTimeout = 0;
this._scanStatus(false);
});
}
async _scanStatus(startup) {
const files = await Cli.listFiles(Gio.File.new_for_path(Cli.STATUS_DIR));
if (!this._header)
return;
const seen = new Set();
for (const file of files) {
const base = file.get_basename();
if (!base.endsWith('.status'))
continue;
const name = base.slice(0, -'.status'.length);
let text;
try {
const [bytes] = await file.load_contents_async(null);
text = new TextDecoder().decode(bytes).trim();
} catch {
continue;
}
const [what, value] = text.split(/\s+/);
if (what === 'running' && GLib.file_test(`/proc/${value}`, GLib.FileTest.EXISTS)) {
seen.add(name);
this._running.set(name, Number(value));
continue;
}
// Finished, or its window was killed: either way it's over
file.delete_async(GLib.PRIORITY_DEFAULT, null, null);
if (!startup && what === 'exit')
this._finished(name, Number(value));
}
// Launched but never started (the terminal failed), or gone without a trace
for (const [name, pid] of this._running) {
if (!seen.has(name) && (pid !== 0 || this._launchedLongAgo(name))) {
this._running.delete(name);
this._launchedAt.delete(name);
}
}
this._updateIndicator();
this._pollWhileRunning();
}
// run-tracked hasn't written its status a minute after the terminal was
// asked to open: the terminal must have failed
_launchedLongAgo(name) {
const at = this._launchedAt.get(name);
return at === undefined || GLib.get_monotonic_time() - at > 60e6;
}
// A window killed outright leaves "running" behind: look again now and then
_pollWhileRunning() {
if (this._running.size === 0 || this._pollTimeout)
return;
this._pollTimeout = this._addTimeout(5, () => {
this._pollTimeout = 0;
this._scanStatus(false);
});
}
_finished(name, code) {
this._running.delete(name);
this._launchedAt.delete(name);
const title = this._titles.get(name) ?? COMMANDS[name]?.title ?? name;
this._titles.delete(name);
if (name === 'update' && code === 0)
this._update = {state: 'current', version: null, checkedAt: GLib.get_real_time() / 1e6};
this._refreshLocal().then(() => {
if (!this._settings.get_boolean('notify-finished'))
return;
if (code === 0) {
const restart = (name === 'update' || name === 'refresh') && this._rebootNeeded;
this._notify(`${title} finished`,
restart ? 'Restart your computer to finish.' : 'Everything went through.',
'success', restart ? [['Restart now', () => this._restart()]] : []);
} else if (code === 129 || code === 130) {
this._notify(`${title} was stopped`, 'Its window was closed before it finished.', 'warning');
} else {
const actions = [['Open log', () => this._openLatestLog()]];
if (name === 'update' || name === 'refresh')
actions.push(['Report problem', () => this._runCommand('report')]);
this._notify(`${title} ran into problems`,
'Some steps failed. The log says which.', 'error', actions);
}
});
}
_restart() {
// GNOME's own restart dialog, with its countdown and cancel button
try {
Gio.Subprocess.new(['gnome-session-quit', '--reboot'], Gio.SubprocessFlags.NONE);
} catch {
Gio.Subprocess.new(['systemctl', 'reboot'], Gio.SubprocessFlags.NONE);
}
}
async _openLatestLog() {
const log = await Cli.newestLog();
if (!log) {
this._notify('No logs yet', 'Logs appear after the first update.');
return;
}
try {
Gio.AppInfo.launch_default_for_uri(log.get_uri(), global.create_app_launch_context(0, -1));
} catch (e) {
this._notify('Couldn\'t open the log', `${log.get_path()}: ${e.message}`, 'error');
}
}
_notify(title, body, kind = null, actions = []) {
if (!this._source) {
this._source = new MessageTray.Source({title: 'CoreDesktop', icon: this._gicon});
this._source.connect('destroy', () => {
this._source = null;
});
Main.messageTray.add(this._source);
}
const icons = {
success: 'emblem-ok-symbolic',
warning: 'dialog-warning-symbolic',
error: 'dialog-error-symbolic',
};
const notification = new MessageTray.Notification({
source: this._source,
title,
body,
gicon: icons[kind] ? new Gio.ThemedIcon({name: icons[kind]}) : this._gicon,
isTransient: kind === null,
});
for (const [label, callback] of actions)
notification.addAction(label, callback);
this._source.addNotification(notification);
}
_addTimeout(seconds, callback) {
const id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, Math.round(seconds * 1000), () => {
this._timeouts.delete(id);
callback();
return GLib.SOURCE_REMOVE;
});
this._timeouts.add(id);
return id;
}
destroy() {
this._settings.disconnectObject(this);
for (const id of this._timeouts)
GLib.source_remove(id);
this._timeouts.clear();
this._checkCancellable?.cancel();
this._monitor?.cancel();
this._monitor = null;
this._source?.destroy();
this._source = null;
this._header = null;
super.destroy();
}
});
export default class CoreDesktopExtension extends Extension {
enable() {
this._indicator = new Indicator(this);
Main.panel.addToStatusArea(this.uuid, this._indicator);
}
disable() {
this._indicator?.destroy();
this._indicator = null;
}
}
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<circle cx="3.5" cy="3.5" r="2" fill="#2e3436"/>
<path fill="#2e3436" d="M13.21 6.46A5.5 5.5 0 1 0 13.21 13.54L11.45 12.06A3.2 3.2 0 1 1 11.45 7.94Z"/>
</svg>

After

Width:  |  Height:  |  Size: 247 B

+210
View File
@@ -0,0 +1,210 @@
// Talking to CoreDesktop's command line tools: running them in the background
// to read their output, or in a terminal window for the user to follow.
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
Gio._promisify(Gio.Subprocess.prototype, 'communicate_utf8_async');
Gio._promisify(Gio.File.prototype, 'load_contents_async');
Gio._promisify(Gio.File.prototype, 'enumerate_children_async');
Gio._promisify(Gio.FileEnumerator.prototype, 'next_files_async');
const HOME = GLib.get_home_dir();
export const COREDESKTOP = GLib.build_filenamev([HOME, '.local', 'share', 'coredesktop']);
export const BIN = GLib.build_filenamev([HOME, '.local', 'bin']);
export const STATE = GLib.build_filenamev([HOME, '.local', 'state', 'coredesktop']);
export const LOGS = GLib.build_filenamev([STATE, 'logs']);
export const REBOOT_NEEDED = GLib.build_filenamev([STATE, 'reboot-needed']);
export const PACMAN_UPDATE_LOG = GLib.build_filenamev([STATE, 'pacman-update.log']);
export const STATUS_DIR = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'coredesktop-extension']);
// Terminals and how each runs a command, in the order CoreDesktop's
// system/run-in-terminal tries them
export const TERMINALS = {
'xdg-terminal-exec': [],
'kgx': ['--'],
'ghostty': ['-e'],
'kitty': [],
'ptyxis': ['--new-window', '--'],
'gnome-terminal': ['--'],
'alacritty': ['-e'],
};
export function stripAnsi(text) {
// eslint-disable-next-line no-control-regex
return text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/\r/g, '');
}
export function bin(name) {
return GLib.build_filenamev([BIN, name]);
}
export function isInstalled() {
return GLib.file_test(GLib.build_filenamev([COREDESKTOP, '.git']), GLib.FileTest.EXISTS);
}
// Run argv in the background. Resolves to {status, stdout, stderr}.
export async function run(argv, cancellable = null) {
const launcher = new Gio.SubprocessLauncher({
flags: Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE,
});
launcher.setenv('PATH', `${BIN}:${GLib.getenv('PATH') ?? '/usr/bin'}`, true);
// Commands such as version show a spinner and ask questions only on a
// terminal; make sure nothing thinks there's one
launcher.unsetenv('COREDESKTOP_TTY');
const proc = launcher.spawnv(argv);
const [stdout, stderr] = await proc.communicate_utf8_async(null, cancellable);
return {status: proc.get_exit_status(), stdout: stdout ?? '', stderr: stderr ?? ''};
}
// The version this machine is on, e.g. 2026.11.26 (01d2432)
export async function localVersion() {
try {
const {status, stdout} = await run(['git', '-C', COREDESKTOP, 'log', '-1',
'--format=%cd (%h)', '--date=format:%Y.%m.%d']);
return status === 0 ? stdout.trim() : null;
} catch {
return null;
}
}
// version --check: {state: 'available', version} | {state: 'current'} | {state: 'unknown'}
export async function checkForUpdate(cancellable) {
try {
const {status, stdout} = await run([bin('version'), '--check'], cancellable);
if (status === 0 && stdout.trim())
return {state: 'available', version: stdout.trim()};
if (status === 1)
return {state: 'current'};
} catch (e) {
if (e.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
throw e;
}
return {state: 'unknown'};
}
// configure --list, with each item's description from its configure.d file:
// [{name, title, description, done}]
export async function configureItems() {
const {status, stdout} = await run([bin('configure'), '--list']);
if (status !== 0)
return [];
const descriptions = await configureDescriptions();
const items = [];
for (const line of stdout.split('\n')) {
const m = line.match(/^(done|to do)\s+(\S+)\s+(.*)$/);
if (!m)
continue;
items.push({
done: m[1] === 'done',
name: m[2],
title: m[3].trim(),
description: descriptions.get(m[2]) ?? '',
});
}
return items;
}
async function configureDescriptions() {
const result = new Map();
const dir = Gio.File.new_for_path(GLib.build_filenamev([COREDESKTOP, 'configure.d']));
for (const file of await listFiles(dir)) {
const base = file.get_basename();
if (!base.endsWith('.sh'))
continue;
const name = base.replace(/\.sh$/, '').replace(/^\d\d-/, '');
try {
const [bytes] = await file.load_contents_async(null);
const text = new TextDecoder().decode(bytes);
const m = text.match(/^DESCRIPTION=(["'])(.*)\1\s*$/m);
if (m)
result.set(name, m[2]);
} catch {
// An unreadable item just goes without a description
}
}
return result;
}
export async function listFiles(dir) {
const files = [];
try {
const enumerator = await dir.enumerate_children_async('standard::name,time::modified',
Gio.FileQueryInfoFlags.NONE, GLib.PRIORITY_DEFAULT, null);
for (;;) {
const infos = await enumerator.next_files_async(50, GLib.PRIORITY_DEFAULT, null);
if (infos.length === 0)
break;
for (const info of infos) {
const file = dir.get_child(info.get_name());
file._mtime = info.get_modification_date_time()?.to_unix() ?? 0;
files.push(file);
}
}
} catch {
// A missing directory has no files
}
return files;
}
// The newest update or install log, or null
export async function newestLog() {
const files = (await listFiles(Gio.File.new_for_path(LOGS)))
.filter(f => f.get_basename().endsWith('.log'));
files.sort((a, b) => b._mtime - a._mtime);
return files[0] ?? null;
}
// Seconds since the epoch the file was last modified, or null
export function mtime(path) {
try {
const info = Gio.File.new_for_path(path).query_info('time::modified',
Gio.FileQueryInfoFlags.NONE, null);
return info.get_modification_date_time()?.to_unix() ?? null;
} catch {
return null;
}
}
export function findTerminal(preference) {
if (preference && preference !== 'auto') {
if (GLib.find_program_in_path(preference))
return [preference, ...(TERMINALS[preference] ?? ['-e'])];
}
for (const [name, args] of Object.entries(TERMINALS)) {
if (GLib.find_program_in_path(name))
return [name, ...args];
}
return null;
}
// Open a terminal window running `argv` under run-tracked, which records its
// progress as <name>.status in STATUS_DIR. The terminal runs as its own systemd
// unit so it outlives a GNOME Shell restart. Returns false if there's no terminal.
export function runInTerminal(extensionPath, preference, name, argv) {
const terminal = findTerminal(preference);
if (!terminal)
return false;
const tracked = GLib.build_filenamev([extensionPath, 'bin', 'run-tracked']);
const command = ['systemd-run', '--user', '--quiet', '--collect',
`--unit=coredesktop-${name}-${Date.now()}`, '--',
...terminal, 'bash', tracked, name, ...argv];
GLib.mkdir_with_parents(STATUS_DIR, 0o700);
Gio.Subprocess.new(command, Gio.SubprocessFlags.NONE);
return true;
}
// "just now", "5 minutes ago", "3 hours ago", "2 days ago"
export function timeAgo(unixSeconds) {
if (!unixSeconds)
return null;
const secs = Math.max(0, GLib.get_real_time() / 1e6 - unixSeconds);
const plural = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'} ago`;
if (secs < 60)
return 'just now';
if (secs < 3600)
return plural(Math.floor(secs / 60), 'minute');
if (secs < 86400)
return plural(Math.floor(secs / 3600), 'hour');
return plural(Math.floor(secs / 86400), 'day');
}
@@ -0,0 +1,267 @@
// Dialogs: the version report, and confirmations that say what a command will
// do before it runs.
import Clutter from 'gi://Clutter';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import Pango from 'gi://Pango';
import St from 'gi://St';
import * as Dialog from 'resource:///org/gnome/shell/ui/dialog.js';
import * as ModalDialog from 'resource:///org/gnome/shell/ui/modalDialog.js';
import * as Cli from './cli.js';
// Everything configure can set up, whether it's done, and a button to set each
// one up. items: [{name, title, description, done, icon, running}]
export const ConfigureDialog = GObject.registerClass(
class ConfigureDialog extends ModalDialog.ModalDialog {
_init({items, onConfigure, onOpenAll}) {
super._init({styleClass: 'coredesktop-dialog coredesktop-configure-dialog'});
const todo = items.filter(i => !i.done).length;
let description;
if (items.length === 0)
description = 'Couldn\'t read what configure can set up. Open it in a terminal instead.';
else if (todo === 0)
description = `All ${items.length} are set up. You can change any of them.`;
else
description = `${todo} of ${items.length} still to set up. Each opens a terminal that walks you through it.`;
this.contentLayout.add_child(new Dialog.MessageDialogContent({title: 'Configure CoreDesktop', description}));
const list = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL, style_class: 'coredesktop-configure-list'});
const sorted = [...items].sort((a, b) => Number(a.done) - Number(b.done));
for (const item of sorted) {
const row = new St.BoxLayout({style_class: 'coredesktop-configure-row'});
row.add_child(new St.Icon({
icon_name: item.icon,
style_class: 'coredesktop-configure-icon',
y_align: Clutter.ActorAlign.CENTER,
}));
const text = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
text.add_child(new St.Label({text: item.title, style_class: 'coredesktop-item-title'}));
text.add_child(new St.Label({text: item.description, style_class: 'coredesktop-item-description'}));
row.add_child(text);
let state, kind;
if (item.running)
[state, kind] = ['Running…', 'running'];
else if (item.done)
[state, kind] = ['Done', 'success'];
else
[state, kind] = ['To do', 'warning'];
row.add_child(new St.Label({
text: state,
style_class: `coredesktop-pill ${kind}`,
y_align: Clutter.ActorAlign.CENTER,
}));
const button = new St.Button({
label: item.done ? 'Change' : 'Set up',
style_class: `button coredesktop-configure-button${item.done ? '' : ' default'}`,
y_align: Clutter.ActorAlign.CENTER,
can_focus: true,
reactive: !item.running,
});
button.connect('clicked', () => {
this.close();
onConfigure(item);
});
row.add_child(button);
list.add_child(row);
}
const scroll = new St.ScrollView({
style_class: 'coredesktop-configure-scroll',
hscrollbar_policy: St.PolicyType.NEVER,
vscrollbar_policy: St.PolicyType.AUTOMATIC,
overlay_scrollbars: true,
});
scroll.set_child(list);
this.contentLayout.add_child(scroll);
this.setButtons([
{
label: 'Open in terminal',
action: () => {
this.close();
onOpenAll();
},
},
{label: 'Close', action: () => this.close(), key: Clutter.KEY_Escape, default: true},
]);
}
});
// Ask before running something. onConfirm runs if the user agrees.
export const ConfirmDialog = GObject.registerClass(
class ConfirmDialog extends ModalDialog.ModalDialog {
_init({title, description, details = [], confirmLabel, onConfirm}) {
super._init({styleClass: 'coredesktop-dialog'});
const content = new Dialog.MessageDialogContent({title, description});
this.contentLayout.add_child(content);
// What the command does, one line each with an icon, so it's easy to scan
if (details.length > 0) {
const list = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
style_class: 'coredesktop-detail-list',
});
for (const [iconName, text] of details) {
const row = new St.BoxLayout({style_class: 'coredesktop-detail-row'});
row.add_child(new St.Icon({icon_name: iconName, style_class: 'coredesktop-detail-icon'}));
const label = new St.Label({text, y_align: Clutter.ActorAlign.CENTER, x_expand: true});
label.clutter_text.line_wrap = true;
label.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
row.add_child(label);
list.add_child(row);
}
this.contentLayout.add_child(list);
}
this.setButtons([
{label: 'Cancel', action: () => this.close(), key: Clutter.KEY_Escape},
{
label: confirmLabel,
action: () => {
this.close();
onConfirm();
},
default: true,
},
]);
}
});
// Runs `version` and shows its report, with a button to update when there's
// something newer
export const VersionDialog = GObject.registerClass(
class VersionDialog extends ModalDialog.ModalDialog {
_init({onUpdate}) {
super._init({styleClass: 'coredesktop-dialog coredesktop-version-dialog'});
this._onUpdate = onUpdate;
this._cancellable = new Gio.Cancellable();
this._output = '';
this._content = new Dialog.MessageDialogContent({
title: 'CoreDesktop version',
description: 'Checking for newer versions of CoreDesktop, the kernel, the video driver and sibling projects…',
});
this.contentLayout.add_child(this._content);
this._report = new St.Label({style_class: 'coredesktop-version-report'});
this._report.clutter_text.line_wrap = false;
this._report.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
const scroll = new St.ScrollView({
style_class: 'coredesktop-version-scroll',
hscrollbar_policy: St.PolicyType.AUTOMATIC,
vscrollbar_policy: St.PolicyType.AUTOMATIC,
overlay_scrollbars: true,
});
const box = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
box.add_child(this._report);
scroll.set_child(box);
this.contentLayout.add_child(scroll);
this._report.text = 'Checking…';
this._report.ease({
opacity: 100, duration: 700, autoReverse: true, repeatCount: -1,
mode: Clutter.AnimationMode.EASE_IN_OUT_SINE,
});
this._setButtons(false);
this.connect('destroy', () => this._cancellable.cancel());
this._load();
}
_setButtons(updateAvailable) {
const buttons = [];
if (this._output) {
buttons.push({
label: 'Copy',
action: () => {
St.Clipboard.get_default().set_text(St.ClipboardType.CLIPBOARD, this._output);
this._content.description = 'Copied to the clipboard.';
},
});
}
if (updateAvailable) {
buttons.push({
label: 'Update now',
action: () => {
this.close();
this._onUpdate();
},
});
}
buttons.push({label: 'Close', action: () => this.close(), key: Clutter.KEY_Escape, default: true});
this.setButtons(buttons);
}
async _load() {
let text;
try {
const {stdout, stderr} = await Cli.run([Cli.bin('version')], this._cancellable);
text = Cli.stripAnsi(stdout || stderr).trimEnd();
} catch (e) {
if (e.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
return;
text = `Couldn't run version: ${e.message}`;
}
this._report.remove_all_transitions();
this._report.opacity = 255;
this._output = text;
const available = /is available/.test(text);
const stale = /mirror .* last synced/i.test(text);
this._content.description = available
? 'Newer versions are available. Update to install them.'
: 'Everything is up to date.';
if (stale)
this._content.description += ' Your package mirror is out of date; update switches to a fresher one.';
this._report.clutter_text.set_markup(markup(text));
this._setButtons(available);
}
});
// Bold the "Label value" names and highlight what's newer or needs attention
function markup(text) {
return text.split('\n').map(line => {
// "Video driver" has a single space before its value
let m = line.match(/^(CoreDesktop|Kernel|Video driver|Last update)(\s+)(.*)$/);
if (m)
return `<b>${esc(m[1])}</b>${esc(m[2])}${highlight(m[3])}`;
m = line.match(/^(\s+\S+)(\s{2,})(.*)$/);
if (m)
return `${esc(m[1])}${esc(m[2])}${highlight(m[3])}`;
if (/^Sibling projects$/.test(line))
return `<b>${esc(line)}</b>`;
if (/mirror|newer packages may be missing/.test(line))
return `<span foreground="#e5a50a">${esc(line)}</span>`;
return esc(line);
}).join('\n');
}
function highlight(value) {
// "2026.11.26 (01d2432), 2026.11.27 (abc1234) is available (run update)"
// Commas inside parentheses, as in "(newer kernel installed, reboot to use it)", don't split
const parts = value.split(/,\s*(?![^(]*\))/);
return parts.map(part => {
if (/is available/.test(part))
return `<span foreground="#3584e4" weight="bold">⬆ ${esc(part)}</span>`;
if (/reboot|couldn't check|modified/.test(part))
return `<span foreground="#e5a50a">${esc(part)}</span>`;
return esc(part);
}).join(', ');
}
function esc(s) {
return GLib.markup_escape_text(s, -1);
}
@@ -0,0 +1,9 @@
{
"uuid": "coredesktop@federated.computer",
"name": "CoreDesktop",
"description": "Run CoreDesktop's update, refresh, configure and version commands from the top bar, and see at a glance when an update is available, a restart is needed, or something still needs setting up.",
"shell-version": ["48", "49", "50", "51"],
"settings-schema": "org.gnome.shell.extensions.coredesktop",
"url": "https://federated.computer",
"version-name": "1.0"
}
+83
View File
@@ -0,0 +1,83 @@
import Adw from 'gi://Adw';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Gtk from 'gi://Gtk';
import {ExtensionPreferences} from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js';
const TERMINALS = ['auto', 'xdg-terminal-exec', 'kgx', 'ghostty', 'kitty', 'ptyxis', 'gnome-terminal', 'alacritty'];
const TERMINAL_NAMES = {
'auto': 'Automatic',
'xdg-terminal-exec': 'Default terminal (xdg-terminal-exec)',
'kgx': 'Console',
'ghostty': 'Ghostty',
'kitty': 'kitty',
'ptyxis': 'Ptyxis',
'gnome-terminal': 'GNOME Terminal',
'alacritty': 'Alacritty',
};
export default class CoreDesktopPreferences extends ExtensionPreferences {
fillPreferencesWindow(window) {
const settings = this.getSettings();
const page = new Adw.PreferencesPage({icon_name: 'preferences-system-symbolic'});
window.add(page);
// Updates
const updates = new Adw.PreferencesGroup({
title: 'Updates',
description: 'The extension asks CoreDesktop (version --check) whether a newer version is out.',
});
page.add(updates);
const interval = new Adw.SpinRow({
title: 'Check every',
subtitle: 'Hours between checks; 0 turns checking off',
adjustment: new Gtk.Adjustment({lower: 0, upper: 48, step_increment: 1, page_increment: 4}),
});
settings.bind('check-interval', interval, 'value', Gio.SettingsBindFlags.DEFAULT);
updates.add(interval);
const badge = new Adw.SwitchRow({
title: 'Show a dot on the top bar icon',
subtitle: 'Blue when an update is available, orange when a restart is needed',
});
settings.bind('show-badge', badge, 'active', Gio.SettingsBindFlags.DEFAULT);
updates.add(badge);
// Running commands
const running = new Adw.PreferencesGroup({
title: 'Running commands',
description: 'Update, refresh, configure, audit and report run in a terminal window, so you can follow them and type your password.',
});
page.add(running);
const available = TERMINALS.filter(t => t === 'auto' || GLib.find_program_in_path(t));
const current = settings.get_string('terminal');
if (!available.includes(current))
available.push(current);
const terminal = new Adw.ComboRow({
title: 'Terminal',
subtitle: 'Automatic uses the same one as CoreDesktop\'s notifications',
model: Gtk.StringList.new(available.map(t => TERMINAL_NAMES[t] ?? t)),
selected: available.indexOf(current),
});
terminal.connect('notify::selected', () =>
settings.set_string('terminal', available[terminal.selected]));
running.add(terminal);
const notify = new Adw.SwitchRow({
title: 'Notify when a command finishes',
subtitle: 'Says whether it worked, and offers to restart or open the log',
});
settings.bind('notify-finished', notify, 'active', Gio.SettingsBindFlags.DEFAULT);
running.add(notify);
const confirm = new Adw.SwitchRow({
title: 'Explain refresh before running it',
subtitle: 'Refresh re-runs the installer and takes a while',
});
settings.bind('confirm-refresh', confirm, 'active', Gio.SettingsBindFlags.DEFAULT);
running.add(confirm);
}
}
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<schemalist>
<schema id="org.gnome.shell.extensions.coredesktop" path="/org/gnome/shell/extensions/coredesktop/">
<key name="terminal" type="s">
<default>'auto'</default>
<summary>Terminal to run commands in</summary>
<description>auto picks the first of xdg-terminal-exec, kgx, ghostty, kitty, ptyxis, gnome-terminal and alacritty, like CoreDesktop's own run-in-terminal.</description>
</key>
<key name="check-interval" type="u">
<range min="0" max="48"/>
<default>4</default>
<summary>Hours between checks for a newer CoreDesktop (0 = never)</summary>
</key>
<key name="show-badge" type="b">
<default>true</default>
<summary>Show a dot on the top bar icon when an update is available or a restart is needed</summary>
</key>
<key name="notify-finished" type="b">
<default>true</default>
<summary>Show a notification when a command run from the menu finishes</summary>
</key>
<key name="confirm-refresh" type="b">
<default>true</default>
<summary>Explain what refresh does and ask before running it</summary>
</key>
</schema>
</schemalist>
@@ -0,0 +1,130 @@
/* Top bar: a dot in the icon's corner */
.coredesktop-badge {
width: 7px;
height: 7px;
border-radius: 4px;
margin: -1px -3px 0 0;
background-color: -st-accent-color;
}
.coredesktop-badge.warning {
background-color: #e5a50a;
}
.coredesktop-menu {
min-width: 380px;
}
/* Header */
.coredesktop-header {
spacing: 12px;
padding-top: 10px;
padding-bottom: 10px;
}
.coredesktop-header-icon {
icon-size: 32px;
}
.coredesktop-header-title {
font-weight: bold;
font-size: 1.15em;
}
.coredesktop-header-version {
font-family: monospace;
font-size: 0.9em;
}
.coredesktop-header-status {
font-size: 0.9em;
font-weight: bold;
}
.coredesktop-header-status.accent { color: -st-accent-color; }
.coredesktop-header-status.success { color: #26a269; }
.coredesktop-header-status.warning { color: #e5a50a; }
.coredesktop-header-status.error { color: #e01b24; }
/* Two-line items: what it is, then what it does */
.coredesktop-action-item {
spacing: 12px;
}
.coredesktop-action-icon {
icon-size: 20px;
}
.coredesktop-item-title {
font-weight: bold;
}
.coredesktop-item-description {
font-size: 0.85em;
opacity: 0.7;
}
.coredesktop-attention .coredesktop-action-icon {
color: #e5a50a;
}
/* Pills: New version, Running…, Done, To do */
.coredesktop-pill {
border-radius: 99px;
padding: 2px 9px;
font-size: 0.8em;
font-weight: bold;
}
.coredesktop-pill.accent,
.coredesktop-pill.running {
background-color: -st-accent-color;
color: -st-accent-fg-color;
}
.coredesktop-pill.success {
background-color: #26a269;
color: #ffffff;
}
.coredesktop-pill.warning {
background-color: #e5a50a;
color: #241f31;
}
.coredesktop-pill.error {
background-color: #c01c28;
color: #ffffff;
}
/* Dialogs */
.coredesktop-detail-list {
spacing: 10px;
padding: 0 24px 12px 24px;
}
.coredesktop-detail-row {
spacing: 12px;
}
.coredesktop-detail-icon {
icon-size: 18px;
color: -st-accent-color;
}
.coredesktop-configure-scroll {
max-height: 480px;
min-width: 620px;
margin: 0 12px 12px 12px;
}
.coredesktop-configure-list {
spacing: 4px;
}
.coredesktop-configure-row {
spacing: 12px;
padding: 8px 12px;
border-radius: 12px;
background-color: rgba(127, 127, 127, 0.08);
}
.coredesktop-configure-icon {
icon-size: 24px;
}
.coredesktop-configure-button {
padding: 6px 14px;
min-width: 64px;
}
.coredesktop-version-scroll {
height: 240px;
min-width: 680px;
margin: 0 24px 12px 24px;
padding: 12px;
border-radius: 12px;
background-color: rgba(127, 127, 127, 0.12);
}
.coredesktop-version-report {
font-family: monospace;
font-size: 0.9em;
}