dsh-layers-hippocampus 1.9.9 → 1.9.21

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.
package/ui/client.js CHANGED
@@ -55,6 +55,8 @@
55
55
  layers: '/api/hippocampus/layers',
56
56
  // Escape hatch: reset a wedged rollover/handoff state.
57
57
  sessionReset: '/api/hippocampus/session/reset',
58
+ // v1.9.15: handoff → 「续接」(open a new conversation that continues it).
59
+ handoff: '/api/hippocampus/handoff',
58
60
  // Settings page: install the GitHub Orchestrator through the Host manager.
59
61
  orchestratorInstall: '/api/hippocampus/orchestrator/install',
60
62
  // v1.7.4: recent recall/capture events, used only to light up the graph.
@@ -70,6 +72,14 @@
70
72
  * so they cannot share React state.
71
73
  */
72
74
  const bus = new EventTarget();
75
+ /**
76
+ * v1.9.14: the tag rail lives in the drawer's head, the tag GRAPH lives inside the
77
+ * panel. They are siblings in the DOM today, but the rail must still drive the
78
+ * panel's own search — otherwise it is a second, decorative tag list ("it looks
79
+ * nothing like the original"). One module store + the bus, same pattern as
80
+ * `spaceStore`, keeps the two independent of React tree shape.
81
+ */
82
+ const tagFocusStore = { tag: null };
73
83
  const announce = (type) => {
74
84
  try {
75
85
  bus.dispatchEvent(new Event(type));
@@ -85,8 +95,7 @@
85
95
  // module-level store + the bus is the single source of truth. Every read
86
96
  // hook appends `?space=<id>` and the backend routes the request to that
87
97
  // physical store (routing isolation), so no view can blend two spaces.
88
- const spaceStore = { current: 'default' };
89
- const DEFAULT_SPACE_ID = 'default';
98
+ const spaceStore = { current: 'default' }; const DEFAULT_SPACE_ID = 'default';
90
99
  function getActiveSpace() {
91
100
  return spaceStore.current || DEFAULT_SPACE_ID;
92
101
  }
@@ -843,7 +852,10 @@
843
852
  height: size,
844
853
  viewBox: '0 0 24 24',
845
854
  fill: 'none',
846
- stroke: active ? palette.accent : 'currentColor',
855
+ // v1.9.18: `stroke` must be a STYLE, not an attribute: an SVG presentation
856
+ // attribute does not resolve `var(--dsh-*)`, so `stroke="var(--…)"` is an
857
+ // invalid colour and the glyph renders invisible (the blank tile).
858
+ style: { stroke: active ? palette.accent : 'currentColor' },
847
859
  strokeWidth: 1.8,
848
860
  strokeLinecap: 'round',
849
861
  strokeLinejoin: 'round',
@@ -856,6 +868,513 @@
856
868
  );
857
869
  }
858
870
 
