paseo-dsh 0.2.15 → 0.2.17

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.
@@ -7,5 +7,5 @@ declare module "react-native" {
7
7
  export const View: any;
8
8
  export const Text: any;
9
9
  export const Pressable: any;
10
- export const Platform: { readonly OS: "ios" | "android" | "web" | "windows" | "macos" };
10
+ export const Platform: { OS: "ios" | "android" | "web" | "windows" | "macos" };
11
11
  }
@@ -1,10 +1,8 @@
1
1
  import type { PluginClientContext, PluginTimelineItemProps } from "@getpaseo/plugin/client";
2
- import { useSettings } from "@getpaseo/plugin/client";
3
2
  import { Fragment, useLayoutEffect, useRef, useState } from "react";
4
3
  import { Pressable, Text, View } from "react-native";
5
4
  import { z } from "zod";
6
- import { DEFAULT_STREAM_STATS, streamStatsSettings } from "../shared/settings";
7
- import { measureFooterLift, watchFooter } from "./web";
5
+ import { measureFooterGeometry, rowIsLaidOut, watchRow } from "./web";
8
6
 
9
7
  export const streamStatsSchema = z.object({
10
8
  firstTokenMs: z.number().optional(),
@@ -23,37 +21,23 @@ export const streamStatsSchema = z.object({
23
21
  steps: z.number().optional(),
24
22
  sessionTokens: z.number().optional(),
25
23
  cacheHit: z.number().optional(),
26
- /** Last stats row of a turn: Paseo puts its completed-turn footer above it. */
24
+ /** Set by the daemon on the last row of a completed turn: the copy footer is above it. */
27
25
  final: z.boolean().optional(),
28
26
  });
29
27
 
30
28
  type StreamStats = z.infer<typeof streamStatsSchema>;
31
29
 
32
30
  /**
33
- * Paseo draws the completed-turn footer — copy / model / time — directly under
34
- * the answer and keeps its own bottom padding free under it, while this row is
35
- * an ordinary timeline item spaced by the host's item gap. Neither number is
36
- * ours to rely on: a theme plugin restyles that footer, and the same footer is
37
- * also drawn under turns that are no longer the newest, where the host's
38
- * margins differ (the row sits 35px under the footer while its turn is latest,
39
- * 23px once a newer turn arrives).
40
- *
41
- * On web the row measures the footer actually painted above it (in `./web`,
42
- * the only client file allowed to touch the DOM) and lifts itself to the gap
43
- * the user chose in Settings → Plugins. Native has no DOM to measure; it keeps
44
- * the geometry the host's footer was tuned for.
31
+ * Paseo paints the completed-turn footer at `STREAM_METADATA_FONT_SIZE` (13px).
32
+ * Until the page can be measured that is also what this row draws at, so the
33
+ * two lines read as one block instead of two sizes.
45
34
  */
46
- /** Paseo's `SPACING[8]` (`TURN_FOOTER_BOTTOM_SPACING`): the footer's bottom padding. */
47
- const TURN_FOOTER_BOTTOM_PADDING = 32;
48
- /**
49
- * The furthest the row may pull up. Measured gaps can exceed Paseo's own 32px
50
- * footer padding once a theme restyles the footer, so the cap is twice that:
51
- * generous enough for themed footers, still bounded so a mis-measure cannot
52
- * drag the row across the answer.
53
- */
54
- const MAX_ROW_LIFT = -2 * TURN_FOOTER_BOTTOM_PADDING;
55
- /** Paseo's footer sets its text in a 18px line box at 13px. */
56
- const LINE_HEIGHT_RATIO = 18 / 13;
35
+ const FOOTER_FONT_SIZE = 13;
36
+ /** Space under the footer's last line, as a fraction of this row's text size. */
37
+ const GAP_EM = 0.46;
38
+ /** The row's own small offsets, also fractions of its text size (~2px / ~1px at 13). */
39
+ const INSET_EM = 0.15;
40
+ const DETAIL_GAP_EM = 0.1;
57
41
 
58
42
  function formatLatency(ms: number): string {
59
43
  return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
@@ -101,58 +85,64 @@ function toolsLine(data: StreamStats): string | undefined {
101
85
  /** One compact line under an answer; tap to expand the full picture. */
102
86
  function StreamStatsRow({ item, theme, layout }: PluginTimelineItemProps<StreamStats>) {
103
87
  const [open, setOpen] = useState(false);
88
+ const [fontSize, setFontSize] = useState(FOOTER_FONT_SIZE);
104
89
  const [lift, setLift] = useState(0);
105
90
  const rowRef = useRef<unknown>(null);
106
- /** The lift currently in the DOM, which the next measurement has to discount. */
91
+ /** The lift the DOM currently carries; the next measurement discounts it. */
107
92
  const appliedLift = useRef(0);
108
- const settings = useSettings(streamStatsSettings);
109
- const gap = settings.status === "ready" ? settings.values.gapPx : DEFAULT_STREAM_STATS.gapPx;
110
- const fontSize = settings.status === "ready" ? settings.values.fontSize : DEFAULT_STREAM_STATS.fontSize;
111
93
  const data = item.data;
112
94
 
113
95
  // The ref must describe the margin the DOM actually carries, not the one a
114
- // pending render is about to apply: a ResizeObserver callback between
115
- // `setLift` and its commit would otherwise discount a lift the frame has not
116
- // moved by yet and measure against the wrong origin.
96
+ // pending render is about to apply.
117
97
  useLayoutEffect(() => {
118
98
  appliedLift.current = lift;
119
99
  }, [lift]);
120
100
 
121
- const applyLift = (next: number) => {
122
- if (appliedLift.current === next) return;
123
- setLift(next);
124
- };
125
-
126
- // The footer above this row is the host's markup and, with a theme plugin
127
- // installed, that plugin's restyling of it — so its height and padding are
128
- // measured instead of assumed. Everything DOM lives in `./web`; off web it
129
- // reports nothing, the row keeps the host's own gap, and native falls back to
130
- // the constant `nativeLift` below.
101
+ // Only the last row of a completed turn has the footer directly above it, and
102
+ // only the web build can see where that footer was painted. Everything else
103
+ // keeps the host's spacing: a guessed offset is what used to ride up over the
104
+ // answer once a second turn pushed the first one down.
131
105
  useLayoutEffect(() => {
132
- if (data.final !== true) {
133
- applyLift(0);
106
+ if (data.final !== true || layout.platform !== "web") {
107
+ setLift(0);
134
108
  return;
135
109
  }
136
110
  const measure = () => {
137
- const next = measureFooterLift(rowRef.current, {
111
+ const found = measureFooterGeometry(rowRef.current, {
138
112
  appliedLift: appliedLift.current,
139
- gap,
140
- maxLift: MAX_ROW_LIFT,
113
+ gapEm: GAP_EM,
114
+ fallbackFontSize: FOOTER_FONT_SIZE,
141
115
  });
142
- applyLift(next ?? 0);
116
+ if (found === null) {
117
+ // A hidden tab (zero-height row) says nothing about the layout: keep
118
+ // the last margin so switching back does not un-tuck the row.
119
+ if (rowIsLaidOut(rowRef.current)) setLift(0);
120
+ return;
121
+ }
122
+ setLift(found.lift);
123
+ setFontSize(found.fontSize);
143
124
  };
144
125
  measure();
145
- const stop = watchFooter(rowRef.current, measure);
146
- return stop ?? undefined;
147
- // `applyLift` only reads refs and a state setter, so the values that can
148
- // change what is measured are the only dependencies.
149
- }, [data.final, gap]);
126
+ // The footer is not necessarily in its final place when the row mounts: it
127
+ // can arrive a frame later, and the host may move it after the turn is
128
+ // marked complete. Re-measure a few times while that settles, and keep
129
+ // watching the containers in case it moves again (a new turn pushing this
130
+ // one down, a theme swap, a font load).
131
+ const retries = [80, 240, 700, 1500].map((ms) => setTimeout(measure, ms));
132
+ const stop = watchRow(rowRef.current, measure);
133
+ return () => {
134
+ for (const timer of retries) clearTimeout(timer);
135
+ stop?.();
136
+ };
137
+ }, [data.final, layout.platform]);
150
138
 
151
139
  const muted = theme.colors.foregroundMuted;
140
+ const lineHeight = Math.round(fontSize * (18 / 13));
141
+ const inset = Math.max(1, Math.round(fontSize * INSET_EM));
152
142
  const base = {
153
143
  color: muted,
154
144
  fontSize,
155
- lineHeight: Math.round(fontSize * LINE_HEIGHT_RATIO),
145
+ lineHeight,
156
146
  fontVariant: ["tabular-nums"] as const,
157
147
  };
158
148
 
@@ -178,7 +168,6 @@ function StreamStatsRow({ item, theme, layout }: PluginTimelineItemProps<StreamS
178
168
  const details = [contextLine(data), tokensLine(data), routeLine(data), toolsLine(data)].filter(
179
169
  (line): line is string => line !== undefined,
180
170
  );
181
- const nativeLift = gap - TURN_FOOTER_BOTTOM_PADDING;
182
171
 
183
172
  return (
184
173
  <Pressable
@@ -186,12 +175,7 @@ function StreamStatsRow({ item, theme, layout }: PluginTimelineItemProps<StreamS
186
175
  accessibilityRole="button"
187
176
  accessibilityLabel={open ? "收起回答统计" : "展开回答统计"}
188
177
  onPress={() => setOpen((value) => !value)}
189
- style={{
190
- alignSelf: "flex-start",
191
- marginTop: data.final === true ? (layout.platform === "web" ? lift : nativeLift) : 0,
192
- marginBottom: 0,
193
- paddingLeft: 2,
194
- }}
178
+ style={{ alignSelf: "flex-start", marginTop: lift, marginBottom: 0, paddingLeft: inset }}
195
179
  >
196
180
  <View style={{ flexDirection: "row", alignItems: "center", flexWrap: "wrap" }}>
197
181
  {segments.map((segment, index) => (
@@ -203,7 +187,7 @@ function StreamStatsRow({ item, theme, layout }: PluginTimelineItemProps<StreamS
203
187
  <Text style={base}>{open ? " ▴" : " ▾"}</Text>
204
188
  </View>
205
189
  {open ? (
206
- <View style={{ marginTop: 2, gap: 1 }}>
190
+ <View style={{ marginTop: inset, gap: Math.max(1, Math.round(fontSize * DETAIL_GAP_EM)) }}>
207
191
  {details.map((line) => (
208
192
  <Text key={line} style={base}>
209
193
  {line}
package/client/web.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  import { Platform } from "react-native";
2
2
 
3
3
  /**
4
- * The one client file that reads the DOM.
4
+ * Where the completed-turn footer is, measured instead of guessed.
5
5
  *
6
- * Paseo runs plugin client code on iOS and Android too, where none of these
7
- * globals exist, so every export here is a no-op off web and the shared
8
- * renderers only ever see numbers (or null). Keeping `getBoundingClientRect`,
9
- * `querySelectorAll` and `ResizeObserver` in this file means a host change to
10
- * its own layout costs one file to fix, and an SSR build has one place to
11
- * stub out.
6
+ * Paseo reserves a fixed strip under that footer (`turnFooterSlot` carries
7
+ * `paddingBottom: SPACING[8]`, 32px) and the stats row is an ordinary timeline
8
+ * item placed after it, so the row floats in that strip with the gap the host
9
+ * happens to give it. The strip is not ours to change, and it is not stable
10
+ * either: a theme plugin restyles the footer, and the same turn is laid out
11
+ * differently once a newer turn pushes it down. Any constant offset therefore
12
+ * fits one combination and overlaps the answer in another.
13
+ *
14
+ * So the row measures the footer actually painted above it. All DOM access
15
+ * lives in this file: Paseo also runs plugin client code on iOS and Android,
16
+ * where these globals do not exist, and the renderer only ever sees the numbers
17
+ * returned here (or null, meaning "leave the host's layout alone").
12
18
  */
13
19
 
14
20
  /** The DOM shape read here; `tsconfig` ships no DOM typings. */
@@ -16,9 +22,32 @@ interface MeasuredNode {
16
22
  parentElement: MeasuredNode | null;
17
23
  previousElementSibling: MeasuredNode | null;
18
24
  children: ArrayLike<MeasuredNode>;
25
+ childNodes: ArrayLike<MeasuredNode>;
26
+ nodeType: number;
27
+ nodeValue: string | null;
19
28
  textContent: string | null;
20
29
  getBoundingClientRect(): { top: number; bottom: number; height: number };
21
30
  querySelectorAll(selector: string): ArrayLike<MeasuredNode>;
31
+ ownerDocument: TextDocument | null;
32
+ }
33
+
34
+ interface TextRect {
35
+ top: number;
36
+ bottom: number;
37
+ height: number;
38
+ }
39
+
40
+ interface TextRange {
41
+ selectNodeContents(node: unknown): void;
42
+ getBoundingClientRect(): TextRect;
43
+ }
44
+
45
+ interface TextDocument {
46
+ createRange(): TextRange;
47
+ }
48
+
49
+ interface ComputedStyle {
50
+ fontSize?: string;
22
51
  }
23
52
 
24
53
  type ResizeObserverConstructor = new (callback: () => void) => {
@@ -26,92 +55,297 @@ type ResizeObserverConstructor = new (callback: () => void) => {
26
55
  disconnect(): void;
27
56
  };
28
57
 
29
- /** Where the footer above an item ends and where the item's own frame starts. */
30
- interface FooterAnchor {
31
- frame: MeasuredNode;
32
- above: MeasuredNode;
58
+ type MutationObserverConstructor = new (callback: () => void) => {
59
+ observe(target: unknown, options: { childList: boolean; subtree: boolean }): void;
60
+ disconnect(): void;
61
+ };
62
+
63
+ /**
64
+ * The footer is one short metadata line (copy, model, time, elapsed). An answer
65
+ * or a whole pushed-down turn is much longer; using one of those as the anchor
66
+ * is exactly how the row ends up on top of the text.
67
+ */
68
+ const MAX_FOOTER_TEXT = 120;
69
+ /** The footer's first line is its copy control; prose that mentions the word is not. */
70
+ const FOOTER_PREFIX = /^(复制|copy)/i;
71
+ /** Wrapper levels to step over before giving up: item frame, list cell, row. */
72
+ const MAX_WRAPPER_DEPTH = 6;
73
+ /** Ancestors watched for layout changes: row, wrappers, turn block, list. */
74
+ const WATCH_DEPTH = 6;
75
+ /**
76
+ * Largest plausible distance, in footer line heights, between the footer's last
77
+ * line and the row the host laid out under it. A wrong anchor lands far outside
78
+ * this; a themed footer that adds padding still lands inside it.
79
+ */
80
+ const MAX_GAP_LINES = 4;
81
+
82
+ /** Whether the row is actually laid out (an inactive tab renders zero-height). */
83
+ export function rowIsLaidOut(row: unknown): boolean {
84
+ const node = webRow(row);
85
+ if (node === null) return false;
86
+ return node.getBoundingClientRect().height > 0;
87
+ }
88
+
89
+ export interface FooterGeometry {
90
+ /** Margin that puts the row's top `gapEm` under the footer's last line. */
91
+ lift: number;
92
+ /** Text size the footer is painted at, so the row can match it. */
93
+ fontSize: number;
94
+ }
95
+
96
+ function webRow(row: unknown): MeasuredNode | null {
97
+ if (Platform.OS !== "web" || row === null || row === undefined) return null;
98
+ return row as MeasuredNode;
99
+ }
100
+
101
+ function lineHeightFor(fontSize: number): number {
102
+ // Paseo sets the footer's 13px text in an 18px line box.
103
+ return fontSize * (18 / 13);
104
+ }
105
+
106
+ const TEXT_NODE = 3;
107
+
108
+ /**
109
+ * Elements that directly hold a piece of visible text. Reading text nodes
110
+ * rather than leaf elements means inline text (a bare string child, which a
111
+ * theme plugin can produce) is measured too.
112
+ */
113
+ function textRuns(node: MeasuredNode, depth = 0): MeasuredNode[] {
114
+ const runs: MeasuredNode[] = [];
115
+ if (depth > 12) return runs;
116
+ for (let index = 0; index < node.childNodes.length; index += 1) {
117
+ const child = node.childNodes[index];
118
+ if (child === undefined) continue;
119
+ if (child.nodeType === TEXT_NODE) {
120
+ const text = child.nodeValue?.trim() ?? "";
121
+ if (text !== "" && node.getBoundingClientRect().height > 0) runs.push(node);
122
+ continue;
123
+ }
124
+ runs.push(...textRuns(child, depth + 1));
125
+ }
126
+ return runs;
127
+ }
128
+
129
+ /**
130
+ * The box the glyphs of a text node actually occupy. A range is used because
131
+ * the element around the text may carry padding (a themed footer that sets its
132
+ * text directly), and the element box would then report the padding as text.
133
+ */
134
+ function textRect(node: MeasuredNode): TextRect {
135
+ const document = node.ownerDocument;
136
+ if (document !== null) {
137
+ const range = document.createRange();
138
+ range.selectNodeContents(node);
139
+ const rect = range.getBoundingClientRect();
140
+ if (rect.height > 0) return rect;
141
+ }
142
+ return node.getBoundingClientRect();
143
+ }
144
+
145
+ /**
146
+ * The font size the footer is painted at: read from a text leaf rather than the
147
+ * footer box, because the box inherits the content size and only adds padding.
148
+ */
149
+ function footerFontSize(node: MeasuredNode, fallback: number): number {
150
+ const read = (globalThis as { getComputedStyle?: (element: unknown) => ComputedStyle })
151
+ .getComputedStyle;
152
+ if (read === undefined) return fallback;
153
+ let largest = 0;
154
+ for (const leaf of textRuns(node)) {
155
+ const parsed = Number.parseFloat(read(leaf).fontSize ?? "");
156
+ if (Number.isFinite(parsed) && parsed > largest) largest = parsed;
157
+ }
158
+ return largest > 0 ? largest : fallback;
159
+ }
160
+
161
+ /**
162
+ * A short block whose visible text starts with the copy control. Answers can
163
+ * mention "copy" too, and a message block can contain a copy button of its own,
164
+ * so neither containing the word nor owning a copy control is enough: the text
165
+ * itself has to start with it.
166
+ */
167
+ function looksLikeFooter(node: MeasuredNode): boolean {
168
+ const text = node.textContent?.trim() ?? "";
169
+ return text !== "" && text.length <= MAX_FOOTER_TEXT && FOOTER_PREFIX.test(text);
170
+ }
171
+
172
+ /** Elements that paint text, used to find the copy line without scanning every box. */
173
+ function textBearing(node: MeasuredNode): MeasuredNode[] {
174
+ const out: MeasuredNode[] = [];
175
+ const all = node.querySelectorAll("*");
176
+ for (let index = 0; index < all.length; index += 1) {
177
+ const element = all[index];
178
+ if (element === undefined || element.children.length > 0) continue;
179
+ const text = element.textContent?.trim() ?? "";
180
+ if (text !== "" && element.getBoundingClientRect().height > 0) out.push(element);
181
+ }
182
+ return out;
183
+ }
184
+
185
+ /**
186
+ * The footer inside `block`, if one is painted there.
187
+ *
188
+ * Paseo does not always put the footer in a sibling row: for a completed turn it
189
+ * is drawn at the end of the answer block, so the row's previous sibling is the
190
+ * whole answer. Look at the sibling first and then inside it, and take the last
191
+ * copy line found — the footer is the last thing in that block, never the first
192
+ * line of the answer.
193
+ */
194
+ function findFooter(block: MeasuredNode): MeasuredNode | null {
195
+ if (looksLikeFooter(block)) return block;
196
+ let found: MeasuredNode | null = null;
197
+ let lowest = Number.NEGATIVE_INFINITY;
198
+ for (const element of textBearing(block)) {
199
+ if (!FOOTER_PREFIX.test(element.textContent?.trim() ?? "")) continue;
200
+ // A message block can carry copy affordances of its own (the hover
201
+ // toolbar). The footer is the one painted lowest, right above this row.
202
+ const bottom = element.getBoundingClientRect().bottom;
203
+ if (bottom > lowest) {
204
+ lowest = bottom;
205
+ found = element;
206
+ }
207
+ }
208
+ if (found === null) return null;
209
+ // And it has to be the last text in the block: a copy control floating in
210
+ // the middle of an answer is not the footer, and measuring it would tuck the
211
+ // row under the wrong line.
212
+ const lowestText = lastTextBottom(block);
213
+ if (lowestText !== null && lowest < lowestText - 2) return null;
214
+ return found;
33
215
  }
34
216
 
35
217
  /**
36
- * The frame this item was laid out in, found from the row rendered inside it:
37
- * wrapper frames that hold nothing but this row are stepped over until a
38
- * sibling with height appears above.
218
+ * The frame this item was laid out in and the footer above it.
219
+ *
220
+ * The row is rendered inside one or more wrappers that hold nothing but it, so
221
+ * empty predecessors are stepped over until a sibling with height appears. That
222
+ * sibling has to contain the footer; anything else means this row is not tucked
223
+ * under one, and moving it would land on the answer.
39
224
  */
40
- function locate(row: MeasuredNode): FooterAnchor | null {
225
+ function locateFooter(row: MeasuredNode): { frame: MeasuredNode; footer: MeasuredNode } | null {
41
226
  let frame: MeasuredNode | null = row;
42
- for (let depth = 0; depth < 8 && frame !== null; depth += 1) {
227
+ for (let depth = 0; depth < MAX_WRAPPER_DEPTH && frame !== null; depth += 1) {
43
228
  const above = frame.previousElementSibling;
44
- if (above !== null && above.getBoundingClientRect().height > 0) return { frame, above };
229
+ if (above !== null && above.getBoundingClientRect().height > 0) {
230
+ const footer = findFooter(above);
231
+ return footer === null ? null : { frame, footer };
232
+ }
45
233
  frame = frame.parentElement;
46
234
  }
47
235
  return null;
48
236
  }
49
237
 
50
- /** Bottom edge of the last visible line of text inside `node`. */
238
+ /** Bottom edge of the last painted line of text inside `node`. */
51
239
  function lastTextBottom(node: MeasuredNode): number | null {
52
240
  let bottom: number | null = null;
53
- const lines = node.querySelectorAll("*");
54
- for (let index = 0; index < lines.length; index += 1) {
55
- const line = lines[index];
56
- if (line === undefined || line.children.length > 0) continue;
57
- if (line.textContent === null || line.textContent.trim() === "") continue;
58
- const rect = line.getBoundingClientRect();
59
- if (rect.height <= 0) continue;
241
+ for (const leaf of textRuns(node)) {
242
+ const rect = textRect(leaf);
60
243
  bottom = bottom === null ? rect.bottom : Math.max(bottom, rect.bottom);
61
244
  }
62
245
  return bottom;
63
246
  }
64
247
 
65
- function webRow(row: unknown): MeasuredNode | null {
66
- if (Platform.OS !== "web" || row === null || row === undefined) return null;
67
- return row as MeasuredNode;
68
- }
69
-
70
248
  /**
71
- * How far `row` has to pull itself up so its frame sits `gap` px under the last
72
- * line of text drawn above it — the completed-turn footer, or the answer's own
73
- * last line when a theme draws no footer.
249
+ * How far `row` pulls itself up so its top sits `gapEm` under the footer's last
250
+ * line, plus the size that footer is painted at.
74
251
  *
75
- * `appliedLift` is the margin the row is carrying right now: the frame has
76
- * already moved by it, so it is taken back out before measuring. Without that,
77
- * the row would measure the position it just moved itself to and bounce between
78
- * two places.
252
+ * `appliedLift` is the margin the row carries right now. The frame has already
253
+ * moved by it, so it is subtracted before measuring; otherwise the row measures
254
+ * the position it just moved itself to and oscillates between two places.
79
255
  *
80
- * Returns null when there is nothing to measure — native, a row that is not in
81
- * the DOM yet, no sibling above — and the caller falls back to its own layout.
256
+ * Returns null when there is nothing safe to measure: native, no footer above,
257
+ * a sibling that only looks like a footer, or a gap too large to be the footer.
258
+ * The caller then keeps the host's spacing rather than guessing.
82
259
  */
83
- export function measureFooterLift(
260
+ export function measureFooterGeometry(
84
261
  row: unknown,
85
- options: { appliedLift: number; gap: number; maxLift: number },
86
- ): number | null {
262
+ options: { appliedLift: number; gapEm: number; fallbackFontSize: number },
263
+ ): FooterGeometry | null {
87
264
  const node = webRow(row);
88
265
  if (node === null) return null;
89
- const anchor = locate(node);
266
+ const anchor = locateFooter(node);
90
267
  if (anchor === null) return null;
91
- const footerBottom = lastTextBottom(anchor.above);
268
+
269
+ const footerBottom = lastTextBottom(anchor.footer);
92
270
  if (footerBottom === null) return null;
93
- const naturalTop = anchor.frame.getBoundingClientRect().top - options.appliedLift;
94
- const lift = options.gap - (naturalTop - footerBottom);
95
- return Math.max(options.maxLift, Math.min(0, Math.round(lift)));
271
+
272
+ const fontSize = footerFontSize(anchor.footer, options.fallbackFontSize);
273
+ // The margin is applied to the row itself, not to the wrapper the sibling is
274
+ // found through: the wrapper keeps its top while the row is pulled up inside
275
+ // it. Take the lift back out of the row's own box.
276
+ const naturalTop = node.getBoundingClientRect().top - options.appliedLift;
277
+ const gapNow = naturalTop - footerBottom;
278
+ // Level with or above the footer text already: this layout is not the one the
279
+ // lift is for, and moving further up would cover the answer.
280
+ if (gapNow <= 0) return null;
281
+ // Too far for a footer to be the element above: it is some other block.
282
+ if (gapNow > lineHeightFor(fontSize) * MAX_GAP_LINES) return null;
283
+
284
+ const gap = Math.round(fontSize * options.gapEm);
285
+ const lift = Math.max(-Math.round(lineHeightFor(fontSize) * MAX_GAP_LINES), gap - gapNow);
286
+ return { lift: Math.min(0, lift), fontSize };
96
287
  }
97
288
 
98
289
  /**
99
- * Calls `onResize` whenever the footer above `row` changes size — a theme
100
- * switching, a font loading, the turn being pushed down by a newer one.
101
- * Returns a cleanup, or null off web or when there is nothing to watch.
290
+ * Calls `onResize` when the row's neighbourhood changes — a theme switching, a
291
+ * font loading, the footer mounting a frame late, or the turn being pushed down
292
+ * by a newer one.
293
+ *
294
+ * Resizing is only half of it: when a new turn is appended the row's own box and
295
+ * its ancestors keep their size and only move, so a ResizeObserver never fires.
296
+ * A MutationObserver on the same ancestors catches the insertion, and the two
297
+ * are coalesced so a burst of changes costs one measurement, taken after the
298
+ * layout has settled.
299
+ *
300
+ * Returns a cleanup, or null off web.
102
301
  */
103
- export function watchFooter(row: unknown, onResize: () => void): (() => void) | null {
302
+ export function watchRow(row: unknown, onResize: () => void): (() => void) | null {
104
303
  const node = webRow(row);
105
304
  if (node === null) return null;
106
- const anchor = locate(node);
107
- if (anchor === null) return null;
108
- const Observer = (globalThis as { ResizeObserver?: ResizeObserverConstructor }).ResizeObserver;
109
- if (Observer === undefined) return null;
110
- const observer = new Observer(onResize);
111
- observer.observe(anchor.above);
112
- // The 12px between "latest turn" and "pushed down by a newer turn" can come
113
- // from the container around this item rather than from the footer's own box.
114
- // Watching the parent catches both without polling.
115
- if (anchor.frame.parentElement !== null) observer.observe(anchor.frame.parentElement);
116
- return () => observer.disconnect();
305
+ const Resize = (globalThis as { ResizeObserver?: ResizeObserverConstructor }).ResizeObserver;
306
+ const Mutation = (globalThis as { MutationObserver?: MutationObserverConstructor })
307
+ .MutationObserver;
308
+ if (Resize === undefined && Mutation === undefined) return null;
309
+
310
+ let pending: ReturnType<typeof setTimeout> | null = null;
311
+ const schedule = () => {
312
+ if (pending !== null) clearTimeout(pending);
313
+ pending = setTimeout(() => {
314
+ pending = null;
315
+ onResize();
316
+ }, 60);
317
+ };
318
+
319
+ const stop: Array<() => void> = [];
320
+ if (Resize !== undefined) {
321
+ const observer = new Resize(schedule);
322
+ if (Mutation !== undefined) {
323
+ const mutations = new Mutation(schedule);
324
+ let frame: MeasuredNode | null = node;
325
+ for (let depth = 0; depth < WATCH_DEPTH && frame !== null; depth += 1) {
326
+ observer.observe(frame);
327
+ // Child insertions are where a new turn shows up; character data
328
+ // (streaming text) is deliberately not watched.
329
+ mutations.observe(frame, { childList: true, subtree: true });
330
+ frame = frame.parentElement;
331
+ }
332
+ stop.push(() => mutations.disconnect());
333
+ } else {
334
+ let frame: MeasuredNode | null = node;
335
+ for (let depth = 0; depth < WATCH_DEPTH && frame !== null; depth += 1) {
336
+ observer.observe(frame);
337
+ frame = frame.parentElement;
338
+ }
339
+ }
340
+ stop.push(() => observer.disconnect());
341
+ } else if (Mutation !== undefined) {
342
+ const mutations = new Mutation(schedule);
343
+ mutations.observe(node.parentElement ?? node, { childList: true, subtree: true });
344
+ stop.push(() => mutations.disconnect());
345
+ }
346
+
347
+ return () => {
348
+ if (pending !== null) clearTimeout(pending);
349
+ for (const dispose of stop) dispose();
350
+ };
117
351
  }
package/index.client.tsx CHANGED
@@ -1,17 +1,6 @@
1
1
  import type { PluginClientContext } from "@getpaseo/plugin/client";
2
- import { StreamStatsSettingsScreen } from "./client/settings-screen";
3
2
  import { contributeStreamStats } from "./client/stream-stats";
4
3
 
5
4
  export default function contribute(client: PluginClientContext) {
6
- const removeStats = contributeStreamStats(client);
7
- const removeSettings = client.addSettingsScreen({
8
- id: "stream-stats",
9
- title: "回答统计行",
10
- icon: "SlidersHorizontal",
11
- Component: StreamStatsSettingsScreen,
12
- });
13
- return () => {
14
- removeStats();
15
- removeSettings();
16
- };
5
+ return contributeStreamStats(client);
17
6
  }
package/index.server.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import type { PluginServerContext } from "@getpaseo/plugin/server";
2
2
  import { ensurePaseoProfile } from "./server/bootstrap";
3
3
  import { createDshProvider } from "./server/provider";
4
- import { streamStatsSettings } from "./shared/settings";
5
4
 
6
5
  /**
7
6
  * Register the DeepSeek Harness provider, provisioning the DSH profile it needs.
@@ -25,7 +24,6 @@ export default function contribute(server: PluginServerContext) {
25
24
  );
26
25
  }
27
26
 
28
- server.registerSettings(streamStatsSettings);
29
27
  server.registerProvider(createDshProvider());
30
28
  return () => {};
31
29
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-dsh",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "DeepSeek Harness (dsh) as a native Paseo provider: question cards, plan mode, thinking levels, steering, images and a real slash menu. 把 DeepSeek Harness 接成 Paseo 原生 provider。",
5
5
  "keywords": [
6
6
  "paseo",
@@ -26,7 +26,6 @@
26
26
  "paseo-plugin.json",
27
27
  "index.server.ts",
28
28
  "server/",
29
- "shared/",
30
29
  "lib/",
31
30
  "bin/",
32
31
  "icon.svg",
@@ -1,148 +0,0 @@
1
- import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
- import { useSettings } from "@getpaseo/plugin/client";
3
- import { Pressable, Text, View } from "react-native";
4
- import { DEFAULT_STREAM_STATS, streamStatsSettings, type StreamStatsSettings } from "../shared/settings";
5
-
6
- /**
7
- * Settings → Plugins → 回答统计行.
8
- *
9
- * The host renders plugin settings only as screens a plugin registers, so the
10
- * two numbers the stats row reads are edited here: how far the row sits under
11
- * the completed-turn footer, and how large its text is. Both default to the
12
- * geometry Paseo's own footer draws with, so leaving this page alone keeps the
13
- * row looking like part of that footer.
14
- */
15
- const FIELDS: Array<{
16
- key: keyof StreamStatsSettings;
17
- label: string;
18
- hint: string;
19
- min: number;
20
- max: number;
21
- step: number;
22
- unit: string;
23
- }> = [
24
- {
25
- key: "gapPx",
26
- label: "与页脚的间距",
27
- hint: "回合页脚最后一行文字到统计行的距离",
28
- min: 0,
29
- max: 24,
30
- step: 1,
31
- unit: "px",
32
- },
33
- {
34
- key: "fontSize",
35
- label: "字号",
36
- hint: "Paseo 自己的回合页脚用 13px",
37
- min: 10,
38
- max: 16,
39
- step: 1,
40
- unit: "px",
41
- },
42
- ];
43
-
44
- export function StreamStatsSettingsScreen({ theme }: PluginSurfaceProps) {
45
- const settings = useSettings(streamStatsSettings);
46
- const values = settings.status === "ready" ? settings.values : DEFAULT_STREAM_STATS;
47
- const editable = settings.status === "ready" && !settings.saving;
48
-
49
- const set = (key: keyof StreamStatsSettings, next: number) => {
50
- if (settings.status !== "ready" || settings.saving) return;
51
- if (settings.values[key] === next) return;
52
- void settings.save({ ...settings.values, [key]: next }, settings.revision);
53
- };
54
-
55
- const muted = theme.colors.foregroundMuted;
56
-
57
- return (
58
- <View style={{ padding: 20, gap: 18 }}>
59
- {FIELDS.map((field) => {
60
- const value = values[field.key];
61
- return (
62
- <View key={field.key} style={{ gap: 6 }}>
63
- <Text style={{ color: theme.colors.foreground, fontSize: 14 }}>{field.label}</Text>
64
- <Text style={{ color: muted, fontSize: 12 }}>{field.hint}</Text>
65
- <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
66
- <StepButton
67
- label="−"
68
- disabled={!editable || value <= field.min}
69
- border={theme.colors.border}
70
- color={theme.colors.foreground}
71
- onPress={() => set(field.key, Math.max(field.min, value - field.step))}
72
- />
73
- <Text
74
- style={{
75
- color: theme.colors.foreground,
76
- fontSize: 14,
77
- minWidth: 64,
78
- textAlign: "center",
79
- fontVariant: ["tabular-nums"],
80
- }}
81
- >
82
- {`${value} ${field.unit}`}
83
- </Text>
84
- <StepButton
85
- label="+"
86
- disabled={!editable || value >= field.max}
87
- border={theme.colors.border}
88
- color={theme.colors.foreground}
89
- onPress={() => set(field.key, Math.min(field.max, value + field.step))}
90
- />
91
- </View>
92
- </View>
93
- );
94
- })}
95
- <Pressable
96
- accessibilityRole="button"
97
- accessibilityLabel="恢复默认"
98
- disabled={!editable}
99
- onPress={() => {
100
- if (settings.status !== "ready" || settings.saving) return;
101
- void settings.save({ ...DEFAULT_STREAM_STATS }, settings.revision);
102
- }}
103
- style={{ alignSelf: "flex-start", paddingVertical: 6 }}
104
- >
105
- <Text style={{ color: muted, fontSize: 12 }}>恢复默认(间距 6px,字号 13px)</Text>
106
- </Pressable>
107
- {settings.status === "ready" ? null : (
108
- <Text style={{ color: theme.colors.statusWarning, fontSize: 12 }}>
109
- {settings.status === "loading"
110
- ? "正在读取设置…"
111
- : `设置不可用:${settings.error}`}
112
- </Text>
113
- )}
114
- {settings.saveError === null ? null : (
115
- <Text style={{ color: theme.colors.statusDanger, fontSize: 12 }}>{settings.saveError}</Text>
116
- )}
117
- </View>
118
- );
119
- }
120
-
121
- function StepButton(props: {
122
- label: string;
123
- disabled: boolean;
124
- border: string;
125
- color: string;
126
- onPress: () => void;
127
- }) {
128
- return (
129
- <Pressable
130
- accessibilityRole="button"
131
- accessibilityLabel={props.label}
132
- disabled={props.disabled}
133
- onPress={props.onPress}
134
- style={{
135
- width: 30,
136
- height: 30,
137
- alignItems: "center",
138
- justifyContent: "center",
139
- borderWidth: 1,
140
- borderColor: props.border,
141
- borderRadius: 6,
142
- opacity: props.disabled ? 0.4 : 1,
143
- }}
144
- >
145
- <Text style={{ color: props.color, fontSize: 15 }}>{props.label}</Text>
146
- </Pressable>
147
- );
148
- }
@@ -1,29 +0,0 @@
1
- import { defineSettings } from "@getpaseo/plugin";
2
- import { z } from "zod";
3
-
4
- /**
5
- * How the answer-stats row sits under a completed turn's footer.
6
- *
7
- * The defaults are what the row was drawn against: Paseo draws that footer at
8
- * `STREAM_METADATA_FONT_SIZE` (13px), and 6px above the row reads as one block
9
- * with it. A theme plugin redraws the footer, and a reader may want a
10
- * different rhythm or text size, so both numbers are host settings instead of
11
- * constants — registered by `index.server.ts`, read by the row and by the
12
- * settings screen.
13
- */
14
- export const streamStatsSettings = defineSettings({
15
- id: "stream-stats",
16
- scope: "host",
17
- version: 1,
18
- schema: z.object({
19
- /** Space between the footer's last line and the stats row, in px. */
20
- gapPx: z.number().min(0).max(24).default(6),
21
- /** The row's text size; Paseo's own footer draws at 13. */
22
- fontSize: z.number().min(10).max(16).default(13),
23
- }),
24
- });
25
-
26
- export type StreamStatsSettings = z.output<typeof streamStatsSettings.schema>;
27
-
28
- /** What the row falls back to while the settings are still loading. */
29
- export const DEFAULT_STREAM_STATS: StreamStatsSettings = { gapPx: 6, fontSize: 13 };