蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

观察终端主题回退和导出的实际背景色

JAVASCRIPTWindows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。theme-colors-and-export.mjs
theme-colors-and-export.mjs166 行
import assert from 'node:assert/strict';
import {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
import {setTimeout as delay} from 'node:timers/promises';
import {tmpdir} from 'node:os';
import {basename, dirname, join, resolve} from 'node:path';
import {pathToFileURL} from 'node:url';

const modules = process.argv[2];
if (!modules) throw new Error('Supply the installed node_modules path.');
const packageDir = resolve(modules, '@earendil-works', 'pi-coding-agent');
const moduleUrl = name => pathToFileURL(join(packageDir, 'dist', 'modes', 'interactive', 'theme', name)).href;
const {THEME_TOKENS} = await import(moduleUrl('theme-tokens.js'));
const {validateThemeJson} = await import(moduleUrl('theme-schema.js'));
const {getAvailableThemes, getThemeExportColors, initTheme, loadThemeFromPath, onThemeChange,
  resolveThemeSetting, setRegisteredThemes, setThemeJsonValidator, stopThemeWatcher, SYSTEM_THEME_NAME, theme} =
  await import(moduleUrl('theme.js'));
const agentModule = name => import(pathToFileURL(join(packageDir, 'dist', name)).href);
const {DefaultResourceLoader, SessionManager, SettingsManager} = await agentModule('index.js');
const {colorToHex} = await import(pathToFileURL(resolve(modules, '@earendil-works', 'pi-tui', 'dist', 'index.js')).href);
const {exportSessionToHtml} = await agentModule('core/export-html/index.js');
const {version} = JSON.parse(await readFile(join(packageDir, 'package.json'), 'utf8'));
setThemeJsonValidator(validateThemeJson);
const required = Object.entries(THEME_TOKENS).filter(([, value]) => !value.fallback).map(([key]) => key);
const optional = Object.fromEntries(Object.entries(THEME_TOKENS).filter(([, value]) => value.fallback)
  .map(([name, value]) => [name, value.fallback]));
const results = [];
function check(name, input, expected, actual) {
  assert.deepStrictEqual(actual, expected, name);
  results.push({name, input, expected, actual, passed: true});
}
const base = resolve(tmpdir());
const folder = await mkdtemp(join(base, 'mbsky-pi-palette-'));
assert.equal(dirname(resolve(folder)), base);
assert.ok(basename(folder).startsWith('mbsky-pi-palette-'));
try {
  const themeFile = join(folder, 'night-study.json');
  const save = data => writeFile(themeFile, JSON.stringify(data), 'utf8');
  const draft = {
    name: 'night-study', appearance: 'dark', vars: {ink: '#bed6e5', highlight: 'ink'},
    colors: Object.fromEntries(required.map(name => [name, THEME_TOKENS[name].slot === 'background'
      ? '#202938' : 'ink'])),
  };
  Object.assign(draft.colors, {accent: 'highlight', muted: 242, text: '', thinkingXhigh: '#a873d1'});
  check('current_required_and_optional_tokens', {schema: 'Pi 1.5.0'},
    [51, {scrollbarTrack: 'muted', scrollbarThumb: 'text', searchMatchBg: 'selectedBg',
      searchMatchText: 'text', thinkingMax: 'thinkingXhigh'}],
    [required.length, optional]);
  await save(draft);
  const loaded = loadThemeFromPath(themeFile, 'truecolor');
  check('color_variables_and_indexed_ansi', {accent: 'highlight → ink', muted: 242},
    [true, true], [loaded.fg('accent', 'Q').includes('\x1b[38;2;190;214;229m'),
      loaded.fg('muted', 'Q').includes('\x1b[38;5;242m')]);
  for (const [token, descriptor] of Object.entries(THEME_TOKENS)) {
    const paint = descriptor.slot === 'background' ? loaded.bg.bind(loaded) : loaded.fg.bind(loaded);
    const ansi = paint(token, 'Q');
    const fallback = descriptor.fallback;
    const related = fallback ? paint(fallback, 'Q') : ansi;
    check('paint:' + token, {token, slot: descriptor.slot, fallback: fallback ?? null},
      [true, true], [ansi.includes('Q') && ansi.startsWith('\x1b['), ansi === related]);
  }
  check('missing_optional_tokens_follow_schema_fallbacks', {omitted: Object.keys(optional)},
    Object.values(optional).map(name => loaded.colors[name]), Object.keys(optional).map(name => loaded.colors[name]));
  check('terminal_default_uses_sgr_reset_foreground', {text: ''}, '\x1b[39mQ\x1b[39m', loaded.fg('text', 'Q'));
  const broken = structuredClone(draft);
  delete broken.colors.accent;
  await save(broken);
  assert.throws(() => loadThemeFromPath(themeFile, 'truecolor'), /Missing required color tokens:[\s\S]*accent/);
  results.push({name: 'missing_required_color_is_rejected', input: 'accent omitted',
    expected: 'Missing color accent', actual: 'Missing color accent', passed: true});
  const cycle = {...draft, vars: {ink: 'highlight', highlight: 'ink'}};
  await save(cycle);
  assert.throws(() => loadThemeFromPath(themeFile, 'truecolor'), /Circular variable reference/);
  results.push({name: 'cyclic_color_aliases_are_rejected', input: 'mutual variable references',
    expected: 'Circular variable reference', actual: 'Circular variable reference', passed: true});
  initTheme();
  check('default_system_and_explicit_automatic_pair', {setting: 'light/dark'},
    [SYSTEM_THEME_NAME, 'light', 'dark'], [theme.name, resolveThemeSetting('light/dark', 'light'),
      resolveThemeSetting('light/dark', 'dark')]);
  const getAnsi = value => value.match(/\x1b\[[0-9;]*m/)?.[0];
  await save({...draft, colors: {...draft.colors, accent: '#4ad', mdHeading: 'oklch(62% 0.1 200)',
    border: 'okhsl(250 60% 55%)'}});
  const modern = loadThemeFromPath(themeFile, 'truecolor');
  const reduced = loadThemeFromPath(themeFile, '256color');
  check('modern_formats_and_256_color_approximation', {values: ['#4ad','oklch','okhsl']},
    ['\x1b[38;2;68;170;221m', true, true, true],
    [getAnsi(modern.fg('accent', 'Q')), ...['mdHeading','border'].map(token => getAnsi(modern.fg(token, 'Q')).startsWith('\x1b[38;2;')),
      getAnsi(reduced.fg('accent', 'Q')).startsWith('\x1b[38;5;')]);

  const profile = join(folder, 'profile');
  const cwd = join(folder, 'reading-room');
  const profileThemes = join(profile, 'themes');
  const projectThemes = join(cwd, '.pi', 'themes');
  const packageThemes = join(folder, 'local-theme-package', 'themes');
  for (const dir of [profileThemes, projectThemes, packageThemes]) await mkdir(dir, {recursive: true});
  process.env.PI_CODING_AGENT_DIR = profile;
  const globalPath = join(profileThemes, 'night-study.json');
  const projectPath = join(projectThemes, 'room-only.json');
  const packagePath = join(packageThemes, 'bundle-color.json');
  const explicitPath = join(folder, 'extra-colors.json');
  await writeFile(globalPath, JSON.stringify(draft));
  await writeFile(projectPath, JSON.stringify({...draft, name: 'room-only'}));
  await writeFile(packagePath, JSON.stringify({...draft, name: 'bundle-color'}));
  await writeFile(join(folder, 'local-theme-package', 'package.json'), JSON.stringify({
    name: 'course-theme-fixture', version: '1.0.0', pi: {themes: ['./themes']},
  }));
  await writeFile(explicitPath, JSON.stringify({...draft, name: 'extra-colors'}));
  await writeFile(join(profile, 'settings.json'), JSON.stringify({
    theme: 'night-study', packages: [dirname(packageThemes)],
  }));
  const names = async trusted => {
    const settingsManager = SettingsManager.create(cwd, profile, {projectTrusted: trusted});
    const loader = new DefaultResourceLoader({cwd, agentDir: profile, settingsManager,
      additionalThemePaths: [explicitPath], noContextFiles: true, noExtensions: true, noSkills: true,
      noPromptTemplates: true, disabledBuiltinExtensions: ['mcp']});
    await loader.reload();
    return loader.getThemes().themes.map(t => t.name).sort();
  };
  check('built_in_theme_names_and_saved_preference', {profile: 'isolated'},
    [true, true, true, 'night-study'], ['system', 'dark', 'light'].map(name => getAvailableThemes().includes(name))
      .concat(SettingsManager.create(cwd, profile).getTheme()));
  check('loader_discovers_user_project_package_and_explicit', {projectTrusted: true},
    ['bundle-color', 'extra-colors', 'night-study', 'room-only'], await names(true));
  check('loader_omits_untrusted_project_theme', {projectTrusted: false},
    ['bundle-color', 'extra-colors', 'night-study'], await names(false));

  setRegisteredThemes([]);
  initTheme('night-study', true);
  const startColor = theme.colors.accent;
  let changeCount = 0;
  onThemeChange(() => { changeCount++; });
  const watchUpdate = {...draft, colors: {...draft.colors, accent: '#37cfaa'}};
  try {
    await writeFile(globalPath, JSON.stringify(watchUpdate));
    const deadline = Date.now() + 4000;
    while (changeCount === 0 && Date.now() < deadline) await delay(25);
    check('active_user_theme_reloads_on_disk_change', {file: 'profile/themes/night-study.json'},
      [true, true, '#37cfaa'], [changeCount > 0, startColor !== theme.colors.accent,
        colorToHex(theme.colors.accent)]);
  } finally {
    stopThemeWatcher();
  }
  const output = process.argv[3] ? resolve(process.argv[3]) : folder;
  const exportThemePath = join(profileThemes, 'export-study.json');
  const exportTheme = {...draft, name: 'export-study', export: {
    pageBg: '#172133', cardBg: '#243958', infoBg: '#31496e',
  }};
  await writeFile(exportThemePath, JSON.stringify(exportTheme));
  const plainTheme = {...draft, name: 'derived-study'};
  await writeFile(join(profileThemes, 'derived-study.json'), JSON.stringify(plainTheme));
  const fileSession = SessionManager.create(cwd, join(folder, 'session-output'));
  fileSession.appendMessage({role: 'user', content: 'Choose two labels for a reading room.', timestamp: Date.now()});
  await exportSessionToHtml(fileSession, undefined, {outputPath: join(output, 'explicit-palette.html'), themeName: 'export-study'});
  await exportSessionToHtml(fileSession, undefined, {outputPath: join(output, 'derived-palette.html'), themeName: 'derived-study'});
  const explicit = await readFile(join(output, 'explicit-palette.html'), 'utf8');
  const derived = await readFile(join(output, 'derived-palette.html'), 'utf8');
  const exportVars = content => Object.fromEntries([...content.matchAll(/--export(PageBg|CardBg|InfoBg):\s*([^;]+);/g)]
    .map(match => [match[1], match[2]]));
  check('html_contains_explicit_export_colors', {source: exportTheme.export},
    {PageBg: '#172133', CardBg: '#243958', InfoBg: '#31496e'}, exportVars(explicit));
  check('html_derives_unspecified_export_colors', {userMessageBg: '#202938'},
    {PageBg: 'rgb(22, 29, 39)', CardBg: 'rgb(27, 35, 48)', InfoBg: 'rgb(52, 56, 56)'}, exportVars(derived));
  process.stdout.write(JSON.stringify({nodeVersion: process.version, packageVersion: version, results}) + '\n');
} finally {
  await rm(folder, {recursive: true, force: true});
}
本例需在 Windows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。

入口文件:projects/pi-agent-themes-lab/theme-colors-and-export.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 theme-colors-and-export.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a290.zip

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习