@chatcode/cco-better-sidebar 0.18.0-alpha.4 → 0.18.0-rc.12

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 (87) hide show
  1. package/README.md +30 -9
  2. package/README_EN.md +30 -9
  3. package/cordis.patch.yml +6 -5
  4. package/lib/client-editor.js +10954 -395
  5. package/lib/client-mermaid.js +10835 -300
  6. package/lib/client-registry.js +4035 -2215
  7. package/lib/client-terminal.js +435 -292
  8. package/lib/client.js +4035 -2215
  9. package/lib/index.js +282 -47
  10. package/lib/types/client/LogoutConfirmDialog.d.ts +5 -0
  11. package/lib/types/client/PluginMarketSettingsSection.d.ts +7 -0
  12. package/lib/types/client/PluginMarketView.d.ts +7 -0
  13. package/lib/types/client/PluginProjectPicker.d.ts +13 -0
  14. package/lib/types/client/api.d.ts +21 -0
  15. package/lib/types/client/builtins/tabs.d.ts +13 -1
  16. package/lib/types/client/icons.d.ts +26 -8
  17. package/lib/types/client/locales-ja.d.ts +25 -0
  18. package/lib/types/client/locales.d.ts +39 -0
  19. package/lib/types/client/plugin-market-catalog.d.ts +25 -0
  20. package/lib/types/client/service.d.ts +1 -1
  21. package/lib/types/client/ui-tweaks/archive.d.ts +9 -28
  22. package/lib/types/client/ui-tweaks/branding.d.ts +1 -1
  23. package/lib/types/client/ui-tweaks/dom-text.d.ts +2 -0
  24. package/lib/types/client/ui-tweaks/index.d.ts +9 -1
  25. package/lib/types/client/ui-tweaks/sidebar-header.d.ts +6 -0
  26. package/lib/types/client/ui-tweaks/typography.d.ts +9 -0
  27. package/lib/types/config.d.ts +4 -3
  28. package/lib/types/context-types.d.ts +12 -14
  29. package/lib/types/login-page-script.d.ts +2 -0
  30. package/lib/types/login-route.d.ts +2 -0
  31. package/lib/types/plugin-market-api.d.ts +5 -0
  32. package/lib/types/plugin-market-shared.d.ts +59 -0
  33. package/lib/types/prefs-shared.d.ts +1 -1
  34. package/lib/types/pty-deps.d.ts +1 -1
  35. package/lib/types/ui-tweaks/config.d.ts +6 -7
  36. package/lib/types/ui-tweaks/index.d.ts +2 -3
  37. package/package.json +2 -2
  38. package/src/client/AccountMenu.tsx +12 -2
  39. package/src/client/BrowserView.tsx +1 -1
  40. package/src/client/DiffTab.tsx +1 -1
  41. package/src/client/EditorHost.tsx +1 -1
  42. package/src/client/FileTree.tsx +10 -5
  43. package/src/client/FreeWindow.tsx +2 -1
  44. package/src/client/GitView.tsx +7 -3
  45. package/src/client/LogoutConfirmDialog.tsx +39 -0
  46. package/src/client/PluginMarketSettingsSection.tsx +55 -0
  47. package/src/client/PluginMarketView.module.css +50 -0
  48. package/src/client/PluginMarketView.tsx +243 -0
  49. package/src/client/PluginProjectPicker.tsx +73 -0
  50. package/src/client/SideCardSection.tsx +2 -23
  51. package/src/client/Sidebar.tsx +2 -2
  52. package/src/client/TabBar.tsx +2 -4
  53. package/src/client/TextEditor.tsx +2 -1
  54. package/src/client/TreePanel.tsx +1 -2
  55. package/src/client/UsageHeatmapSection.tsx +1 -1
  56. package/src/client/api.ts +12 -0
  57. package/src/client/builtins/tabs.tsx +25 -5
  58. package/src/client/builtins/viewers.tsx +2 -1
  59. package/src/client/icons.tsx +57 -4
  60. package/src/client/index.tsx +10 -1
  61. package/src/client/intercept.tsx +1 -1
  62. package/src/client/locales-ja.ts +65 -0
  63. package/src/client/locales.ts +118 -1
  64. package/src/client/md-toc.tsx +1 -1
  65. package/src/client/mermaid.tsx +2 -1
  66. package/src/client/open-with-settings.tsx +1 -1
  67. package/src/client/plugin-market-catalog.ts +90 -0
  68. package/src/client/service.ts +1 -1
  69. package/src/client/sidebar.module.css +81 -19
  70. package/src/client/ui-tweaks/archive.tsx +118 -140
  71. package/src/client/ui-tweaks/branding.tsx +117 -49
  72. package/src/client/ui-tweaks/cachehit.tsx +24 -14
  73. package/src/client/ui-tweaks/dom-text.ts +12 -0
  74. package/src/client/ui-tweaks/index.tsx +75 -103
  75. package/src/client/ui-tweaks/sidebar-header.ts +73 -0
  76. package/src/client/ui-tweaks/typography.ts +38 -0
  77. package/src/config.ts +22 -2
  78. package/src/context-types.ts +5 -15
  79. package/src/index.ts +28 -21
  80. package/src/login-page-script.ts +107 -0
  81. package/src/login-route.ts +7 -4
  82. package/src/plugin-market-api.ts +88 -0
  83. package/src/plugin-market-shared.ts +30 -0
  84. package/src/prefs-shared.ts +1 -1
  85. package/src/pty-deps.ts +2 -2
  86. package/src/ui-tweaks/config.ts +12 -12
  87. package/src/ui-tweaks/index.ts +7 -13