871
+ // ---- sidebar entry: the PAIR, and the fallback ---------------------------
872
+ //
873
+ // CORRECTION (v1.9.16). v1.9.12 concluded that `sidebar.panellist` "does not
874
+ // exist in this DSH" and moved the entry to `sidebar.footer.action`. The live
875
+ // slot tree says otherwise: that seat is rendered and has eight active
876
+ // occupants (dsh-market ×2, workspace-control ×4, dsh-context, rice-guard).
877
+ //
878
+ // What was actually missing is the CONTRACT: a `sidebar.panellist` id is a
879
+ // panel ICON that addresses the `main` slot with the SAME id — the PAIR is the
880
+ // feature, one half alone is "an icon that does nothing". dsh-market registers
881
+ // exactly that pair (`main` key SIDEBAR_PANEL_ID + `panellist` id
882
+ // SIDEBAR_PANEL_ID) inside `slots.inject`, and additionally holds fallback
883
+ // seats, so a host without the seat degrades instead of going dark.
884
+ //
885
+ // This file therefore mounts the pair (icon + main panel) AND keeps the footer
886
+ // entry as a fallback that hides itself the moment the icon actually renders.
887
+ const MEMORY_PANEL_ID = 'hippocampus-panel';
888
+
889
+ /** Flipped by MemoryPanelIcon on mount: proof that the real icon rendered. */
890
+ const panelSeatStore = { supported: false, listeners: new Set() };
891
+
892
+ /**
893
+ * Flip the store, then notify AFTER the current render pass.
894
+ *
895
+ * The callback is reachable from a slot renderer, and a synchronous setState
896
+ * on another component during render is exactly the warning React logs.
897
+ */
898
+ function markPanelSeat() {
899
+ if (panelSeatStore.supported) return;
900
+ panelSeatStore.supported = true;
901
+ const notify = () => {
902
+ for (const listener of panelSeatStore.listeners) {
903
+ try {
904
+ listener();
905
+ } catch (error) {
906
+ report('panel seat listener', error);
907
+ }
908
+ }
909
+ };
910
+ try {
911
+ queueMicrotask(notify);
912
+ } catch (error) {
913
+ setTimeout(notify, 0);
914
+ }
915
+ }
916
+
917
+ function usePanelSeat() {
918
+ const [supported, setSupported] = React.useState(panelSeatStore.supported);
919
+ React.useEffect(() => {
920
+ const listener = () => setSupported(panelSeatStore.supported);
921
+ panelSeatStore.listeners.add(listener);
922
+ return () => panelSeatStore.listeners.delete(listener);
923
+ }, []);
924
+ return supported;
925
+ }
926
+
927
+ /**
928
+ * v1.9.19: an error boundary around the panel.
929
+ *
930
+ * "The panel appears and vanishes in the same frame" is not a styling bug: the
931
+ * owner unmounts the occupant as soon as our render throws, so the previous
932
+ * build showed a flash of banner and then a blank main column with no message
933
+ * anywhere. A boundary turns that into visible text.
934
+ *
935
+ * Built lazily because a test double may not implement React.Component.
936
+ */
937
+ const PanelErrorBoundary = (() => {
938
+ if (!React || typeof React.Component !== 'function') return null;
939
+ return class PanelErrorBoundary extends React.Component {
940
+ constructor(props) {
941
+ super(props);
942
+ this.state = { error: null };
943
+ }
944
+
945
+ static getDerivedStateFromError(error) {
946
+ return { error };
947
+ }
948
+
949
+ componentDidCatch(error) {
950
+ report('memory panel render', error);
951
+ }
952
+
953
+ render() {
954
+ if (this.state.error) {
955
+ const error = this.state.error;
956
+ return h(
957
+ 'div',
958
+ { style: { padding: 16, fontFamily: 'ui-monospace, monospace', fontSize: 12, color: '#d9534f' } },
959
+ h('div', { style: { fontWeight: 700, marginBottom: 6 } }, '海马体面板渲染失败'),
960
+ h('div', null, `${(error && error.name) || 'Error'}: ${(error && error.message) || String(error)}`),
961
+ h('pre', { style: { marginTop: 8, whiteSpace: 'pre-wrap', opacity: 0.75 } }, String((error && error.stack) || '').slice(0, 1200)),
962
+ );
963
+ }
964
+ return this.props.children;
965
+ }
966
+ };
967
+ })();
968
+
969
+ /** The `main` half of the pair: the panel a sidebar icon dispatches. */
970
+ function MemoryPanelHost() {
971
+ return h(
972
+ 'div',
973
+ { style: { height: '100%', minHeight: 0, overflow: 'auto' } },
974
+ PanelErrorBoundary ? h(PanelErrorBoundary, null, h(MemoryPanel)) : h(MemoryPanel),
975
+ );
976
+ }
977
+
978
+ /**
979
+ * The `sidebar.panellist` half.
980
+ *
981
+ * HOOK-FREE on purpose. This shell may invoke a slot renderer as a plain
982
+ * function (dsh-market's own icon is hook-free too); a hook there throws
983
+ * "Invalid hook call", the tile renders empty, and nothing downstream ever
984
+ * learns the seat worked — which is precisely how 1.9.16 first shipped a
985
+ * blank icon plus a footer button that refused to hide.
986
+ */
987
+ function MemoryPanelIcon(owner = {}) {
988
+ markPanelSeat();
989
+ return h(MemoryIcon, {
990
+ size: owner && owner.size ? owner.size : 16,
991
+ active: owner ? owner.active === true : false,
992
+ });
993
+ }
994
+
995
+ // The fallback: a footer action (hidden once the real icon renders) and the
996
+ // sheet it opens. Two components share one open state through this store.
997
+ const memoryPanelStore = { open: false, listeners: new Set() };
998
+
999
+ function setMemoryPanelOpen(next) {
1000
+ const value = next === true;
1001
+ if (memoryPanelStore.open === value) return;
1002
+ memoryPanelStore.open = value;
1003
+ for (const listener of memoryPanelStore.listeners) {
1004
+ try {
1005
+ listener(value);
1006
+ } catch (error) {
1007
+ report('memory panel listener', error);
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ function useMemoryPanelOpen() {
1013
+ const [open, setOpen] = React.useState(memoryPanelStore.open);
1014
+ React.useEffect(() => {
1015
+ const listener = () => setOpen(memoryPanelStore.open);
1016
+ memoryPanelStore.listeners.add(listener);
1017
+ return () => memoryPanelStore.listeners.delete(listener);
1018
+ }, []);
1019
+ return open;
1020
+ }
1021
+
1022
+ /** The FALLBACK entry: hidden while the real sidebar icon renders. */
1023
+ function SidebarMemoryAction() {
1024
+ const open = useMemoryPanelOpen();
1025
+ const seat = usePanelSeat();
1026
+ if (seat) return null;
1027
+ return h(
1028
+ 'button',
1029
+ {
1030
+ type: 'button',
1031
+ title: '海马体记忆:打开面板(Esc 关闭)',
1032
+ 'aria-label': '海马体记忆',
1033
+ 'aria-expanded': open ? 'true' : 'false',
1034
+ onClick: () => setMemoryPanelOpen(!memoryPanelStore.open),
1035
+ style: {
1036
+ display: 'inline-flex',
1037
+ alignItems: 'center',
1038
+ gap: 6,
1039
+ padding: '5px 9px',
1040
+ background: open ? 'var(--dsh-surface-raised, rgba(127,127,127,0.12))' : 'transparent',
1041
+ border: 'none',
1042
+ borderRadius: 8,
1043
+ color: palette.text,
1044
+ cursor: 'pointer',
1045
+ font: 'inherit',
1046
+ },
1047
+ },
1048
+ h(MemoryIcon, { size: 16, active: open }),
1049
+ h('span', { style: { fontSize: 12 } }, '记忆'),
1050
+ );
1051
+ }
1052
+
1053
+ // ---- v1.9.15 续接(handoff → new conversation) ---------------------------
1054
+ //
1055
+ // v1.5.6 shipped a controller that opened a new conversation BY ITSELF when a
1056
+ // handoff fired; v1.6.3 deleted it (it fired mid-conversation and threw the
1057
+ // person into an empty second conversation). This is the deliberate half: one
1058
+ // button, visible only while a handoff summary is worth continuing, and the
1059
+ // click does exactly what the "+" button does — the Host's own
1060
+ // `uiWorkspace.startSession`. No polling controller, no timer that switches
1061
+ // the screen under you.
1062
+ const RESUME_POLL_MS = 20000;
1063
+ /** A marker older than this is no longer "continue where you left off". */
1064
+ const RESUME_WINDOW_MS = 72 * 60 * 60 * 1000;
1065
+ /** The Cordis context, kept for click-time service lookup (components render later). */
1066
+ let hostContext = null;
1067
+
1068
+ function resumeWanted(view, now = Date.now()) {
1069
+ if (!view || view.resumeAvailable !== true) return false;
1070
+ if (view.active !== true && view.nextSessionRequired !== true) return false;
1071
+ const at = Number(view.at);
1072
+ return !Number.isFinite(at) || at <= 0 || now - at <= RESUME_WINDOW_MS;
1073
+ }
1074
+
1075
+ /**
1076
+ * Polls the tiny /handoff view. Deliberately NOT the /stats payload: the panel
1077
+ * payload is heavy, and this button sits in the sidebar whether the panel is
1078
+ * open or closed.
1079
+ */
1080
+ function useHandoffResume() {
1081
+ const [view, setView] = React.useState(null);
1082
+ React.useEffect(() => {
1083
+ let alive = true;
1084
+ let timer = null;
1085
+ const tick = async () => {
1086
+ try {
1087
+ const { body, hasJson } = await getJson(API.handoff);
1088
+ if (alive && hasJson && body && typeof body === 'object') setView(body.handoff ?? null);
1089
+ } catch (error) {
1090
+ // An older Host without this route must never break the sidebar.
1091
+ }
1092
+ if (alive) timer = setTimeout(tick, RESUME_POLL_MS);
1093
+ };
1094
+ tick();
1095
+ return () => {
1096
+ alive = false;
1097
+ if (timer) clearTimeout(timer);
1098
+ };
1099
+ }, []);
1100
+ return view;
1101
+ }
1102
+
1103
+ function SidebarResumeButton() {
1104
+ const view = useHandoffResume();
1105
+ const [busy, setBusy] = React.useState(false);
1106
+ const [note, setNote] = React.useState(null);
1107
+ if (!resumeWanted(view)) return null;
1108
+ const start = () => {
1109
+ const workspace = hostContext && typeof hostContext.get === 'function' ? hostContext.get('uiWorkspace') : null;
1110
+ if (!workspace || typeof workspace.startSession !== 'function') {
1111
+ setNote('宿主未提供 uiWorkspace.startSession');
1112
+ return;
1113
+ }
1114
+ setBusy(true);
1115
+ try {
1116
+ const options = {};
1117
+ if (view.agentPreset) options.agentPreset = view.agentPreset;
1118
+ // Only when the Host will NOT cold-start inject the same text.
1119
+ if (typeof view.prompt === 'string' && view.prompt.length > 0) options.prompt = view.prompt;
1120
+ workspace.startSession(undefined, Object.keys(options).length > 0 ? options : undefined);
1121
+ } catch (error) {
1122
+ setNote(String((error && error.message) || error));
1123
+ } finally {
1124
+ setBusy(false);
1125
+ }
1126
+ };
1127
+ return h(
1128
+ 'button',
1129
+ {
1130
+ type: 'button',
1131
+ title: note
1132
+ ? `续接失败:${note}`
1133
+ : view.coldStartWillInject
1134
+ ? '本会话已交接:开一个新会话继续(摘要与前几轮原话由冷启动自动注入)'
1135
+ : '本会话已交接:开一个新会话继续,并把交接摘要写进草稿',
1136
+ 'aria-label': '续接',
1137
+ onClick: start,
1138
+ disabled: busy,
1139
+ style: {
1140
+ ...smallButtonStyle,
1141
+ marginBottom: 0,
1142
+ display: 'inline-flex',
1143
+ alignItems: 'center',
1144
+ gap: 4,
1145
+ },
1146
+ },
1147
+ h('span', { style: { fontSize: 12 } }, busy ? '续接中…' : '续接'),
1148
+ );
1149
+ }
1150
+
1151
+ // ---- v1.9.13 tag rail ---------------------------------------------------
1152
+ //
1153
+ // The rail lives INSIDE the memory panel because `sidebar.panellist` is an
1154
+ // ICON rail (one icon per panel id), not a list host: the shell renders the
1155
+ // icon there and the content in the `main` panel. The rail is a real browser —
1156
+ // counts come from the same /memories projection the panel uses, and clicking
1157
+ // a tag narrows the list. The preference persists per browser.
1158
+ const TAG_RAIL_KEY = 'hippocampus:tag-rail';
1159
+ function readTagRail() {
1160
+ try {
1161
+ return window.localStorage.getItem(TAG_RAIL_KEY) !== 'off';
1162
+ } catch (error) {
1163
+ return true;
1164
+ }
1165
+ }
1166
+ function writeTagRail(on) {
1167
+ try {
1168
+ window.localStorage.setItem(TAG_RAIL_KEY, on ? 'on' : 'off');
1169
+ } catch (error) {
1170
+ /* a private-mode browser keeps the choice for this page only */
1171
+ }
1172
+ }
1173
+
1174
+ function TagRail(props) {
1175
+ const { enabled, spaceId = null, onPick = null, pick = null } = props || {}; const [tags, setTags] = React.useState([]);
1176
+ const [error, setError] = React.useState(null);
1177
+ React.useEffect(() => {
1178
+ if (!enabled) return undefined;
1179
+ let alive = true;
1180
+ const load = () => {
1181
+ getJson(`${API.memories}?limit=200${spaceId ? `&space=${encodeURIComponent(spaceId)}` : ''}`)
1182
+ .then(({ body }) => {
1183
+ if (!alive) return;
1184
+ const rows = (body && body.memories) || [];
1185
+ const counts = new Map();
1186
+ for (const row of rows) {
1187
+ for (const tag of row.tags || []) counts.set(tag, (counts.get(tag) || 0) + 1);
1188
+ }
1189
+ setTags([...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 40));
1190
+ setError(null);
1191
+ })
1192
+ .catch((caught) => {
1193
+ if (alive) setError(String((caught && caught.message) || caught));
1194
+ });
1195
+ };
1196
+ load();
1197
+ bus.addEventListener('config-changed', load);
1198
+ return () => {
1199
+ alive = false;
1200
+ bus.removeEventListener('config-changed', load);
1201
+ };
1202
+ }, [enabled, spaceId]);
1203
+
1204
+ if (!enabled) return null;
1205
+ return h(
1206
+ 'div',
1207
+ {
1208
+ style: {
1209
+ width: 208,
1210
+ flexShrink: 0,
1211
+ borderRight: `1px solid ${palette.border}`,
1212
+ padding: '10px 10px 16px',
1213
+ overflow: 'auto',
1214
+ display: 'flex',
1215
+ flexDirection: 'column',
1216
+ gap: 4,
1217
+ },
1218
+ },
1219
+ h('div', { style: { ...labelStyle, display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
1220
+ h('span', null, `标签(${tags.length})`),
1221
+ pick ? h('button', { type: 'button', style: smallButtonStyle, onClick: () => onPick?.(null) }, '清除') : null,
1222
+ ),
1223
+ error ? h('div', { style: { fontSize: 11, color: palette.warn } }, error) : null,
1224
+ tags.length === 0 && !error
1225
+ ? h('div', { style: { fontSize: 11, color: palette.muted } }, '暂无标签')
1226
+ : null,
1227
+ tags.map(([tag, count]) => {
1228
+ const active = pick === tag;
1229
+ return h(
1230
+ 'button',
1231
+ {
1232
+ key: tag,
1233
+ type: 'button',
1234
+ onClick: () => onPick?.(active ? null : tag),
1235
+ title: `按「${tag}」筛选(${count} 条)`,
1236
+ style: {
1237
+ display: 'flex',
1238
+ justifyContent: 'space-between',
1239
+ gap: 6,
1240
+ padding: '3px 6px',
1241
+ background: active ? 'var(--dsh-surface-raised, rgba(127,127,127,0.16))' : 'transparent',
1242
+ border: 'none',
1243
+ borderRadius: 6,
1244
+ color: active ? palette.accent : palette.text,
1245
+ cursor: 'pointer',
1246
+ fontSize: 11,
1247
+ textAlign: 'left',
1248
+ overflow: 'hidden',
1249
+ },
1250
+ },
1251
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, tag),
1252
+ h('span', { style: { color: palette.muted } }, String(count)),
1253
+ );
1254
+ }),
1255
+ );
1256
+ }
1257
+
1258
+ /**
1259
+ * The panel itself, as a right-hand sheet inside `shell.overlay`.
1260
+ * Esc and the backdrop both close it; focus stays inside the sheet while open.
1261
+ */
1262
+ function MemoryOverlay() {
1263
+ const open = useMemoryPanelOpen();
1264
+ const [rail, setRail] = React.useState(readTagRail);
1265
+ const [pick, setPick] = React.useState(null);
1266
+ React.useEffect(() => {
1267
+ if (!open || typeof window === 'undefined') return undefined;
1268
+ const onKey = (event) => {
1269
+ if (event && event.key === 'Escape') setMemoryPanelOpen(false);
1270
+ };
1271
+ window.addEventListener('keydown', onKey);
1272
+ return () => window.removeEventListener('keydown', onKey);
1273
+ }, [open]);
1274
+ if (!open) return null;
1275
+ return h(
1276
+ 'div',
1277
+ { style: { position: 'fixed', inset: 0, zIndex: 3000, display: 'flex', justifyContent: 'flex-end' } },
1278
+ h('div', {
1279
+ onClick: () => setMemoryPanelOpen(false),
1280
+ 'aria-hidden': 'true',
1281
+ style: { position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.36)' },
1282
+ }),
1283
+ h(
1284
+ 'div',
1285
+ {
1286
+ role: 'dialog',
1287
+ 'aria-modal': 'true',
1288
+ 'aria-label': '海马体记忆',
1289
+ style: {
1290
+ position: 'relative',
1291
+ width: 'min(1120px, 98vw)',
1292
+ height: '100%',
1293
+ display: 'flex',
1294
+ flexDirection: 'column',
1295
+ background: 'var(--dsh-surface, #1b1b1f)',
1296
+ color: palette.text,
1297
+ borderLeft: `1px solid ${palette.border}`,
1298
+ boxShadow: '-8px 0 24px rgba(0,0,0,0.35)',
1299
+ },
1300
+ },
1301
+ h(
1302
+ 'div',
1303
+ {
1304
+ style: {
1305
+ display: 'flex',
1306
+ alignItems: 'center',
1307
+ justifyContent: 'space-between',
1308
+ gap: 12,
1309
+ padding: '10px 14px',
1310
+ borderBottom: `1px solid ${palette.border}`,
1311
+ },
1312
+ },
1313
+ h('strong', { style: { fontSize: 14 } }, '海马体记忆'),
1314
+ h(
1315
+ 'div',
1316
+ { style: { display: 'flex', gap: 8 } },
1317
+ h(
1318
+ 'button',
1319
+ {
1320
+ type: 'button',
1321
+ onClick: () => {
1322
+ const next = !rail;
1323
+ writeTagRail(next);
1324
+ setRail(next);
1325
+ if (!next) setPick(null);
1326
+ },
1327
+ title: rail ? '隐藏标签栏' : '显示标签栏',
1328
+ style: { ...smallButtonStyle, ...(rail ? { borderColor: palette.accent, color: palette.accent } : {}) },
1329
+ },
1330
+ '标签栏',
1331
+ ),
1332
+ h(
1333
+ 'button',
1334
+ {
1335
+ type: 'button',
1336
+ onClick: () => setMemoryPanelOpen(false),
1337
+ style: {
1338
+ padding: '4px 10px',
1339
+ background: 'transparent',
1340
+ border: `1px solid ${palette.border}`,
1341
+ borderRadius: 8,
1342
+ color: palette.text,
1343
+ cursor: 'pointer',
1344
+ font: 'inherit',
1345
+ },
1346
+ },
1347
+ '关闭',
1348
+ ),
1349
+ ),
1350
+ ),
1351
+ h(
1352
+ 'div',
1353
+ { style: { flex: 1, minHeight: 0, display: 'flex' } },
1354
+ h(TagRail, {
1355
+ enabled: rail,
1356
+ pick,
1357
+ onPick: (tag) => {
1358
+ setPick(tag);
1359
+ // Drive the panel's own search: the rail is an INDEX into the real tag
1360
+ // view (graph + query), never a parallel one.
1361
+ tagFocusStore.tag = tag;
1362
+ announce('tag-focus');
1363
+ },
1364
+ }),
1365
+ h(
1366
+ 'div',
1367
+ { style: { flex: 1, minWidth: 0, overflow: 'auto' } },
1368
+ pick
1369
+ ? h('div', { style: { padding: '8px 14px', fontSize: 12, color: palette.muted } }, `当前筛选标签:${pick}(仅作导航,面板内搜索请用面板自己的查询框)`)
1370
+ : null,
1371
+ h(MemoryPanel),
1372
+ ),
1373
+ ),
1374
+ ),
1375
+ );
1376
+ }
1377
+
859
1378
  // ---- storage ring ------------------------------------------------------
860
1379
 
861
1380
  /**
@@ -2417,6 +2936,17 @@
2417
2936
  // same order on every render (ready -> pending -> ready must not shift them).
2418
2937
  const [searchInput, setSearchInput] = React.useState('');
2419
2938
  const [searchQuery, setSearchQuery] = React.useState('');
2939
+ // v1.9.14: the drawer's tag rail drives THIS panel's search + graph filter.
2940
+ // Without this the rail is a second, decorative tag list.
2941
+ React.useEffect(() => {
2942
+ const onFocus = () => {
2943
+ const tag = tagFocusStore.tag;
2944
+ setSearchInput(typeof tag === 'string' ? tag : '');
2945
+ setSearchQuery(typeof tag === 'string' ? tag : '');
2946
+ };
2947
+ bus.addEventListener('tag-focus', onFocus);
2948
+ return () => bus.removeEventListener('tag-focus', onFocus);
2949
+ }, []);
2420
2950
  // Space-isolated memory list + selection for the regulated transfer flow.
2421
2951
  // Capability handshake (old host vs new client): only fetch /memories when
2422
2952
  // the host advertises it; otherwise show a version hint, never a 404.
@@ -2429,6 +2959,15 @@
2429
2959
  // v1.6.1: archive month details are collapsed by default (the summary cards
2430
2960
  // above already answer "how many / how much"); expanding is opt-in.
2431
2961
  const [archiveOpen, setArchiveOpen] = React.useState(false);
2962
+ // v1.9.0 layered view. v1.9.20 HOISTED above the phase early returns: it used
2963
+ // to be called after them, so the pending render ran N hooks and the ready
2964
+ // render ran N+2 — React error #310 ("rendered more hooks than during the
2965
+ // previous render"), the owner unmounted the panel, and the main column went
2966
+ // blank with no message. `enabled` keeps it idle on a host without layers.
2967
+ const layerState = useLayers({
2968
+ enabled: payload?.capabilities?.layers === true,
2969
+ sessionId: payload?.panel?.session?.sessionId ?? null,
2970
+ });
2432
2971
 
2433
2972
  if (state.state === 'migrating') {
2434
2973
  return h('div', { style: { padding: 16 } }, h(MigrationCard, { migration: payload?.migration ?? state.migration }));
@@ -2451,13 +2990,6 @@
2451
2990
  const tagTreeInfo = panel.tagTree || {};
2452
2991
  const rawInfo = panel.raw || {};
2453
2992
  const session = panel.session || null;
2454
- // v1.9.0: poll the layered view only when this host advertises it. The hook
2455
- // is called unconditionally (hooks cannot be conditional) but `enabled`
2456
- // keeps it idle on an old host.
2457
- const layerState = useLayers({
2458
- enabled: payload?.capabilities?.layers === true,
2459
- sessionId: session?.sessionId ?? null,
2460
- });
2461
2993
  const spaces = panel.spaces || null;
2462
2994
  const spaceIds = spaceList || (spaces && Array.isArray(spaces.ids) ? spaces.ids : [activeSpace]);
2463
2995
  const currentSpace = (spaces && spaces.current) || activeSpace;
@@ -2994,6 +3526,13 @@
2994
3526
  { value: 'ingest', label: 'ingest — 用写入时刻' },
2995
3527
  ];
2996
3528
 
3529
+ /** v1.9.13: who may fold this context surface (mirrors the resolver's enum). */
3530
+ const OWNERSHIP_OPTIONS = [
3531
+ { value: 'auto', label: 'auto — 有人折叠就让出,交接保留(默认)' },
3532
+ { value: 'lone', label: 'lone — 始终由海马体折叠' },
3533
+ { value: 'shared', label: 'shared — 只观察,不折叠也不交接' },
3534
+ ];
3535
+
2997
3536
  /** Server config -> form draft (nested groups kept separate). */
2998
3537
  function draftFromConfig(config) {
2999
3538
  return {
@@ -3109,6 +3648,18 @@
3109
3648
  // Security red line (v1.5.1): default TRUE, only an explicit operator
3110
3649
  // choice may turn the engine-level consent gate off.
3111
3650
  requireExplicitConsentForTransfer: (config.context && config.context.requireExplicitConsentForTransfer) !== false,
3651
+ // v1.9.13: the operator's switches over the 1.9.8–1.9.11 machinery. Each one
3652
+ // is bounded and reversible, and its effect shows in the status card above.
3653
+ ownership: (config.context && config.context.ownership) || 'auto',
3654
+ smartPruneEnabled: (config.context && config.context.smartPrune ? config.context.smartPrune.enabled !== false : true),
3655
+ smartPruneOnceFoldAt: Number((config.context && config.context.smartPrune && config.context.smartPrune.onceFoldAt) ?? 0.65),
3656
+ liveCompactEnabled: (config.context && config.context.liveCompact ? config.context.liveCompact.enabled !== false : true),
3657
+ },
3658
+ // v1.9.13: coordinator budgets (ms). 0 for minInterval = no wall-clock floor.
3659
+ handoff: {
3660
+ minIntervalMs: Number((config.handoff && config.handoff.minIntervalMs) ?? 0),
3661
+ requestBudgetMs: Number((config.handoff && config.handoff.requestBudgetMs) ?? 1500),
3662
+ failFastBudgetMs: Number((config.handoff && config.handoff.failFastBudgetMs) ?? 800),
3112
3663
  },
3113
3664
  // Inverted-index physical limit: bounds read-model memory, never the log.
3114
3665
  index: {
@@ -3993,6 +4544,76 @@
3993
4544
  disabled,
3994
4545
  }),
3995
4546
  ),
4547
+ // v1.9.13: the four versions of machinery (1.9.8–1.9.11) finally have switches.
4548
+ // Every control here maps to a key that is BOTH whitelisted by webRoutes and
4549
+ // resolved by resolveConfig — the three-way test enforces that, so a slider can
4550
+ // never render and silently not save.
4551
+ h(
4552
+ Section,
4553
+ { title: '折叠与交接(1.9.8–1.9.13)', hidden: simpleMode },
4554
+ h(Select, {
4555
+ label: '折叠归属(context.ownership)',
4556
+ hint: 'auto(默认):探测到别的插件在折叠就让出 smartPrune/liveCompact,只保留交接;lone:无论谁在场都由海马体折叠;shared:只观察,不折叠也不交接。',
4557
+ value: draft.context.ownership,
4558
+ options: OWNERSHIP_OPTIONS,
4559
+ onChange: (value) => edit('context.ownership', value),
4560
+ disabled,
4561
+ }),
4562
+ h(Toggle, {
4563
+ label: '允许一次性折叠(context.smartPrune.enabled)',
4564
+ hint: '关掉后海马体不再改写上下文表面;交接仍按真实比例触发,只是没有「先缩一次」的那一步。',
4565
+ checked: draft.context.smartPruneEnabled,
4566
+ onChange: (value) => edit('context.smartPruneEnabled', value),
4567
+ disabled,
4568
+ }),
4569
+ h(Field, {
4570
+ label: '一次性折叠触发比例(context.smartPrune.onceFoldAt)',
4571
+ hint: '占用到这个比例折叠一次并立即交接;0 = 关闭一次性折叠。上限 0.85(硬停线)。',
4572
+ value: draft.context.smartPruneOnceFoldAt,
4573
+ min: 0,
4574
+ max: 0.85,
4575
+ step: 0.05,
4576
+ onChange: (value) => edit('context.smartPruneOnceFoldAt', value),
4577
+ disabled,
4578
+ }),
4579
+ h(Toggle, {
4580
+ label: '指针化超大工具结果(context.liveCompact.enabled)',
4581
+ hint: '把单个超长工具结果换成头尾 + 可恢复指针。与宿主 tool-result-pruner 同时开启会重复裁剪,auto 归属下会自动让出。',
4582
+ checked: draft.context.liveCompactEnabled,
4583
+ onChange: (value) => edit('context.liveCompactEnabled', value),
4584
+ disabled,
4585
+ }),
4586
+ h(Field, {
4587
+ label: '请求路径最多等待交接(handoff.requestBudgetMs)',
4588
+ hint: '毫秒。超时即放行请求,蒸馏在后台继续;这是「不回话」的直接解药,调大等于让它更久地卡住这一轮。',
4589
+ value: draft.handoff.requestBudgetMs,
4590
+ min: 300,
4591
+ max: 5000,
4592
+ step: 100,
4593
+ onChange: (value) => edit('handoff.requestBudgetMs', value),
4594
+ disabled,
4595
+ }),
4596
+ h(Field, {
4597
+ label: '两次交接的最小间隔(handoff.minIntervalMs)',
4598
+ hint: '毫秒,0 = 不限制(默认)。真正防重复的是「压力再涨 5 个百分点」,这里只是可选的硬地板。',
4599
+ value: draft.handoff.minIntervalMs,
4600
+ min: 0,
4601
+ max: 600000,
4602
+ step: 1000,
4603
+ onChange: (value) => edit('handoff.minIntervalMs', value),
4604
+ disabled,
4605
+ }),
4606
+ h(Field, {
4607
+ label: '超窗时的交接预算(handoff.failFastBudgetMs)',
4608
+ hint: '请求已经确定放不下时的等待上限(100–5000ms)。越短越早报错。',
4609
+ value: draft.handoff.failFastBudgetMs,
4610
+ min: 100,
4611
+ max: 5000,
4612
+ step: 100,
4613
+ onChange: (value) => edit('handoff.failFastBudgetMs', value),
4614
+ disabled,
4615
+ }),
4616
+ ),
3996
4617
  ];
3997
4618
  }
3998
4619
 
@@ -4568,6 +5189,9 @@
4568
5189
  index: { ...(prev.index || {}) },
4569
5190
  temp: { ...(prev.temp || {}) },
4570
5191
  tagTree: { ...(prev.tagTree || {}) },
5192
+ // v1.9.13: the handoff group must join the shallow-clone list, or a
5193
+ // cancelled edit mutates the previous draft in place.
5194
+ handoff: { ...(prev.handoff || {}) },
4571
5195
  ui: { ...(prev.ui || {}) },
4572
5196
  // tools.disabled is an ARRAY: clone it so a cancelled edit cannot
4573
5197
  // mutate the previous draft's array in place.
@@ -4651,6 +5275,17 @@
4651
5275
  'context.autoRolloverThreshold': Number(draft.context.autoRolloverThreshold),
4652
5276
  'context.nativeTokenLimit': Number(draft.context.nativeTokenLimit),
4653
5277
  'context.requireExplicitConsentForTransfer': Boolean(draft.context.requireExplicitConsentForTransfer),
5278
+ // v1.9.13: the operator's switches over the 1.9.8–1.9.11 machinery. Every
5279
+ // one of these is in EDITABLE_CONFIG_KEYS and resolved by resolveConfig —
5280
+ // the three-way test locks that, so a control can never render and not save.
5281
+ 'context.ownership':
5282
+ draft.context.ownership === 'lone' || draft.context.ownership === 'shared' ? draft.context.ownership : 'auto',
5283
+ 'context.smartPrune.enabled': Boolean(draft.context.smartPruneEnabled),
5284
+ 'context.smartPrune.onceFoldAt': Number(draft.context.smartPruneOnceFoldAt),
5285
+ 'context.liveCompact.enabled': Boolean(draft.context.liveCompactEnabled),
5286
+ 'handoff.minIntervalMs': Number(draft.handoff.minIntervalMs),
5287
+ 'handoff.requestBudgetMs': Number(draft.handoff.requestBudgetMs),
5288
+ 'handoff.failFastBudgetMs': Number(draft.handoff.failFastBudgetMs),
4654
5289
  'index.maxPostingsPerTag': Number(draft.index.maxPostingsPerTag),
4655
5290
  'tools.disabled': Array.isArray(draft.tools.disabled) ? [...draft.tools.disabled] : [],
4656
5291
  'tagging.autoTag': Boolean(draft.tagging.autoTag),
@@ -4789,6 +5424,59 @@
4789
5424
  { style: { padding: 16, display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 980 } },
4790
5425
  h('div', { style: { fontSize: 16, fontWeight: 600 } }, '海马体记忆'),
4791
5426
  h('div', { style: labelStyle }, '保存后立即作用于运行时(fail-fast 校验,越界会被拒绝),并在可持久化时写回 Loader 配置。'),
5427
+ // v1.9.12: 「现在是什么状态」 before 「改什么」. Every field below is READ-ONLY and
5428
+ // comes from the same /stats payload the panel uses, so the two surfaces cannot
5429
+ // disagree. The four facts that were invisible during the 2026-12-01 incident
5430
+ // (工作模式 / 交接 / 折叠归属 / 命令可用性) are now on screen.
5431
+ (() => {
5432
+ const panel = statsPayload && statsPayload.panel ? statsPayload.panel : null;
5433
+ const session = panel && panel.session ? panel.session : null;
5434
+ const global = panel && panel.global ? panel.global : null;
5435
+ const own = panel && panel.ownership ? panel.ownership : null;
5436
+ const commands = panel && panel.commands ? panel.commands : null;
5437
+ const phaseText = state.state === 'ready' ? '就绪' : String(state.state || '未知');
5438
+ const pct = session && Number.isFinite(session.ratio) ? `${Math.round(session.ratio * 100)}%` : '—';
5439
+ const handoffText = !session
5440
+ ? '未知'
5441
+ : session.handoffActive
5442
+ ? '已交接:建议新建对话续接'
5443
+ : session.handoffState === 'consumed'
5444
+ ? '已消费(当前会话可继续)'
5445
+ : '无';
5446
+ const foldText = !own ? '未知' : own.smartPrune === 'on' ? '由海马体折叠' : `已让出(${own.reason})`;
5447
+ const cmdText = !commands ? '未知' : commands.available ? '可用' : '不可用:/memory 会失效';
5448
+ const row = (label, value, tone) =>
5449
+ h(
5450
+ 'div',
5451
+ { style: { display: 'flex', gap: 10, alignItems: 'baseline', fontSize: 12, lineHeight: '20px' } },
5452
+ h('span', { style: { color: palette.muted, minWidth: 76 } }, label),
5453
+ h('span', { style: { color: tone || palette.text } }, value),
5454
+ );
5455
+ return h(
5456
+ 'div',
5457
+ { style: { ...cardStyle, display: 'flex', flexDirection: 'column', gap: 2 } },
5458
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 } },
5459
+ h('strong', { style: { fontSize: 13 } }, '当前状态'),
5460
+ h('div', { style: { display: 'flex', gap: 8 } },
5461
+ h('button', {
5462
+ type: 'button',
5463
+ style: smallButtonStyle,
5464
+ onClick: () => {
5465
+ announce('config-changed');
5466
+ setMemoryPanelOpen(true);
5467
+ },
5468
+ }, '打开面板'),
5469
+ ),
5470
+ ),
5471
+ row('引擎', `${phaseText}${global ? ` · ${fmtNumber(global.events)} 条事件 · ${fmtNumber(global.activeTags)} 个活跃标签` : ''}`),
5472
+ row('上下文', session
5473
+ ? `已用 ${fmtNumber(session.tokens)} + 预留 ${fmtNumber(session.reservedTokens)} / 窗口 ${fmtNumber(session.nativeTokenLimit)}(${pct})`
5474
+ : '未知'),
5475
+ row('交接', handoffText, session && session.handoffActive ? palette.warn : null),
5476
+ row('折叠归属', foldText, own && own.smartPrune !== 'on' ? palette.warn : null),
5477
+ row('命令', cmdText, commands && !commands.available ? palette.danger : null),
5478
+ );
5479
+ })(),
4792
5480
  // v1.6.3: 视图切换。简洁模式只显示四块,隐藏项不参与保存、文件里保持原值。
