Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
make shell terminal palette theme-aware so daytime themes read correctly
[._.]/ Adam Eivy1847caf4f652
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 70ff7e7dbe..40bfeb117d 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -115,5 +115,6 @@ grep -i "what you want to do" client/src/lib/README.md| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` / `daysBetween(date)` (cadence health: missing/overdue/soon/steady, plus an `external` state that never nags), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`. || `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |+| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. || `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex e04149d76f..bd03c75347 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -81,6 +81,7 @@ export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';export * from './syncCounts.js';+export * from './terminalTheme.js';export * from './tribe.js';export * from './universeBuilderExpand.js';export * from './wrSceneCursor.js';diff --git a/client/src/lib/terminalTheme.js b/client/src/lib/terminalTheme.jsnew file mode 100644index 0000000000..d76e33311f--- /dev/null+++ b/client/src/lib/terminalTheme.js@@ -0,0 +1,98 @@+// Pure helpers for building the xterm.js terminal palette from the active PortOS+// theme. Kept side-effect-free (no DOM reads) so it can be unit-tested; the Shell+// page reads CSS custom properties off the document and hands resolved colors in.+//+// The base 8 ANSI colors (red/green/yellow/blue) come from theme CSS vars so they+// track each theme's identity. The remaining slots are mode-tuned literals: the+// night palette is bright/pastel for dark backgrounds, while the day palette is+// darkened and saturated so colored CLI output stays legible on a light terminal+// background (the old single dark-tuned palette washed out in daytime themes).++// Bright/pastel ANSI slots tuned for dark backgrounds. `black`/`white` are null so+// the builder falls back to the theme's card/foreground (their dark-mode behavior).+export const ANSI_NIGHT = {+ black: null,+ magenta: '#a855f7',+ cyan: '#06b6d4',+ white: null,+ brightBlack: '#404040',+ brightRed: '#f87171',+ brightGreen: '#4ade80',+ brightYellow: '#fbbf24',+ brightBlue: '#60a5fa',+ brightMagenta: '#c084fc',+ brightCyan: '#22d3ee',+ brightWhite: '#ffffff',+};++// Darkened, saturated ANSI slots tuned for light backgrounds. `black`/`white` are+// explicit here (theme card is white in daytime themes, so it can't stand in for+// "black"), and the bright variants get *more* contrast — i.e. darker, not lighter.+export const ANSI_DAY = {+ black: '#1f2937',+ magenta: '#a21caf',+ cyan: '#0e7490',+ white: '#52525b',+ brightBlack: '#71717a',+ brightRed: '#b91c1c',+ brightGreen: '#15803d',+ brightYellow: '#a16207',+ brightBlue: '#1d4ed8',+ brightMagenta: '#86198f',+ brightCyan: '#155e75',+ brightWhite: '#27272a',+};++// Parse a CSS color value into a `#rrggbb` hex string. Handles both forms PortOS+// uses for theme variables: the space-separated RGB triple (`15 15 15`, used by+// the `--port-*` color vars) and the rgb()/rgba() function form (`rgb(7 7 7 / 0.86)`,+// used by the `--port-terminal-*` tokens). Alpha is dropped — xterm renders an+// opaque terminal. Returns `fallback` when the value is missing or unparseable.+export function parseCssColorToHex(raw, fallback = '#000000') {+ if (!raw) return fallback;+ const nums = String(raw)+ .replace(/rgba?\(|\)|\//g, ' ')+ .trim()+ .split(/[\s,]+/)+ .map(Number)+ .filter((n) => !Number.isNaN(n));+ if (nums.length < 3) return fallback;+ return (+ '#' ++ nums+ .slice(0, 3)+ .map((n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0'))+ .join('')+ );+}++// Build the xterm `theme` object from resolved theme colors and the active mode.+// colors: { bg, fg, accent, card, error, success, warning } — all #rrggbb hex+// mode: 'day' | 'night' (anything other than 'day' is treated as night)+export function buildTerminalTheme(colors, mode) {+ const { bg, fg, accent, card, error, success, warning } = colors;+ const ansi = mode === 'day' ? ANSI_DAY : ANSI_NIGHT;+ return {+ background: bg,+ foreground: fg,+ cursor: accent,+ cursorAccent: bg,+ selectionBackground: accent + (mode === 'day' ? '33' : '40'),+ black: ansi.black ?? card,+ red: error,+ green: success,+ yellow: warning,+ blue: accent,+ magenta: ansi.magenta,+ cyan: ansi.cyan,+ white: ansi.white ?? fg,+ brightBlack: ansi.brightBlack,+ brightRed: ansi.brightRed,+ brightGreen: ansi.brightGreen,+ brightYellow: ansi.brightYellow,+ brightBlue: ansi.brightBlue,+ brightMagenta: ansi.brightMagenta,+ brightCyan: ansi.brightCyan,+ brightWhite: ansi.brightWhite,+ };+}diff --git a/client/src/lib/terminalTheme.test.js b/client/src/lib/terminalTheme.test.jsnew file mode 100644index 0000000000..e6d1e24d26--- /dev/null+++ b/client/src/lib/terminalTheme.test.js@@ -0,0 +1,103 @@+import { describe, it, expect } from 'vitest';+import {+ ANSI_DAY,+ ANSI_NIGHT,+ buildTerminalTheme,+ parseCssColorToHex,+} from './terminalTheme.js';++const COLORS = {+ bg: '#fafafa',+ fg: '#171717',+ accent: '#2563eb',+ card: '#ffffff',+ error: '#dc2626',+ success: '#16a34a',+ warning: '#f59e0b',+};++describe('parseCssColorToHex', () => {+ it('parses the space-separated RGB triple form (--port-* color vars)', () => {+ expect(parseCssColorToHex('15 15 15')).toBe('#0f0f0f');+ expect(parseCssColorToHex('250 250 250')).toBe('#fafafa');+ });++ it('parses the rgb()/rgba() function form (--port-terminal-* tokens)', () => {+ expect(parseCssColorToHex('rgb(7 7 7)')).toBe('#070707');+ expect(parseCssColorToHex('rgb(247 247 248)')).toBe('#f7f7f8');+ });++ it('drops alpha from rgba()/slash-alpha forms', () => {+ expect(parseCssColorToHex('rgb(5 12 16 / 0.86)')).toBe('#050c10');+ expect(parseCssColorToHex('rgba(255, 255, 255, 0.85)')).toBe('#ffffff');+ });++ it('returns the fallback for missing or unparseable values', () => {+ expect(parseCssColorToHex('')).toBe('#000000');+ expect(parseCssColorToHex(undefined)).toBe('#000000');+ expect(parseCssColorToHex('not a color', '#abcdef')).toBe('#abcdef');+ expect(parseCssColorToHex('1 2', '#abcdef')).toBe('#abcdef');+ });++ it('clamps and rounds out-of-range / fractional channel values', () => {+ expect(parseCssColorToHex('300 -5 127.6')).toBe('#ff0080');+ });+});++describe('buildTerminalTheme', () => {+ it('drives base ANSI colors from the supplied theme colors in both modes', () => {+ for (const mode of ['day', 'night']) {+ const theme = buildTerminalTheme(COLORS, mode);+ expect(theme.background).toBe(COLORS.bg);+ expect(theme.foreground).toBe(COLORS.fg);+ expect(theme.cursor).toBe(COLORS.accent);+ expect(theme.red).toBe(COLORS.error);+ expect(theme.green).toBe(COLORS.success);+ expect(theme.yellow).toBe(COLORS.warning);+ expect(theme.blue).toBe(COLORS.accent);+ }+ });++ it('uses the dark-tuned night palette and falls back to card/fg for black/white', () => {+ const theme = buildTerminalTheme(COLORS, 'night');+ expect(theme.black).toBe(COLORS.card);+ expect(theme.white).toBe(COLORS.fg);+ expect(theme.magenta).toBe(ANSI_NIGHT.magenta);+ expect(theme.brightWhite).toBe(ANSI_NIGHT.brightWhite);+ expect(theme.brightBlack).toBe(ANSI_NIGHT.brightBlack);+ });++ it('uses the light-tuned day palette with explicit dark black/white', () => {+ const theme = buildTerminalTheme(COLORS, 'day');+ // On a light theme card is white, so "black" must NOT inherit it.+ expect(theme.black).toBe(ANSI_DAY.black);+ expect(theme.black).not.toBe(COLORS.card);+ expect(theme.white).toBe(ANSI_DAY.white);+ expect(theme.magenta).toBe(ANSI_DAY.magenta);+ expect(theme.brightWhite).toBe(ANSI_DAY.brightWhite);+ });++ it('treats any non-day mode as night', () => {+ expect(buildTerminalTheme(COLORS, undefined)).toEqual(buildTerminalTheme(COLORS, 'night'));+ expect(buildTerminalTheme(COLORS, 'whatever')).toEqual(buildTerminalTheme(COLORS, 'night'));+ });++ it('renders the day bright variants darker than their night counterparts (contrast on light bg)', () => {+ const day = buildTerminalTheme(COLORS, 'day');+ const night = buildTerminalTheme(COLORS, 'night');+ const luma = (hex) => {+ const r = parseInt(hex.slice(1, 3), 16);+ const g = parseInt(hex.slice(3, 5), 16);+ const b = parseInt(hex.slice(5, 7), 16);+ return 0.299 * r + 0.587 * g + 0.114 * b;+ };+ for (const key of ['brightRed', 'brightGreen', 'brightBlue', 'brightMagenta', 'brightCyan', 'brightWhite']) {+ expect(luma(day[key])).toBeLessThan(luma(night[key]));+ }+ });++ it('uses a lighter selection alpha for day mode', () => {+ expect(buildTerminalTheme(COLORS, 'day').selectionBackground).toBe(COLORS.accent + '33');+ expect(buildTerminalTheme(COLORS, 'night').selectionBackground).toBe(COLORS.accent + '40');+ });+});diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex 2fba9c62e2..375e2ea08f 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -5,9 +5,11 @@ import { FitAddon } from '@xterm/addon-fit';import { WebLinksAddon } from '@xterm/addon-web-links';import '@xterm/xterm/css/xterm.css';import { useSocket } from '../hooks/useSocket';+import { useThemeContext } from '../components/ThemeContext';import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown, Plus, X, Terminal as TerminalIcon, ClipboardPaste, OctagonX, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft, Bot } from 'lucide-react';import * as api from '../services/api';import { readClipboard } from '../lib/clipboard';+import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';// Must match MAX_TOTAL_SESSIONS in server/services/shell.jsconst MAX_SESSIONS = 20;@@ -46,13 +48,24 @@ const NAV_KEYS = [{ label: 'Enter', Icon: CornerDownLeft, seq: '\r' },];-// Read a CSS custom property as hex (e.g., '--port-bg' → '#0f0f0f')-const getThemeHex = (varName) => {- const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();- if (!raw) return '#000000';- const parts = raw.split(' ').map(Number);- if (parts.length !== 3) return '#000000';- return '#' + parts.map(n => n.toString(16).padStart(2, '0')).join('');+// Read the active theme's colors off the document and assemble the xterm palette.+// The day/night mode comes from the `data-port-theme-mode` attribute applyTheme()+// stamps on <html>, so this stays correct without threading React state in.+// Background/foreground prefer the dedicated --port-terminal-* tokens (hand-tuned+// per theme) and fall back to the page bg/text.+const readTerminalTheme = () => {+ const root = document.documentElement;+ const mode = root.dataset.portThemeMode === 'day' ? 'day' : 'night';+ const css = (varName) => getComputedStyle(root).getPropertyValue(varName).trim();+ return buildTerminalTheme({+ bg: parseCssColorToHex(css('--port-terminal-bg') || css('--port-bg'), '#070707'),+ fg: parseCssColorToHex(css('--port-terminal-text') || css('--port-text'), '#e5e5e5'),+ accent: parseCssColorToHex(css('--port-accent')),+ card: parseCssColorToHex(css('--port-card')),+ error: parseCssColorToHex(css('--port-error')),+ success: parseCssColorToHex(css('--port-success')),+ warning: parseCssColorToHex(css('--port-warning')),+ }, mode);};const formatAge = (createdAt) => {@@ -114,6 +127,8 @@ export default function Shell() {// Cleared by any user-initiated start/attach action.const userIdleRef = useRef(false);const socket = useSocket();+ const { themeId, theme: activeTheme } = useThemeContext();+ const themeMode = activeTheme?.mode ?? 'night';const [connected, setConnected] = useState(false);const [sessions, setSessions] = useState([]);const [activeSessionId, setActiveSessionId] = useState(null);@@ -206,42 +221,12 @@ export default function Shell() {useEffect(() => {if (!terminalRef.current || termInstanceRef.current) return;- const bg = getThemeHex('--port-bg');- const fg = getThemeHex('--port-text');- const accent = getThemeHex('--port-accent');- const card = getThemeHex('--port-card');- const error = getThemeHex('--port-error');- const success = getThemeHex('--port-success');- const warning = getThemeHex('--port-warning');-const term = new Terminal({cursorBlink: true,cursorStyle: 'block',fontSize: 14,fontFamily: '"Roboto Mono for Powerline", "MesloLGS NF", "MesloLGS Nerd Font", "Hack Nerd Font", "FiraCode Nerd Font", "JetBrainsMono Nerd Font", Menlo, Monaco, "Courier New", monospace',- theme: {- background: bg,- foreground: fg,- cursor: accent,- cursorAccent: bg,- selectionBackground: accent + '40',- black: card,- red: error,- green: success,- yellow: warning,- blue: accent,- magenta: '#a855f7',- cyan: '#06b6d4',- white: fg,- brightBlack: '#404040',- brightRed: '#f87171',- brightGreen: '#4ade80',- brightYellow: '#fbbf24',- brightBlue: '#60a5fa',- brightMagenta: '#c084fc',- brightCyan: '#22d3ee',- brightWhite: '#ffffff'- },+ theme: readTerminalTheme(),scrollback: 5000,allowProposedApi: true});@@ -268,6 +253,17 @@ export default function Shell() {};}, []);+ // Re-skin the live terminal when the user switches themes. The terminal is+ // created once (above), so without this the xterm palette would stay frozen at+ // whatever theme was active on mount — most visibly, a dark terminal stranded in+ // a daytime theme. Depends on themeId (catches sibling day↔day / night↔night+ // swaps that change accent/bg) and themeMode (catches the day/night palette flip).+ useEffect(() => {+ if (termInstanceRef.current) {+ termInstanceRef.current.options.theme = readTerminalTheme();+ }+ }, [themeId, themeMode]);+// Handle window resizeuseEffect(() => {const handleResize = () => {