package/src/index.ts CHANGED
@@ -21,7 +21,6 @@ import { WebSocket, WebSocketServer } from 'ws'
21
21
  import type { Context, SidebarHttpRequest } from './context-types.ts'
22
22
  import {
23
23
  Config,
24
- PrefsSchema,
25
24
  resolveSidebarConfig,
26
25
  SIDEBAR_PREFS_DEFAULTS,
27
26
  SIDEBAR_PREFS_NS,
@@ -52,9 +51,10 @@ import {
52
51
  import { registerTools } from './tools.ts'
53
52
  import { AgentOpenRegistry, registerOpenTool, type AgentOpenRequest } from './agent-opens.ts'
54
53
  import { CodingPlanCatalogue } from './codingplan.ts'
55
- import { checkOneUpdate, CHATCODE_UPDATE_PACKAGES, performAllUpdates } from './chatcode-update.ts'
54
+ import { checkOneUpdate, CHATCODE_CLI_PKG, CHATCODE_UPDATE_PACKAGES, installedGlobalVersion, performAllUpdates } from './chatcode-update.ts'
56
55
  import { readJsonBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
57
56
  import { apply as applyUiTweaksHost } from './ui-tweaks/index.ts'
57
+ import { buildPluginMarketApi } from './plugin-market-api.ts'
58
58
 
59
59
  export { Config }
60
60
  export type { SidebarConfig, ResolvedSidebarConfig }
@@ -492,6 +492,7 @@ function buildApi(
492
492
  const { sessionId, cwd } = await cwdOf(payload)
493
493
  return { sessionId, cwd, root: rootLabel(cwd), parent: parentOf(cwd) ?? null }
494
494
  },
495
+ ...buildPluginMarketApi(ctx, cwdOf),
495
496
  'fs.tree': async (payload) => {
496
497
  const { cwd } = await cwdOf(payload)
497
498
  const record = payload as { path?: unknown }
@@ -663,6 +664,9 @@ function buildApi(
663
664
  'chatcode.start': () => requireChatcodeAuth().startLogin(),
664
665
  'chatcode.cancel': payload => requireChatcodeAuth().cancelLogin(requireString(payload, 'sessionId')).then(() => ({ ok: true })),
665
666
  'chatcode.logout': () => requireChatcodeAuth().logout().then(() => ({ ok: true })),
667
+ // The globally installed CLI version the sidebar shows beside its wordmark.
668
+ // Reads npm global modules directly (no registry network like chatcode.update.check).
669
+ 'chatcode.installed-version': async () => ({ version: await installedGlobalVersion(CHATCODE_CLI_PKG) }),
666
670
  // Check both ChatCode packages (web runtime + CLI) against the npm
667
671
  // registry and the globally installed version. Runs on the DSH host; a
668
672
  // package not globally installed degrades to `current: null`.
@@ -829,9 +833,8 @@ function buildApi(
829
833
  * {@link resolveSidebarConfig}.
830
834
  */
831
835
  export function apply(ctx: Context, config?: SidebarConfig): void {
832
- // dsh-ui-tweaks is embedded as an intact feature module. Its historical
833
- // settings namespace and /_dsh/ui-tweaks routes stay unchanged so existing
834
- // settings.yaml values and browser behavior carry over without migration.
836
+ // dsh-ui-tweaks is embedded as an intact feature module. Its routes stay
837
+ // unchanged while its live fields share this entry's generated settings form.
835
838
  // Cordis honours the root `inject` list in production. Keeping this guard
836
839
  // lets lightweight embedders that call apply() directly retain the sidebar
837
840
  // subset when they intentionally omit the settings service.
@@ -886,8 +889,8 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
886
889
  void codingPlanCatalogue.refresh().catch(() => { /* catalogue returns a safe unavailable snapshot */ })
887
890
 
888
891
  // ── User-facing "Side card" preferences ──────────────────────────────────
889
- // Register the namespace with the settings provider so the Settings page
890
- // (client half) can render and persist the new-conversation defaults. The
892
+ // The Settings page (client half) renders and persists the
893
+ // new-conversation defaults from this entry's volatile Config fields. The
891
894
  // DSH settings RPC domain (api-proxy) only serves allowlisted namespaces to
892
895
  // configuration clients, so the client reaches this namespace through the
893
896
  // plugin's own fenced routes below ('settings.get'/'settings.update'),
@@ -921,17 +924,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
921
924
  }
922
925
  }
923
926
  ctx.inject(['settings'], (sctx) => {
924
- // DSH 0.1.2-alpha.2 validates namespaces at compile time
925
- // (SettingsNamespaceInput); the 'dsh-better-sidebar' literal passes, so the
926
- // runtime helper this used to call (settingsNamespace) is gone upstream.
927
927
  const ns = SIDEBAR_PREFS_NS
928
- // The structural settings mirror types `schema` as unknown, so the
929
- // generic is not inferred here; the real service resolves it from the
930
- // schemastery schema (PrefsSchema) — narrow the owner scope explicitly.
931
- const scope = sctx.settings.register(ns, PrefsSchema) as {
932
- get(): SidebarPrefs
933
- watch(callback: (next: SidebarPrefs, prev: SidebarPrefs) => void): () => void
934
- }
935
928
  const viewOf = (): { value?: unknown; revision?: number } => {
936
929
  const descriptor = sctx.settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === ns)
937
930
  return descriptor === undefined
@@ -957,6 +950,15 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
957
950
  return viewOf()
958
951
  },
959
952
  }
953
+ const scope = {
954
+ get: (): SidebarPrefs => {
955
+ const value = viewOf().value
956
+ return {
957
+ ...SIDEBAR_PREFS_DEFAULTS,
958
+ ...(typeof value === 'object' && value !== null ? value : {}),
959
+ } as SidebarPrefs
960
+ },
961
+ }
960
962
  // Register (or unregister) the terminal tools from the current setting,
961
963
  // and keep them in sync with every settings commit.
962
964
  syncToolsGate(scope)
@@ -988,10 +990,15 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
988
990
  }
989
991
  }
990
992
  syncOpenToolsGate()
991
- // ONE watch subscription drives both gates: settings commits re-evaluate
992
- // the terminal tools AND the open tool together (each gate is idempotent
993
- // and owns its own disposer).
994
- scope.watch(() => { syncToolsGate(scope); syncOpenToolsGate() })
993
+ // Volatile Config writes preserve the plugin fiber. Re-read the projected
994
+ // form after each Loader update so both gates track the committed values.
995
+ const updates = sctx as unknown as {
996
+ on(event: 'loader/volatile-update', listener: () => void): () => void
997
+ }
998
+ updates.on('loader/volatile-update', () => {
999
+ syncToolsGate(scope)
1000
+ syncOpenToolsGate()
1001
+ })
995
1002
  })
996
1003
 
997
1004
  // ── JSON API ────────────────────────────────────────────────────────────
@@ -0,0 +1,107 @@
1
+ /** Standalone sign-in recovery; each document starts once and always keeps a usable reopen action. */
2
+ export const CHATCODE_LOGIN_PAGE_SCRIPT = String.raw`
3
+ (() => {
4
+ const message = document.getElementById('message');
5
+ const button = document.getElementById('login');
6
+ const fallback = document.getElementById('login-fallback');
7
+ const link = document.getElementById('login-link');
8
+ const current = new URL(location.href);
9
+ const returnTo = (() => {
10
+ const value = current.searchParams.get('return');
11
+ if (!value || !value.startsWith('/') || value.startsWith('//')) return '/';
12
+ const target = new URL(value, location.origin);
13
+ return target.origin === location.origin ? target.pathname + target.search + target.hash : '/';
14
+ })();
15
+ let busy = false, checking = false, attempted = false, recheck = false, attempt, popup;
16
+ const call = async name => {
17
+ const response = await fetch('/sidebar/api/' + name, {
18
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}',
19
+ });
20
+ const data = await response.json();
21
+ if (!response.ok || !data.ok) throw new Error('操作失败');
22
+ return data.value;
23
+ };
24
+ const showMessage = (text, error = false) => {
25
+ message.textContent = text;
26
+ message.classList.toggle('error', error);
27
+ };
28
+ async function login() {
29
+ if (busy) return;
30
+ attempted = true;
31
+ busy = true;
32
+ button.disabled = true;
33
+ button.textContent = '正在打开登录页…';
34
+ let tab = null;
35
+ try { tab = window.open('', '_blank'); if (tab) tab.opener = null; } catch {}
36
+ try {
37
+ if (!attempt) {
38
+ const started = await call('chatcode.start');
39
+ const url = new URL(started.url);
40
+ if (!['http:', 'https:'].includes(url.protocol) || typeof started.sessionId !== 'string') throw new Error('登录地址无效');
41
+ attempt = { sessionId: started.sessionId, url: url.href };
42
+ }
43
+ link.href = attempt.url;
44
+ link.textContent = attempt.url;
45
+ fallback.hidden = false;
46
+ if (tab && !tab.closed) {
47
+ try { tab.location.href = attempt.url; popup = tab; } catch { try { tab.close(); } catch {} }
48
+ }
49
+ showMessage('请在登录页完成登录;若网页已关闭,可随时重新打开。');
50
+ } catch {
51
+ try { if (tab) tab.close(); } catch {}
52
+ showMessage('登录页打开失败,请重试。', true);
53
+ } finally {
54
+ busy = false;
55
+ button.disabled = false;
56
+ button.textContent = attempt ? '重新打开登录页' : '去登录';
57
+ }
58
+ }
59
+ async function status() {
60
+ if (checking || busy) return;
61
+ checking = true;
62
+ const observedAttempt = attempt, observedStarted = attempted;
63
+ try {
64
+ const state = await call('chatcode.status');
65
+ if (busy || attempt !== observedAttempt || attempted !== observedStarted) return;
66
+ if (state.available && state.validation === 'valid' && !state.expired) {
67
+ try { if (popup) popup.close(); window.focus(); } catch {}
68
+ location.replace(returnTo);
69
+ return;
70
+ }
71
+ if (!state.available) {
72
+ recheck = true;
73
+ button.textContent = '重新检测';
74
+ showMessage('登录服务暂不可用,请稍后重试。', true);
75
+ return;
76
+ }
77
+ if (state.configured && state.validation === 'unavailable') {
78
+ recheck = true;
79
+ button.textContent = '重新检测';
80
+ showMessage('暂时无法验证已有账号,请检查网络后重新检测。', true);
81
+ return;
82
+ }
83
+ recheck = false;
84
+ button.textContent = attempt ? '重新打开登录页' : '去登录';
85
+ if (attempt && (state.login?.sessionId !== attempt.sessionId || state.login.state !== 'pending')) {
86
+ attempt = undefined;
87
+ fallback.hidden = true;
88
+ link.removeAttribute('href');
89
+ link.textContent = '';
90
+ button.textContent = '去登录';
91
+ showMessage('登录请求已失效,请重新登录。');
92
+ }
93
+ if (!attempted) await login();
94
+ } catch {
95
+ recheck = true;
96
+ button.textContent = '重新检测';
97
+ showMessage('无法读取登录状态,请稍后重试。', true);
98
+ } finally {
99
+ checking = false;
100
+ if (!busy) button.disabled = false;
101
+ }
102
+ }
103
+ button.addEventListener('click', () => { void (recheck ? status() : login()); });
104
+ void status();
105
+ setInterval(() => { void status(); }, 2000);
106
+ })();
107
+ `
@@ -2,14 +2,17 @@ import { readFile } from 'node:fs/promises'
2
2
  import { dirname, join } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import type { Context, SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts'
5
+ import { CHATCODE_LOGIN_PAGE_SCRIPT } from './login-page-script.ts'
5
6
 
6
7
  const assetPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'logo.svg')
7
8
 
8
- function page(logo: string): string {
9
+ /** Render the standalone login gate with one automatic attempt and persistent manual recovery. */
10
+ export function renderChatcodeLoginPage(logo: string): string {
9
11
  return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>请登录 ChatCode</title><style>
10
12
  *{box-sizing:border-box}body{margin:0;min-width:320px;min-height:100vh;display:grid;place-items:center;font-family:Inter,"Microsoft YaHei",system-ui,sans-serif;color:#172b4d;background:radial-gradient(circle at 18% 18%,#e5edff 0,transparent 30rem),linear-gradient(135deg,#edf2fb,#dfe8f7)}.card{width:min(490px,calc(100vw - 40px));padding:34px 44px 36px;border:1px solid #dce4ef;border-radius:18px;background:#fff;box-shadow:0 20px 48px rgba(36,62,103,.18),0 2px 8px rgba(36,62,103,.06)}.brand{display:flex;align-items:center;justify-content:center;gap:12px;padding-bottom:27px;border-bottom:1px solid #edf0f5}.brand img{width:34px;height:34px}.brand strong{font-size:22px;letter-spacing:-.02em}.content{padding-top:40px;text-align:center}.content h1{margin:0;font-size:28px;line-height:1.3;font-weight:650}.content p{min-height:24px;margin:12px 0 30px;color:#71809a;font-size:14px;line-height:1.7}.action{width:100%;min-height:46px;border:0;border-radius:8px;background:#9B0B09;color:#fff;font:600 15px/1 Inter,"Microsoft YaHei",sans-serif;cursor:pointer;box-shadow:0 8px 18px rgba(155,11,9,.25);transition:transform .18s ease,box-shadow .18s ease,background .18s ease}.action:hover:not(:disabled){transform:translateY(-2px);background:#b20d0a;box-shadow:0 12px 24px rgba(155,11,9,.38)}.action:focus-visible{outline:3px solid #f0b7b5;outline-offset:3px}.action:disabled{cursor:default;opacity:.7}.error{color:#b42318}@media(max-width:480px){.card{padding:30px 26px}.content{padding-top:32px}}
11
- </style></head><body><main class="card"><div class="brand"><img src="data:image/svg+xml;base64,${logo}" alt=""><strong>ChatCode</strong></div><section class="content"><h1>请登录 ChatCode</h1><p id="message">请登录后继续使用。</p><button id="login" class="action" type="button">去登录</button></section></main><script>
12
- const message=document.getElementById('message'),button=document.getElementById('login');const current=new URL(location.href);const returnTo=(()=>{const v=current.searchParams.get('return');return v&&v.startsWith('/')&&!v.startsWith('//')?v:'/'} )();const call=async(name,body={})=>{const r=await fetch('/sidebar/api/'+name,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});const d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error?.message||'操作失败');return d.value};let waiting=false;async function status(){try{const s=await call('chatcode.status');if(s.available&&s.validation==='valid'&&!s.expired){location.replace(returnTo);return}if(waiting)message.textContent='正在等待浏览器完成登录…'}catch{message.textContent='无法读取登录状态,请稍后重试。';message.classList.add('error')}}async function login(){const tab=window.open('','_blank');button.disabled=true;button.textContent='正在打开登录页…';message.classList.remove('error');try{const s=await call('chatcode.start');waiting=true;if(tab&&!tab.closed){tab.opener=null;tab.location.href=s.url;message.textContent='请在新打开的浏览器窗口完成登录…'}else{message.innerHTML='浏览器拦截了登录窗口,请 <a href="'+s.url+'" target="_blank" rel="noopener noreferrer">打开登录页</a> 后完成登录。'}}catch{try{tab&&tab.close()}catch{}button.disabled=false;button.textContent='去登录';message.textContent='登录页打开失败,请重试。';message.classList.add('error')}}button.addEventListener('click',login);status();setInterval(status,2000);
13
+ .login-fallback{margin:18px 0 0;color:#71809a;font-size:12px;line-height:1.7;overflow-wrap:anywhere}.login-fallback a{display:block;margin-top:4px;color:#315da8;text-underline-offset:3px}
14
+ </style></head><body><main class="card"><div class="brand"><img src="data:image/svg+xml;base64,${logo}" alt=""><strong>ChatCode</strong></div><section class="content"><h1>请登录 ChatCode</h1><p id="message" aria-live="polite">正在检查登录状态…</p><button id="login" class="action" type="button" disabled>正在检查登录状态…</button><div id="login-fallback" class="login-fallback" hidden>若登录网页已关闭或未弹出,可再次访问:<a id="login-link" target="_blank" rel="noopener noreferrer"></a></div></section></main><script>
15
+ ${CHATCODE_LOGIN_PAGE_SCRIPT}
13
16
  </script></body></html>`
14
17
  }
15
18
 
@@ -20,7 +23,7 @@ export function registerLoginRoute(ctx: Context, fence: (req: SidebarHttpRequest
20
23
  try {
21
24
  const logo = (await readFile(assetPath)).toString('base64')
22
25
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': "default-src 'self'; img-src 'self' data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'" })
23
- res.end(req.method === 'HEAD' ? undefined : page(logo))
26
+ res.end(req.method === 'HEAD' ? undefined : renderChatcodeLoginPage(logo))
24
27
  } catch { res.writeHead(500); res.end('login page unavailable') }
25
28
  } })
26
29
  }
@@ -0,0 +1,88 @@
1
+ /** Shared config plugin routes inside the sidebar's existing trust fence. */
2
+ import type { Context } from './context-types.ts'
3
+ import { realpath, stat } from 'node:fs/promises'
4
+ import { isAbsolute } from 'node:path'
5
+ import type { PluginMarketService, PluginMarketScope, PluginProjectDirectories } from './plugin-market-shared.ts'
6
+ import { requireString, SidebarError } from './wire.ts'
7
+
8
+ interface DirectoryPicker {
9
+ capability(): { kind: 'native'; pick(signal: AbortSignal): Promise<string | null> }
10
+ | { kind: 'browse'; list(path?: string, signal?: AbortSignal): Promise<PluginProjectDirectories> }
11
+ }
12
+
13
+ export function buildPluginMarketApi(ctx: Pick<Context, 'get'>, cwdOf: (payload: unknown) => Promise<{ cwd: string }>): Record<string, (payload: unknown) => Promise<unknown>> {
14
+ const service = (): PluginMarketService => {
15
+ const value = ctx.get('chatcodePluginMarket', false) as PluginMarketService | undefined
16
+ if (!value) throw new SidebarError('chatcode-unavailable', '插件市场服务未挂载,请更新并启用 ChatCode config 插件。', 503)
17
+ return value
18
+ }
19
+ const scopeOf = (payload: unknown): PluginMarketScope => {
20
+ const scope = requireString(payload, 'scope')
21
+ if (scope !== 'project' && scope !== 'user') throw new SidebarError('bad-request', 'scope must be project or user')
22
+ return scope
23
+ }
24
+ const selectedProject = async (payload: unknown): Promise<string> => {
25
+ if (typeof (payload as { projectPath?: unknown } | null)?.projectPath !== 'string') throw new SidebarError('bad-request', '请先选择目标项目目录。')
26
+ const path = requireString(payload, 'projectPath')
27
+ const qualified = process.platform !== 'win32' || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(path)
28
+ if (!isAbsolute(path) || !qualified || path.includes('\0')) throw new SidebarError('bad-request', '请选择有效的项目目录。')
29
+ const canonical = await realpath(path)
30
+ if (!(await stat(canonical)).isDirectory()) throw new SidebarError('bad-request', '请选择项目文件夹。')
31
+ return canonical
32
+ }
33
+ const picker = () => {
34
+ const value = ctx.get('directoryPicker', false) as DirectoryPicker | undefined
35
+ if (!value) throw new SidebarError('method-error', '目录选择器未挂载,请启用宿主目录选择插件。', 503)
36
+ return value.capability()
37
+ }
38
+ // A sessionless settings page has no implicit project. Only user-scoped
39
+ // operations may use the launch cwd internally, which never becomes a target.
40
+ const contextOf = async (payload: unknown): Promise<{ sessionId: string; cwd?: string }> => {
41
+ const sessionId = (payload as { sessionId?: unknown } | null)?.sessionId
42
+ if (sessionId === undefined || sessionId === '') return { sessionId: '' }
43
+ requireString(payload, 'sessionId')
44
+ return { sessionId: sessionId as string, cwd: (await cwdOf(payload)).cwd }
45
+ }
46
+ const projectOf = async (payload: unknown): Promise<string | undefined> => {
47
+ if ((payload as { projectPath?: unknown } | null)?.projectPath !== undefined) return selectedProject(payload)
48
+ return (await contextOf(payload)).cwd
49
+ }
50
+ return {
51
+ 'plugins.context': contextOf,
52
+ 'plugins.project.pick': async () => {
53
+ const capability = picker()
54
+ if (capability.kind === 'browse') return { kind: 'browse' }
55
+ const path = await capability.pick(AbortSignal.timeout(120_000))
56
+ return { kind: 'native', path: path === null ? null : await selectedProject({ projectPath: path }) }
57
+ },
58
+ 'plugins.project.directories': async payload => {
59
+ const capability = picker()
60
+ if (capability.kind !== 'browse') throw new SidebarError('method-error', '当前宿主使用系统文件夹选择窗口。')
61
+ const path = (payload as { path?: unknown } | null)?.path
62
+ return capability.list(path === undefined ? undefined : requireString(payload, 'path'), AbortSignal.timeout(15_000))
63
+ },
64
+ 'plugins.marketplaces': () => service().marketplaces(),
65
+ 'plugins.catalog': async payload => {
66
+ const market = service()
67
+ const id = requireString(payload, 'marketplaceId')
68
+ if ((payload as { includeMetadata?: unknown }).includeMetadata !== true) return market.plugins(id)
69
+ return market.catalog ? market.catalog(id) : { plugins: await market.plugins(id), warning: '' }
70
+ },
71
+ 'plugins.installed': async payload => {
72
+ const project = await projectOf(payload)
73
+ const records = await service().installed(project ?? process.cwd())
74
+ return project ? records : records.filter(record => record.scope === 'user')
75
+ },
76
+ 'plugins.install': async payload => {
77
+ const scope = scopeOf(payload)
78
+ const project = scope === 'project' ? await selectedProject(payload) : await projectOf(payload)
79
+ return service().install(project ?? process.cwd(), requireString(payload, 'pluginId'), scope)
80
+ },
81
+ 'plugins.uninstall': async payload => {
82
+ const scope = scopeOf(payload)
83
+ const project = scope === 'project' ? await selectedProject(payload) : await projectOf(payload)
84
+ await service().uninstall(project ?? process.cwd(), requireString(payload, 'pluginId'), scope)
85
+ return { ok: true }
86
+ },
87
+ }
88
+ }
@@ -0,0 +1,30 @@
1
+ /** Credential-free structural contract of the config plugin's host service. */
2
+ export type PluginMarketScope = 'project' | 'user'
3
+ export interface PluginMarketplace { id: string; name: string; description: string; official: boolean }
4
+ export interface MarketplacePlugin { id: string; marketplaceId: string; name: string; description: string }
5
+ export interface InstalledMarketplacePlugin extends MarketplacePlugin {
6
+ scope: PluginMarketScope
7
+ projectPath: string
8
+ installPath: string
9
+ version: string
10
+ installedAt: string
11
+ }
12
+ export interface MarketplaceCatalog { marketplaces: PluginMarketplace[]; warning: string }
13
+ export interface PluginCatalog { plugins: MarketplacePlugin[]; warning: string }
14
+ /** Host-owned paths for the remote Web directory browser. */
15
+ export interface PluginProjectDirectories {
16
+ path: string
17
+ home: string
18
+ crumbs: Array<{ name: string; path: string; hidden: boolean }>
19
+ entries: Array<{ name: string; path: string; hidden: boolean }>
20
+ truncated: boolean
21
+ }
22
+ export type PluginProjectPick = { kind: 'native'; path: string | null } | { kind: 'browse' }
23
+ export interface PluginMarketService {
24
+ marketplaces(): Promise<MarketplaceCatalog>
25
+ plugins(marketplaceId: string): Promise<MarketplacePlugin[]>
26
+ catalog?(marketplaceId: string): Promise<PluginCatalog>
27
+ installed(cwd: string): Promise<InstalledMarketplacePlugin[]>
28
+ install(cwd: string, pluginId: string, scope: PluginMarketScope): Promise<InstalledMarketplacePlugin>
29
+ uninstall(cwd: string, pluginId: string, scope: PluginMarketScope): Promise<void>
30
+ }
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  /** The user-settings namespace holding the side card preferences. */
10
- export const SIDEBAR_PREFS_NS = 'dsh-better-sidebar'
10
+ export const SIDEBAR_PREFS_NS = 'better-sidebar'
11
11
 
12
12
  /** User-facing side card preferences (new-conversation defaults). */
13
13
  export interface SidebarPrefs {
package/src/pty-deps.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * agent terminal tools are simply not registered.
18
18
  *
19
19
  * Version contract: the plugin must stay in sync with DSH core —
20
- * `@deepseek-ai/dsh-subprocess-local` declares `"node-pty": "^1.1.0"` in
20
+ * `@deepseek-ai/dsh-subprocess-local` declares `"node-pty": "1.2.0-beta.15"` in
21
21
  * its `dependencies`. Both sides then resolve the SAME pnpm store entry
22
22
  * (same range, same integrity → one native binding, no drift). Do NOT
23
23
  * switch to a fork (e.g. @lydell/node-pty) or a different range without
@@ -39,7 +39,7 @@ export type NodePtyModule = typeof nodePtyNs
39
39
  * range DSH core declares (`@deepseek-ai/dsh-subprocess-local`): the same
40
40
  * range keeps pnpm resolving both to one physical package.
41
41
  */
42
- export const DSH_NODE_PTY_RANGE = '^1.1.0'
42
+ export const DSH_NODE_PTY_RANGE = '1.2.0-beta.15'
43
43
 
44
44
  /**
45
45
  * The WebSocket close-code-1011 reason the host sends when node-pty is
@@ -14,7 +14,7 @@ import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
14
14
  // `settingsNamespace()` was removed in DSH 0.1.2-alpha.2. Keep the opaque
15
15
  // namespace type for source compatibility with older DSH declarations, while
16
16
  // emitting the plain validated literal required by the current runtime.
17
- export const UI_TWEAKS_SETTINGS_NAMESPACE = 'ui-tweaks' as SettingsNamespace
17
+ export const UI_TWEAKS_SETTINGS_NAMESPACE = 'better-sidebar' as SettingsNamespace
18
18
 
19
19
  /** Raw user-facing configuration (partial inputs receive schema defaults). */
20
20
  export interface UITweaksConfig {
@@ -29,10 +29,9 @@ export interface UITweaksConfig {
29
29
  */
30
30
  codeFontScale?: number
31
31
  /**
32
- * Absolute code font size in px (8–32). 13 matches the stock DSH code block
33
- * at a 16px body. Drives the code block directly; inline code and the small
34
- * code font follow proportionally. When unset, falls back to the legacy
35
- * `codeFontScale` percentage, then to the stock default.
32
+ * Absolute code font size in px (8–32), default 13. Drives code blocks;
33
+ * inline code and small code follow proportionally. When unset, uses a non-default legacy
34
+ * `codeFontScale` percentage, otherwise 13px.
36
35
  */
37
36
  codeFontSize?: number
38
37
  /**
@@ -54,7 +53,7 @@ export interface UITweaksConfig {
54
53
  gitBarEnabled?: boolean
55
54
  /**
56
55
  * Whether the Archive manager is shown: the "归档" Settings page that lists
57
- * archived sessions and can restore or permanently delete them. Off by
56
+ * archived sessions and can restore or confirm permanent deletion through the shared Host. Off by
58
57
  * default; users turn it on in Settings.
59
58
  */
60
59
  archiveManagerEnabled?: boolean
@@ -114,7 +113,7 @@ export interface UITweaksConfig {
114
113
 
115
114
  export const MIN_FONT_SIZE = 10
116
115
  export const MAX_FONT_SIZE = 32
117
- export const DEFAULT_FONT_SIZE = 16
116
+ export const DEFAULT_FONT_SIZE = 14
118
117
 
119
118
  /** 16px matches the stock DSH vertical rhythm (message/block gaps, etc.). */
120
119
  export const MIN_LINE_HEIGHT = 0
@@ -126,7 +125,7 @@ export const MIN_CODE_FONT_SCALE = 50
126
125
  export const MAX_CODE_FONT_SCALE = 150
127
126
  export const DEFAULT_CODE_FONT_SCALE = 81
128
127
 
129
- /** Absolute code font size (px): 13 is the stock DSH code block at a 16px body. */
128
+ /** Default absolute code-block size, paired with 14px prose. */
130
129
  export const MIN_CODE_FONT_SIZE = 8
131
130
  export const MAX_CODE_FONT_SIZE = 32
132
131
  export const DEFAULT_CODE_FONT_SIZE = 13
@@ -164,7 +163,7 @@ export const DEFAULT_NOTIFY_SOUND = false
164
163
 
165
164
  /** Configuration schema with documented defaults. */
166
165
  export const Config: Schema<UITweaksConfig> = z.object({
167
- fontSize: z.number().min(10).max(32).default(16),
166
+ fontSize: z.number().min(10).max(32).default(DEFAULT_FONT_SIZE),
168
167
  codeFontScale: z.number().min(MIN_CODE_FONT_SCALE).max(MAX_CODE_FONT_SCALE).default(DEFAULT_CODE_FONT_SCALE),
169
168
  codeFontSize: z.number().min(MIN_CODE_FONT_SIZE).max(MAX_CODE_FONT_SIZE),
170
169
  lineHeight: z.number().min(MIN_LINE_HEIGHT).max(MAX_LINE_HEIGHT).default(DEFAULT_LINE_HEIGHT),
@@ -229,11 +228,12 @@ export interface ResolvedUITweaksConfig {
229
228
  export function resolveConfig(config: UITweaksConfig = {}): ResolvedUITweaksConfig {
230
229
  const fontSize = config.fontSize ?? DEFAULT_FONT_SIZE
231
230
  const codeFontScale = config.codeFontScale ?? DEFAULT_CODE_FONT_SCALE
232
- // Effective code size: the absolute px input wins; otherwise derive px from
233
- // the legacy percentage at the resolved body size; otherwise stock.
231
+ // Explicit code sizing wins; the stock preference keeps readable 13px code.
234
232
  const codeFontSize = typeof config.codeFontSize === 'number'
235
233
  ? Math.min(MAX_CODE_FONT_SIZE, Math.max(MIN_CODE_FONT_SIZE, config.codeFontSize))
236
- : Math.max(8, Math.round(fontSize * (13 / 16) * (codeFontScale / DEFAULT_CODE_FONT_SCALE)))
234
+ : codeFontScale === DEFAULT_CODE_FONT_SCALE
235
+ ? DEFAULT_CODE_FONT_SIZE
236
+ : Math.max(8, Math.round(fontSize * (13 / 16) * (codeFontScale / DEFAULT_CODE_FONT_SCALE)))
237
237
  const lineHeight = config.lineHeight ?? DEFAULT_LINE_HEIGHT
238
238
  const tableStyle = config.tableStyle ?? 'default'
239
239
  const gitBarEnabled = config.gitBarEnabled ?? DEFAULT_GITBAR_ENABLED
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * dsh-ui-tweaks — server half.
3
3
  *
4
- * Registers the `ui-tweaks` settings namespace so users can tune the
5
- * conversation UI either from the Settings panel or by editing the settings
6
- * document directly (settings.yaml `ui-tweaks:` section). All rendering work
4
+ * Uses the owning sidebar entry's live settings so users can tune the
5
+ * conversation UI from the Settings panel. All rendering work
7
6
  * happens in the browser bundle (`src/client`), which reads and writes this
8
7
  * namespace through the same-origin route mounted here — the Web settings RPC
9
8
  * only exposes a fixed allowlist of namespaces since rc.6, so a custom route is
@@ -12,11 +11,7 @@
12
11
  */
13
12
 
14
13
  import type { Context } from '@deepseek-ai/cordis'
15
- import {
16
- UI_TWEAKS_SETTINGS_NAMESPACE,
17
- Config,
18
- type UITweaksConfig,
19
- } from './config.ts'
14
+ import { UI_TWEAKS_SETTINGS_NAMESPACE, type UITweaksConfig } from './config.ts'
20
15
  import { installTurnOutcomeProjection } from './turn-outcome.ts'
21
16
  import { UITweaksWebBackend, installUITweaksWeb } from './web.ts'
22
17
  import { GitBackend } from './git.ts'
@@ -30,10 +25,6 @@ export const name = 'dsh-ui-tweaks'
30
25
  export const inject = ['settings']
31
26
 
32
27
  export function apply(ctx: Context): void {
33
- ctx.settings.register(UI_TWEAKS_SETTINGS_NAMESPACE, Config, {
34
- applies: 'live',
35
- })
36
-
37
28
  // The task notifier classifies turn endings (completed / aborted / failed)
38
29
  // through this session projection (same registration pattern as above).
39
30
  installTurnOutcomeProjection(ctx)
@@ -44,7 +35,10 @@ export function apply(ctx: Context): void {
44
35
 
45
36
  // The GitBar runs git in the session's working directory through these
46
37
  // same-origin routes (sessions/llm are optional services, duck-typed).
47
- const readConfig = (): UITweaksConfig => ctx.settings.get(UI_TWEAKS_SETTINGS_NAMESPACE) as UITweaksConfig
38
+ const readConfig = (): UITweaksConfig => {
39
+ const descriptor = ctx.settings.describe().find(candidate => candidate.ns === UI_TWEAKS_SETTINGS_NAMESPACE)
40
+ return descriptor?.value as UITweaksConfig | undefined ?? {}
41
+ }
48
42
  installGitWeb(ctx, new GitBackend(ctx, readConfig))
49
43
 
50
44
  // The Archive panel lists archived sessions and restores ("deletes") them