4793
5481
  h(
4794
5482
  'div',
@@ -4975,6 +5663,9 @@ h(
4975
5663
  // Exported for the bundle-contract tests: the pure retry decision is the
4976
5664
  // piece the P0 fix depends on, so it must be testable without a browser.
4977
5665
  retryPolicy: decideRetry,
5666
+ // v1.9.12: the icon is painted by the sidebar action and by the panel header, so
5667
+ // it is exported rather than fished out of a slot registration in tests.
5668
+ MemoryIcon,
4978
5669
  // Pure geometry for the history view: testable without a DOM.
4979
5670
  ghostGraphParts,
4980
5671
  // v1.7.4 graph geometry: layout world, force model, overlap separation and
@@ -4990,7 +5681,14 @@ h(
4990
5681
  // lock them without a browser: capability handshake + human error mapper.
4991
5682
  spaceCreateAvailable,
4992
5683
  describeSpaceError,
5684
+ // v1.9.15: the 「续接」 button's visibility rule, pure so it is testable
5685
+ // without a browser (a handoff marker that is days old must not render).
5686
+ resumeWanted,
4993
5687
  apply(ctx) {
5688
+ // v1.9.15: components render after this call, so the context is kept for
5689
+ // click-time service lookup (the sidebar resume button asks it for the
5690
+ // uiWorkspace service only when a person clicks).
5691
+ hostContext = ctx ?? null;
4994
5692
  let slots = null;
4995
5693
  try {
4996
5694
  slots = ctx && ctx.slots;
@@ -4999,10 +5697,17 @@ h(
4999
5697
  }
5000
5698
  if (!slots || typeof slots.inject !== 'function' || typeof slots.register !== 'function') return;
5001
5699
 
5002
- const mount = (name, options, component) => {
5700
+ const mount = (name, options, component, onInjected = null) => {
5003
5701
  try {
5004
5702
  slots.inject(name, () => {
5005
5703
  try {
5704
+ if (typeof onInjected === 'function') {
5705
+ try {
5706
+ onInjected();
5707
+ } catch (error) {
5708
+ report(`inject hook ${name}`, error);
5709
+ }
5710
+ }
5006
5711
  return slots.register({ name, ...options }, component);
5007
5712
  } catch (error) {
5008
5713
  report(`register ${name}`, error);
@@ -5014,8 +5719,37 @@ h(
5014
5719
  }
5015
5720
  };
5016
5721
 
5017
- mount('sidebar.panellist', { id: 'hippocampus-panel', order: 60, label: '海马体记忆' }, MemoryIcon);
5018
- mount('main', { key: 'hippocampus-panel' }, MemoryPanel);
5722
+ // v1.9.16: the PAIR is registered DIRECTLY, exactly like dsh-market.
5723
+ // `slots.inject(name, cb)` runs `cb` when the slot exists and treats its
5724
+ // RETURN VALUE as the inject effect's cleanup — so the registration dies
5725
+ // the first time the shell re-instantiates the factory that declares the
5726
+ // seat. Live evidence: this shell reported the `main` occupant as
5727
+ // `active:false` (disposed) right after the icon was clicked, and the
5728
+ // panel stayed blank.
5729
+ const mountDirect = (name, options, component) => {
5730
+ try {
5731
+ if (typeof slots.register !== 'function') return;
5732
+ slots.register({ name, ...options }, component);
5733
+ } catch (error) {
5734
+ report(`register ${name}`, error);
5735
+ }
5736
+ };
5737
+
5738
+ // Every seat below was verified live through
5739
+ // `cordis_inspect_query(client, Slots, listSubTree)` — and the list is
5740
+ // pinned by `test/v1102.seats.test.js`, because a seat name is an open
5741
+ // string: a wrong one registers, renders nothing, and fails in silence.
5742
+ //
5743
+ // sidebar.panellist + main the real entry: an icon PAIRED with a
5744
+ // main panel under the same id
5745
+ // sidebar.footer.action fallback entry (hides once the icon renders)
5746
+ // shell.overlay the fallback sheet that entry opens
5747
+ // settings.section the settings page
5748
+ mountDirect('main', { key: MEMORY_PANEL_ID }, MemoryPanelHost);
5749
+ mountDirect('sidebar.panellist', { id: MEMORY_PANEL_ID, order: 60, label: '海马体记忆' }, MemoryPanelIcon);
5750
+ mount('sidebar.footer.action', { id: 'hippocampus-resume', order: 31, label: '续接' }, SidebarResumeButton);
5751
+ mount('sidebar.footer.action', { id: 'hippocampus-open', order: 30, label: '海马体记忆' }, SidebarMemoryAction);
5752
+ mount('shell.overlay', { id: 'hippocampus-overlay', order: 30, label: '海马体记忆' }, MemoryOverlay);
5019
5753
  mount('settings.section', { id: 'hippocampus-settings', order: 25, label: '海马体记忆' }, MemorySettings);
5020
5754
  },
5021
5755
  };