Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Smart Results client minors: credential links, long cells, repeated chart caption (#249)

Oleksandr Ivanchenko6fa1f2ab005e
diff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsx
index 764410c2..51c47a21 100644
--- a/frontend/src/components/MarkdownRenderer.tsx
+++ b/frontend/src/components/MarkdownRenderer.tsx
@@ -6,6 +6,7 @@ import { playSfx } from '../audio/chiptune';
import { HastNode, blockAt, hastText, rehypeSmartIndex, resultBlocks } from '../smartResults';
import type { ReplyPart, ReplySource } from './results/registry';
import { SmartResult } from './results/SmartResult';
+import { ReplyText } from './results/ReplyText';
interface CodeBlockProps {
language?: string;
@@ -172,6 +173,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
};
return (
+ <ReplyText.Provider value={content}>
<div className={`markdown-content text-sm leading-relaxed text-zinc-200 ${className}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
@@ -359,5 +361,6 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
<span className="inline-block w-1.5 h-4 ml-0.5 align-middle bg-sky-400 animate-pulse rounded-sm" />
)}
</div>
+ </ReplyText.Provider>
);
};
diff --git a/frontend/src/components/results/Chart.tsx b/frontend/src/components/results/Chart.tsx
index 5ba31056..54abc510 100644
--- a/frontend/src/components/results/Chart.tsx
+++ b/frontend/src/components/results/Chart.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
-import { ChartBlock, ChartPoint, ChartSeries, inRange, isNum, isObj, isText, optText, parseCommon, uniqueIds } from '../../smartResults';
+import { ChartBlock, ChartPoint, ChartSeries, inRange, isNum, isObj, isText, optText, parseCommon, repeatsReply, uniqueIds } from '../../smartResults';
import type { RendererProps } from './registry';
+import { ReplyText } from './ReplyText';
const MAX_VALUE = 1e15;
@@ -120,6 +121,7 @@ const BarPattern: React.FC<{ id: string; variant: number; color: string }> = ({
*/
export const Chart: React.FC<RendererProps<ChartBlock>> = ({ block }) => {
const uid = useId();
+ const replyText = React.useContext(ReplyText);
const [view, setView] = useState<'chart' | 'table'>('chart');
const [active, setActive] = useState<{ seriesIdx: number; pointIdx: number } | null>(null);
// Drawn at the card's real width (1 SVG unit = 1 px) so axis text stays readable on a 390 px phone.
@@ -380,7 +382,7 @@ export const Chart: React.FC<RendererProps<ChartBlock>> = ({ block }) => {
</div>
)}
- {block.summary && <p className="mt-2 text-xs leading-relaxed text-zinc-400">{block.summary}</p>}
+ {block.summary && !repeatsReply(block.summary, replyText) && <p className="mt-2 text-xs leading-relaxed text-zinc-400">{block.summary}</p>}
</div>
);
};
diff --git a/frontend/src/components/results/Files.tsx b/frontend/src/components/results/Files.tsx
index a8f3a48e..c61a437d 100644
--- a/frontend/src/components/results/Files.tsx
+++ b/frontend/src/components/results/Files.tsx
@@ -67,6 +67,28 @@ function humanSize(bytes: number): string {
return `${v >= 10 ? Math.round(v) : Math.round(v * 10) / 10} ${units[i]}`;
}
+/** A cell longer than this is drawn on one line with an ellipsis; its whole text is on hover and on focus. */
+export const LONG_CELL = 48;
+
+/**
+ * One table cell. A long one (the server already cuts a cell at 300 characters and ends it with an
+ * ellipsis) is clipped to a short width with CSS ellipsis so it cannot stretch the table, takes focus,
+ * and shows its whole text on hover (title) and on focus (it wraps open). The full text stays in the DOM.
+ */
+export const Cell: React.FC<{ text: string }> = ({ text }) =>
+ text.length > LONG_CELL ? (
+ <span
+ tabIndex={0}
+ title={text}
+ data-long-cell=""
+ className="block max-w-[14rem] truncate rounded-sm focus:overflow-visible focus:whitespace-normal focus:break-words focus:outline-none focus:ring-1 focus:ring-sky-500/70"
+ >
+ {text}
+ </span>
+ ) : (
+ <>{text}</>
+ );
+
const TablePreview: React.FC<{ columns: string[]; rows: string[][] }> = ({ columns, rows }) => (
<div className="mt-2 min-w-0 max-w-full overflow-x-auto rounded-lg border border-zinc-800">
<table className="w-full min-w-max border-collapse text-left text-[11px]">
@@ -84,7 +106,7 @@ const TablePreview: React.FC<{ columns: string[]; rows: string[][] }> = ({ colum
<tr key={ri} className="border-b border-zinc-900 last:border-0">
{r.map((c, ci) => (
<td key={ci} className="whitespace-nowrap px-2 py-1.5 text-zinc-300">
- {c}
+ <Cell text={c} />
</td>
))}
</tr>
diff --git a/frontend/src/components/results/ReplyText.ts b/frontend/src/components/results/ReplyText.ts
new file mode 100644
index 00000000..e8fa8397
--- /dev/null
+++ b/frontend/src/components/results/ReplyText.ts
@@ -0,0 +1,7 @@
+import React from 'react';
+
+/**
+ * The reply's own markdown text, set by MarkdownRenderer around its blocks. A block that would repeat a
+ * sentence the reply already shows (a chart's summary caption) leaves it out; see `repeatsReply`.
+ */
+export const ReplyText = React.createContext<string>('');
diff --git a/frontend/src/smartResults.ts b/frontend/src/smartResults.ts
index 1c8e66ed..85e0dd59 100644
--- a/frontend/src/smartResults.ts
+++ b/frontend/src/smartResults.ts
@@ -259,12 +259,16 @@ export const isNum = (v: unknown): v is number => typeof v === 'number' && Numbe
export const inRange = (a: unknown, min: number, max: number): a is unknown[] => Array.isArray(a) && a.length >= min && a.length <= max;
export const uniqueIds = (items: unknown[]) =>
items.every((x) => isObj(x) && typeof x.id === 'string' && x.id !== '') && new Set(items.map((x) => (x as { id: string }).id)).size === items.length;
-/** An http(s) URL, or null. Anything else (javascript:, data:, relative) is not a link a block may show. */
+/**
+ * An http(s) URL, or null. Anything else (javascript:, data:, relative) is not a link a block may show,
+ * and neither is one that carries a username or password (https://user:pw@host/): a link must not leak
+ * a credential into the page, the history or a copy, and "user@" in front of a host is a spoofing trick.
+ */
export const isHttpUrl = (v: unknown): v is string => {
if (typeof v !== 'string' || v.length > 2048) return false;
try {
const u = new URL(v);
- return u.protocol === 'https:' || u.protocol === 'http:';
+ return (u.protocol === 'https:' || u.protocol === 'http:') && u.username === '' && u.password === '';
} catch {
return false;
}
@@ -406,6 +410,17 @@ export function plainText(md: string): string {
/** Letters and digits only, so the rendered table and the block can be compared loosely. */
export const matchKey = (s: string) => plainText(s).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
+/**
+ * Does `caption` say what the reply's own text already says? A chart's summary that the reply's closing
+ * sentence repeats ("October had 2,260 signups and 455 paid.") is not shown a second time under the chart.
+ * Compared loosely, on letters and digits only, and only for a caption long enough to be a sentence.
+ */
+export function repeatsReply(caption: string | null | undefined, replyText: string | null | undefined): boolean {
+ if (!caption || !replyText) return false;
+ const key = matchKey(caption);
+ return key.length >= 8 && matchKey(replyText).includes(key);
+}
+
/**
* The number in a numeric cell: "EUR 1,200", "12 GB", "$9.50", "-3%", "1 200". NaN when there isn't one.
* The column's unit and a leading currency sign are dropped first.
diff --git a/frontend/tests/smartResultsMinors067.test.mjs b/frontend/tests/smartResultsMinors067.test.mjs
new file mode 100644
index 00000000..87c6cc84
--- /dev/null
+++ b/frontend/tests/smartResultsMinors067.test.mjs
@@ -0,0 +1,120 @@
+// Client-side Smart Results minors left from 0.6.5 QA (Rigel):
+// more-M4 a card link with credentials in the URL is refused
+// typed-M3 a long (server-cut) table cell shows an ellipsis and its whole text on hover and focus
+// renderers-D4 a chart caption that the reply's own text already says is not drawn a second time
+// renderers-D6 "Preview, file is longer" only when the total is larger than what is shown
+// typed-M2 (a 20-line file plus blank lines reads "truncated, 22 lines") is decided in the server's
+// line count (src/server/smart_results/files.rs `excerpt`); the client cannot tell blank lines from
+// text it never received, so it is reported to Vega instead of papered over here.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { MarkdownRenderer } from './src/components/MarkdownRenderer';
+ export { isHttpUrl, previewNote, repeatsReply } from './src/smartResults';
+ export { validCards } from './src/components/results/Cards';
+ export { Cell, LONG_CELL } from './src/components/results/Files';
+ export { FIXTURES } from './src/components/results/fixtures';
+ export const md = (props) => renderToStaticMarkup(React.createElement(MarkdownRenderer, props));
+ export const html = (el) => renderToStaticMarkup(el);
+ export { React };
+`);
+
+const count = (s, re) => (s.match(re) ?? []).length;
+
+// ---- more-M4 -------------------------------------------------------------------------------------
+test('isHttpUrl: a URL with a username or password is not a link', () => {
+ assert.equal(m.isHttpUrl('https://user:[email protected]/docs'), false, 'c08');
+ assert.equal(m.isHttpUrl('https://[email protected]/docs'), false, 'username only');
+ assert.equal(m.isHttpUrl('http://:[email protected]/'), false, 'password only');
+ assert.equal(m.isHttpUrl('https://[email protected]/'), false, 'a host spoof through userinfo');
+ assert.equal(m.isHttpUrl('https://example.com/docs?next=https://[email protected]'), true, '@ in the query is not userinfo');
+ assert.equal(m.isHttpUrl('https://example.com/a@b'), true, '@ in the path is not userinfo');
+ assert.equal(m.isHttpUrl('https://example.com/docs'), true);
+ assert.equal(m.isHttpUrl('http://example.com:8080/x'), true);
+ assert.equal(m.isHttpUrl('javascript:alert(1)'), false);
+});
+
+test('cards: a link with credentials makes the block fall back, so no link is drawn', () => {
+ const b = JSON.parse(JSON.stringify(m.FIXTURES.cards.results.blocks[0]));
+ assert.ok(m.validCards(b), 'the fixture is valid');
+ const bad = JSON.parse(JSON.stringify(b));
+ bad.items[0].url = 'https://user:[email protected]/docs';
+ assert.equal(m.validCards(bad), null);
+});
+
+// ---- typed-M3 ------------------------------------------------------------------------------------
+test('a long table cell: one line, an ellipsis, the whole text on hover and focus; a short cell is unchanged', () => {
+ const long = 'x'.repeat(299) + '…';
+ const h = m.html(m.React.createElement(m.Cell, { text: long }));
+ assert.match(h, /data-long-cell/);
+ assert.match(h, /\btruncate\b/, 'clipped with a CSS ellipsis');
+ assert.ok(h.includes(`title="${long}"`), 'the whole text on hover');
+ assert.match(h, /tabindex="0"/i, 'reachable by keyboard');
+ assert.match(h, /focus:whitespace-normal/, 'opens out on focus');
+ assert.ok(h.includes(`>${long}<`), 'the whole text stays in the DOM for a screen reader');
+ assert.equal(m.html(m.React.createElement(m.Cell, { text: 'short' })), 'short');
+ assert.equal(m.html(m.React.createElement(m.Cell, { text: 'y'.repeat(m.LONG_CELL) })), 'y'.repeat(m.LONG_CELL), 'at the limit is not clipped');
+});
+
+test('a files preview with a 300-character cell draws it clipped, once per long cell', () => {
+ const long = 'z'.repeat(299) + '…';
+ const block = JSON.parse(JSON.stringify(m.FIXTURES.files.results.blocks[0]));
+ block.items = [
+ { id: 'a0', attachment_id: 'att', name: 'long.csv', mime: 'text/csv', size_bytes: 900, preview: { kind: 'table', columns: ['id', 'note'], rows: [['1', long], ['2', 'ok']] } },
+ ];
+ const h = m.md({ content: 'Here it is.', results: { version: 1, blocks: [block] }, messageId: 'm1' });
+ assert.equal(count(h, /data-long-cell/g), 1);
+ assert.ok(h.includes(`title="${long}"`));
+});
+
+// ---- renderers-D4 --------------------------------------------------------------------------------
+test('repeatsReply: loose match on letters and digits, only for a sentence-sized caption', () => {
+ const reply = 'Signups kept climbing.\n\nOctober had 2,260 signups and 455 paid.';
+ assert.equal(m.repeatsReply('October had 2,260 signups and 455 paid.', reply), true);
+ assert.equal(m.repeatsReply('october had 2260 signups and 455 paid', reply), true, 'punctuation and case do not matter');
+ assert.equal(m.repeatsReply('Signups doubled since July.', reply), false);
+ assert.equal(m.repeatsReply('Paid', 'Paid signups grew'), false, 'a short caption is not matched');
+ assert.equal(m.repeatsReply('', reply), false);
+ assert.equal(m.repeatsReply(null, reply), false);
+ assert.equal(m.repeatsReply('October had 2,260 signups', ''), false);
+});
+
+test('chart card: the summary caption is left out when the reply says the same sentence, and kept when it does not', () => {
+ const fx = m.FIXTURES.chartLine;
+ const SENT = 'October had 2,260 signups and 455 paid.';
+ const same = m.md({ content: fx.reply, results: fx.results, messageId: 'm1' });
+ assert.match(same, /data-smart-frame="chart"/);
+ // The reply's closing sentence is the only visible copy; the svg <desc> keeps the summary for screen readers.
+ const visible = same.replace(/<desc[^>]*>.*?<\/desc>/g, '');
+ assert.equal(count(visible, new RegExp(SENT.replace(/[.]/g, '\\.'), 'g')), 1, 'drawn once');
+ // A different caption stays.
+ const other = JSON.parse(JSON.stringify(fx.results));
+ other.blocks[0].summary = 'Paid signups grew every month.';
+ const kept = m.md({ content: fx.reply, results: other, messageId: 'm1' });
+ assert.match(kept, /<p[^>]*>Paid signups grew every month\.<\/p>/);
+ // A caption the reply does not repeat at all still shows when the reply is different.
+ const lone = m.md({ content: 'Here is the trend.\n\n' + fx.reply.split('\n\n')[1], results: fx.results, messageId: 'm1' });
+ assert.match(lone, /<p[^>]*>October had 2,260 signups and 455 paid\.<\/p>/, 'no repeat in the reply: the caption stays');
+});
+
+// ---- renderers-D6 --------------------------------------------------------------------------------
+test('previewNote: "Preview, file is longer" only when the preview is cut', () => {
+ const t = (cut) => ({ kind: 'table', columns: ['a', 'b'], rows: [['1', '2'], ['3', '4']], ...cut });
+ const x = (cut, excerpt = 'one\ntwo') => ({ kind: 'text', excerpt, ...cut });
+ assert.equal(m.previewNote(t({ total_rows: 2 })), null, 'total equals the rows shown');
+ assert.equal(m.previewNote(t({ total_rows: 1 })), null, 'total below the rows shown');
+ assert.equal(m.previewNote(t({ total_rows: 2, total_cols: 2 })), null);
+ assert.equal(m.previewNote(x({ total_lines: 2 })), null, 'total_lines equals the lines shown');
+ assert.equal(m.previewNote(x({ total_lines: 1 })), null);
+ assert.equal(m.previewNote(t({})), null);
+ assert.equal(m.previewNote(t({ total_rows: 143 })), 'Showing 2 of 143 rows');
+ assert.equal(m.previewNote(x({ total_lines: 512 })), 'Showing 2 of 512 lines');
+ assert.equal(m.previewNote(t({ truncated: true })), 'Preview, file is longer');
+ assert.equal(m.previewNote(x({ truncated: true })), 'Preview, file is longer');
+});