openvibers/openvibe.sdk Commits

SDK: add shared paged chat history helpers (#190)

OP OpenVibers committed 3 days ago · 722dc7511e · 13 files, +257 −34

* SDK: share paged chat history helper

* Merge origin/main and reserve SDK 0.140.0

Changes

ddiff --git a/CHANGELOG.md b/CHANGELOG.md
iindex 343b2e8..4af1bde 100644
---- a/CHANGELOG.md
++++ b/CHANGELOG.md
@@@ -1,5 +1,9 @@
# Changelog
++## 0.140.0 — 2026-11-10
++
++- `chat.history.pages()` asynchronously iterates newest-first cursor pages; `chat.history.attach()` loads older pages on scroll while preserving the visible message anchor. The same helper is available to Live and Dock.
++
## 0.139.0 (2026-11-10)
- `community.comments`: shared comment thread resolve/read/write/edit/delete and visibility methods, including ordered pages and paged replies.
ddiff --git a/README.md b/README.md
iindex 5a42279..65637e2 100644
---- a/README.md
++++ b/README.md
@@@ -13,7 +13,7 @@ npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags
> Supported browser and server clients for the OpenVibe platform.
--**Status:** alpha, v0.139.0 (the five 1.0 core entries — `core`, `auth`, `events`, `db` and `media` — are frozen: their exported names change only with a major release; roadmap Wave 2; developer apps from Wave 20; Media objects v2 from Wave 4; the Tools platform API; Search, Chat, AI, Vision and consent clients; sign-in with recovery and a client health check). Every release is tagged (see [CHANGELOG.md](CHANGELOG.md)). Tested against local stub servers and the built-in mock platform only, never against the live platform. Services pin release tags; each repository's `STATUS.json` names the one it uses.
++**Status:** alpha, v0.140.0 (the five 1.0 core entries — `core`, `auth`, `events`, `db` and `media` — are frozen: their exported names change only with a major release; roadmap Wave 2; developer apps from Wave 20; Media objects v2 from Wave 4; the Tools platform API; Search, Chat, AI, Vision and consent clients; sign-in with recovery and a client health check). Every release is tagged (see [CHANGELOG.md](CHANGELOG.md)). Tested against local stub servers and the built-in mock platform only, never against the live platform. Services pin release tags; each repository's `STATUS.json` names the one it uses.
**Plan:** OpenVibe End-to-End Realignment & Implementation Plan, revision 3 (20 Sep 2026), §3.2; roadmap §30.
**License:** MIT ([LICENSE](LICENSE)). This package is a library that apps outside the network embed, so it uses MIT. The OpenVibe services themselves stay AGPL-3.0.
@@@ -22,7 +22,7 @@ npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags
After v0.97.1 is tagged:
```bash
--npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.139.0
++npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.140.0
```
It has no runtime dependencies. It needs Node ≥ 20, or any browser with `fetch`, Web Crypto and `TextDecoder`. There is no build step. The package is CommonJS with ESM entry points (`import` works). Each subpath has its own `.d.ts`. For a page with no bundler, `browser/openvibe-sdk.mjs` is one self-contained ES module of the browser-safe subpaths (see [Browser without a bundler](#browser-without-a-bundler)). It does not depend on `openvibe-contracts` at runtime: it copies the contract types it uses (from the temporary Contracts sharing branch, a devDependency the tests check them against).
ddiff --git a/STATUS.json b/STATUS.json
iindex 3a2f28c..421f14a 100644
---- a/STATUS.json
++++ b/STATUS.json
@@@ -3,7 +3,7 @@
"stage": "alpha",
"code": true,
"wave": "W2",
-- "version": "0.139.0",
++ "version": "0.140.0",
"plan": "OpenVibe End-to-End Realignment & Implementation Plan, revision 3 (20 Sep 2026), \u00a73.2; roadmap \u00a730",
"deployed": false,
"deployment": "none: a package released as git tags; services and apps pin a tag",
ddiff --git a/browser/openvibe-sdk.mjs b/browser/openvibe-sdk.mjs
iindex 19cdad2..565cdee 100644
---- a/browser/openvibe-sdk.mjs
++++ b/browser/openvibe-sdk.mjs
@@@ -1,4 +1,4 @@
--// Generated by scripts/browser-bundle.js from browser.js (openvibe-sdk 0.139.0, MIT). Do not edit.
++// Generated by scripts/browser-bundle.js from browser.js (openvibe-sdk 0.140.0, MIT). Do not edit.
// One self-contained ES module: core at the top level plus the browser-safe subpaths as namespaces
// (auth, locker, registry, trust, levels, modules, realtime, media, cam, mediaUpload, ui, community, homeFeed, bot, search, bench, meme, vision, themes, design, redact, chat, ai, credentials, jobs, tools, projects, geo). No server-only code: no service tokens, JWT verification, events, identity.
/* eslint-disable */
@@@ -37,12 +37,12 @@ module.exports = {
design: __load(39),
redact: __load(40),
chat: __load(41),
-- ai: __load(42),
-- credentials: __load(43),
-- jobs: __load(44),
-- tools: __load(46),
-- projects: __load(47),
-- geo: __load(48),
++ ai: __load(43),
++ credentials: __load(44),
++ jobs: __load(45),
++ tools: __load(47),
++ projects: __load(48),
++ geo: __load(49),
};
},
// ── 1: src/core/index.js ───────────────────────────────────────────
@@@ -57,7 +57,7 @@ const { paginate, offsetPager } = __load(7);
const semver = __load(6);
/** The package version (test/version.test.js keeps it equal to package.json). */
--const SDK_VERSION = '0.139.0';
++const SDK_VERSION = '0.140.0';
module.exports = {
createClient,
@@@ -4801,6 +4801,7 @@ function (module, exports) {
const { isOpenVibeError } = __load(3);
const enc = encodeURIComponent;
++const history = __load(42);
function createChatClient(client, defaults = {}) {
const { baseUrl } = defaults;
@@@ -4813,12 +4814,14 @@ function createChatClient(client, defaults = {}) {
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
return {
++ /** Shared async page iterator and scroll-preserving DOM history controller. */
++ history,
/** Vibe's model comparison API, authenticated as the person. */
ask: (input, o = {}) => call({ method: 'POST', path: '/api/vibe/ask', json: input, ...once }, o),
pick: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/pick', json: { message_id: messageId, model }, ...once }, o),
prefer: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/prefer', json: { message_id: messageId, model }, ...once }, o),
global: {
-- /** { messages, … } — the global feed; query: limit, after_id (a delta after a message id). */
++ /** { messages, more } — newest-first page; query: limit, before (exclusive ID), after_id (live delta). */
history: (query = {}, o = {}) => call({ path: '/api/chat/global/history', query }, o),
/** Post to global chat as the token's person. { message: string, reply_to_id?, auto_delete_minutes? } */
send: (message, extra = {}, o = {}) => call({ method: 'POST', path: '/api/chat/send', json: { message, ...extra }, ...once }, o),
@@@ -5020,9 +5023,88 @@ function createFeedPublisher(client, { feed, key, baseUrl } = {}) {
};
}
--module.exports = { createChatClient, createInboxVisitor, createFeedPublisher };
++module.exports = { createChatClient, createInboxVisitor, createFeedPublisher, history };
},
--// ── 42: src/ai.js ───────────────────────────────────────────────────
++// ── 42: src/chat-history.js ─────────────────────────────────────────
++function (module, exports) {
++'use strict';
++
++/** Shared older-page iterator and scroll controller for Chat, Live and the Dock. */
++function pages(readPage, { limit = 50, before = null, signal } = {}) {
++ if (typeof readPage !== 'function') throw new TypeError('readPage must be a function');
++ const pageSize = Math.min(100, Math.max(1, Number(limit) || 50));
++ return {
++ async *[Symbol.asyncIterator]() {
++ let cursor = before == null ? null : Number(before);
++ while (true) {
++ if (signal && signal.aborted) throw signal.reason || new Error('History read aborted');
++ const query = { limit: pageSize, ...(cursor == null ? {} : { before: cursor }) };
++ const page = await readPage(query, { signal });
++ if (!page || !Array.isArray(page.messages)) return;
++ yield page;
++ if (!page.more || !page.messages.length) return;
++ const oldest = Number(page.messages[page.messages.length - 1].id);
++ if (!Number.isFinite(oldest) || oldest <= 0 || oldest === cursor) return;
++ cursor = oldest;
++ }
++ },
++ };
++}
++
++function attach({ feed, status = null, fetchPage, render, hasMore = true, threshold = 600, scrollToBottom = true } = {}) {
++ if (!feed || typeof feed.addEventListener !== 'function') throw new TypeError('feed must be a scrollable element');
++ if (typeof fetchPage !== 'function' || typeof render !== 'function') throw new TypeError('fetchPage and render are required');
++ let more = hasMore !== false;
++ let loading = false;
++ let disposed = false;
++ const state = status || feed.querySelector('[data-history-status]');
++ const setStatus = (message) => {
++ if (!state) return;
++ state.textContent = message;
++ state.hidden = !message;
++ };
++ setStatus(more ? '' : 'The start of the chat');
++
++ async function load() {
++ if (disposed || loading || !more) return;
++ const first = feed.querySelector('[data-id]');
++ if (!first) return;
++ loading = true;
++ setStatus('Loading earlier messages');
++ const cursor = Number(first.dataset.id);
++ const anchorTop = first.getBoundingClientRect().top;
++ try {
++ const page = await fetchPage(cursor);
++ if (!page || !Array.isArray(page.messages)) { setStatus(''); return; }
++ const anchor = feed.querySelector('[data-id="' + first.dataset.id + '"]');
++ // API pages are newest-first; prepend oldest-first to preserve chronological display.
++ page.messages.slice().reverse().forEach((message) => {
++ if (!message || feed.querySelector('[data-id="' + Number(message.id) + '"]')) return;
++ feed.insertBefore(render(message), anchor || (state && state.nextSibling) || feed.firstChild);
++ });
++ more = !!page.more;
++ setStatus(more ? '' : 'The start of the chat');
++ if (anchor) feed.scrollTop += anchor.getBoundingClientRect().top - anchorTop;
++ } catch {
++ setStatus('');
++ } finally {
++ loading = false;
++ }
++ }
++ const onScroll = () => { if (feed.scrollTop < threshold) load(); };
++ feed.addEventListener('scroll', onScroll);
++ if (scrollToBottom) feed.scrollTop = feed.scrollHeight;
++ return {
++ load,
++ get loading() { return loading; },
++ get more() { return more; },
++ dispose() { disposed = true; feed.removeEventListener('scroll', onScroll); },
++ };
++}
++
++module.exports = { pages, attach };
++},
++// ── 43: src/ai.js ───────────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
@@@ -5212,7 +5294,7 @@ function createAiClient(client, defaults = {}) {
module.exports = { createAiClient, TERMINAL, OPS, CLASSES };
},
--// ── 43: src/credentials.js ──────────────────────────────────────────
++// ── 44: src/credentials.js ──────────────────────────────────────────
function (module, exports) {
'use strict';
@@@ -5230,7 +5312,7 @@ function createCredentialsClient(client, defaults = {}) {
module.exports = { createCredentialsClient };
},
--// ── 44: src/jobs.js ─────────────────────────────────────────────────
++// ── 45: src/jobs.js ─────────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
@@@ -5268,7 +5350,7 @@ function (module, exports) {
*/
const { OpenVibeError, isOpenVibeError } = __load(3);
const { newIdempotencyKey } = __load(5);
--const { appendFiles } = __load(45);
++const { appendFiles } = __load(46);
const { parseSSE } = __load(25);
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);
@@@ -5432,7 +5514,7 @@ function createJobsClient(client, { baseUrl, service = 'tools', audience = 'open
module.exports = { createJobsClient, isTerminal, TERMINAL_STATES: [...TERMINAL] };
},
--// ── 45: src/core/form.js ────────────────────────────────────────────
++// ── 46: src/core/form.js ────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
@@@ -5466,7 +5548,7 @@ function appendFiles(form, list, where) {
module.exports = { isBlob, isUpload, appendFiles };
},
--// ── 46: src/tools.js ────────────────────────────────────────────────
++// ── 47: src/tools.js ────────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
@@@ -5500,8 +5582,8 @@ function (module, exports) {
*/
const { OpenVibeError, isOpenVibeError } = __load(3);
const { newIdempotencyKey } = __load(5);
--const { isUpload, appendFiles } = __load(45);
--const { createJobsClient } = __load(44);
++const { isUpload, appendFiles } = __load(46);
++const { createJobsClient } = __load(45);
const enc = encodeURIComponent;
const ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
@@@ -5761,7 +5843,7 @@ function createToolsClient(client, { baseUrl, service = 'tools', audience = 'ope
module.exports = { createToolsClient, ToolRunError, isToolRunError };
},
--// ── 47: src/projects.js ─────────────────────────────────────────────
++// ── 48: src/projects.js ─────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
@@@ -5877,7 +5959,7 @@ function createProjectsClient(client, { baseUrl } = {}) {
module.exports = { createProjectsClient };
},
--// ── 48: src/geo.js ──────────────────────────────────────────────────
++// ── 49: src/geo.js ──────────────────────────────────────────────────
function (module, exports) {
'use strict';
/**
ddiff --git a/docs/api-surface.json b/docs/api-surface.json
iindex fd2969d..0baf372 100644
---- a/docs/api-surface.json
++++ b/docs/api-surface.json
@@@ -73,7 +73,8 @@
"object": [
"createChatClient",
"createFeedPublisher",
-- "createInboxVisitor"
++ "createInboxVisitor",
++ "history"
]
},
"chatApps": {
@@@ -587,7 +588,13 @@
"openvibe-sdk/chat": {
"createChatClient": "function",
"createFeedPublisher": "function",
-- "createInboxVisitor": "function"
++ "createInboxVisitor": "function",
++ "history": {
++ "object": [
++ "attach",
++ "pages"
++ ]
++ }
},
"openvibe-sdk/chat-apps": {
"APP_LIMITS": {
ddiff --git a/esm/chat.mjs b/esm/chat.mjs
iindex 2cf71ba..3d4cfb5 100644
---- a/esm/chat.mjs
++++ b/esm/chat.mjs
@@@ -2,6 +2,6 @@
import cjs from '../src/chat.js';
export const {
-- createChatClient, createInboxVisitor, createFeedPublisher,
++ createChatClient, createInboxVisitor, createFeedPublisher, history,
} = cjs;
export default cjs;
ddiff --git a/package-lock.json b/package-lock.json
iindex 43e6019..7ed6808 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-sdk",
-- "version": "0.139.0",
++ "version": "0.140.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-sdk",
-- "version": "0.139.0",
++ "version": "0.140.0",
"license": "MIT",
"bin": {
"openvibe-download": "bin/openvibe-download.js"
ddiff --git a/package.json b/package.json
iindex 83bdf2c..c1bf859 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-sdk",
-- "version": "0.139.0",
++ "version": "0.140.0",
"description": "Supported browser and server clients for the OpenVibe platform: auth (incl. developer apps), registry discovery, identity, user modules, events, realtime, media, community, Bot robots, search, chat, AI runs, Tools (registry, run API and jobs), VIP memberships and developer projects, the async PostgreSQL data layer (db) and the Valkey cache, limits store, queue and pub/sub, with deadlines, safe retries, problem errors and trace propagation.",
"main": "index.js",
"types": "types/index.d.ts",
ddiff --git a/src/chat-history.js b/src/chat-history.js
nnew file mode 100644
iindex 0000000..46bc138
---- /dev/null
++++ b/src/chat-history.js
@@@ -0,0 +1,76 @@
++'use strict';
++
++/** Shared older-page iterator and scroll controller for Chat, Live and the Dock. */
++function pages(readPage, { limit = 50, before = null, signal } = {}) {
++ if (typeof readPage !== 'function') throw new TypeError('readPage must be a function');
++ const pageSize = Math.min(100, Math.max(1, Number(limit) || 50));
++ return {
++ async *[Symbol.asyncIterator]() {
++ let cursor = before == null ? null : Number(before);
++ while (true) {
++ if (signal && signal.aborted) throw signal.reason || new Error('History read aborted');
++ const query = { limit: pageSize, ...(cursor == null ? {} : { before: cursor }) };
++ const page = await readPage(query, { signal });
++ if (!page || !Array.isArray(page.messages)) return;
++ yield page;
++ if (!page.more || !page.messages.length) return;
++ const oldest = Number(page.messages[page.messages.length - 1].id);
++ if (!Number.isFinite(oldest) || oldest <= 0 || oldest === cursor) return;
++ cursor = oldest;
++ }
++ },
++ };
++}
++
++function attach({ feed, status = null, fetchPage, render, hasMore = true, threshold = 600, scrollToBottom = true } = {}) {
++ if (!feed || typeof feed.addEventListener !== 'function') throw new TypeError('feed must be a scrollable element');
++ if (typeof fetchPage !== 'function' || typeof render !== 'function') throw new TypeError('fetchPage and render are required');
++ let more = hasMore !== false;
++ let loading = false;
++ let disposed = false;
++ const state = status || feed.querySelector('[data-history-status]');
++ const setStatus = (message) => {
++ if (!state) return;
++ state.textContent = message;
++ state.hidden = !message;
++ };
++ setStatus(more ? '' : 'The start of the chat');
++
++ async function load() {
++ if (disposed || loading || !more) return;
++ const first = feed.querySelector('[data-id]');
++ if (!first) return;
++ loading = true;
++ setStatus('Loading earlier messages');
++ const cursor = Number(first.dataset.id);
++ const anchorTop = first.getBoundingClientRect().top;
++ try {
++ const page = await fetchPage(cursor);
++ if (!page || !Array.isArray(page.messages)) { setStatus(''); return; }
++ const anchor = feed.querySelector('[data-id="' + first.dataset.id + '"]');
++ // API pages are newest-first; prepend oldest-first to preserve chronological display.
++ page.messages.slice().reverse().forEach((message) => {
++ if (!message || feed.querySelector('[data-id="' + Number(message.id) + '"]')) return;
++ feed.insertBefore(render(message), anchor || (state && state.nextSibling) || feed.firstChild);
++ });
++ more = !!page.more;
++ setStatus(more ? '' : 'The start of the chat');
++ if (anchor) feed.scrollTop += anchor.getBoundingClientRect().top - anchorTop;
++ } catch {
++ setStatus('');
++ } finally {
++ loading = false;
++ }
++ }
++ const onScroll = () => { if (feed.scrollTop < threshold) load(); };
++ feed.addEventListener('scroll', onScroll);
++ if (scrollToBottom) feed.scrollTop = feed.scrollHeight;
++ return {
++ load,
++ get loading() { return loading; },
++ get more() { return more; },
++ dispose() { disposed = true; feed.removeEventListener('scroll', onScroll); },
++ };
++}
++
++module.exports = { pages, attach };
ddiff --git a/src/chat.js b/src/chat.js
iindex 90e4a4a..91dc48d 100644
---- a/src/chat.js
++++ b/src/chat.js
@@@ -29,6 +29,7 @@
const { isOpenVibeError } = require('./core/errors');
const enc = encodeURIComponent;
++const history = require('./chat-history');
function createChatClient(client, defaults = {}) {
const { baseUrl } = defaults;
@@@ -41,12 +42,14 @@ function createChatClient(client, defaults = {}) {
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
return {
++ /** Shared async page iterator and scroll-preserving DOM history controller. */
++ history,
/** Vibe's model comparison API, authenticated as the person. */
ask: (input, o = {}) => call({ method: 'POST', path: '/api/vibe/ask', json: input, ...once }, o),
pick: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/pick', json: { message_id: messageId, model }, ...once }, o),
prefer: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/prefer', json: { message_id: messageId, model }, ...once }, o),
global: {
-- /** { messages, … } — the global feed; query: limit, after_id (a delta after a message id). */
++ /** { messages, more } — newest-first page; query: limit, before (exclusive ID), after_id (live delta). */
history: (query = {}, o = {}) => call({ path: '/api/chat/global/history', query }, o),
/** Post to global chat as the token's person. { message: string, reply_to_id?, auto_delete_minutes? } */
send: (message, extra = {}, o = {}) => call({ method: 'POST', path: '/api/chat/send', json: { message, ...extra }, ...once }, o),
@@@ -248,4 +251,4 @@ function createFeedPublisher(client, { feed, key, baseUrl } = {}) {
};
}
--module.exports = { createChatClient, createInboxVisitor, createFeedPublisher };
++module.exports = { createChatClient, createInboxVisitor, createFeedPublisher, history };
ddiff --git a/src/core/index.js b/src/core/index.js
iindex 8a8506c..fc3799a 100644
---- a/src/core/index.js
++++ b/src/core/index.js
@@@ -8,7 +8,7 @@ const { paginate, offsetPager } = require('./paginate');
const semver = require('./semver');
/** The package version (test/version.test.js keeps it equal to package.json). */
--const SDK_VERSION = '0.139.0';
++const SDK_VERSION = '0.140.0';
module.exports = {
createClient,
ddiff --git a/test/chat.test.js b/test/chat.test.js
iindex 0408bd7..f54b3cf 100644
---- a/test/chat.test.js
++++ b/test/chat.test.js
@@@ -7,7 +7,7 @@
const assert = require('node:assert/strict');
const { stubServer, send, run } = require('./helpers');
const { createClient } = require('../src/core');
--const { createChatClient, createInboxVisitor, createFeedPublisher } = require('../src/chat');
++const { createChatClient, createInboxVisitor, createFeedPublisher, history } = require('../src/chat');
async function chatStub() {
let busy = 0;
@@@ -20,6 +20,36 @@ async function chatStub() {
}
run([
++ ['the ESM chat entry exports the shared history helper', async () => {
++ const esm = await import('../esm/chat.mjs');
++ assert.equal(typeof esm.history.pages, 'function');
++ assert.equal(typeof esm.history.attach, 'function');
++ }],
++ ['history pages iterate backward from newest-first reads and the controller preserves its anchor', async () => {
++ const requests = [];
++ const iterator = history.pages(async (query) => {
++ requests.push(query);
++ return query.before == null
++ ? { messages: [{ id: 4 }, { id: 3 }], more: true }
++ : { messages: [{ id: 2 }, { id: 1 }], more: false };
++ }, { limit: 2 });
++ const pages = [];
++ for await (const page of iterator) pages.push(page.messages.map((m) => m.id));
++ assert.deepEqual(pages, [[4, 3], [2, 1]]);
++ assert.deepEqual(requests, [{ limit: 2 }, { limit: 2, before: 3 }]);
++
++ const feed = { children: [], scrollTop: 0, scrollHeight: 0, handlers: {}, get firstChild() { return this.children[0]; }, addEventListener(name, fn) { this.handlers[name] = fn; }, removeEventListener(name) { delete this.handlers[name]; }, querySelector(selector) { const match = /^\[data-id="(\d+)"\]$/.exec(selector); return match ? this.children.find((x) => x.dataset && x.dataset.id === match[1]) : selector === '[data-id]' ? this.children.find((x) => x.dataset && x.dataset.id) : null; }, insertBefore(item, anchor) { this.children.splice(this.children.indexOf(anchor), 0, item); this.scrollHeight = this.children.length * 20; } };
++ const message = (id) => { const item = { dataset: { id: String(id) }, getBoundingClientRect: () => ({ top: feed.children.indexOf(item) * 20 }) }; return item; };
++ const status = { hidden: true, textContent: '', nextSibling: null };
++ const anchor = message(3), newest = message(4); feed.children = [status, anchor, newest]; feed.scrollHeight = 60;
++ const ctl = history.attach({ feed, status, fetchPage: async () => ({ messages: [{ id: 2 }, { id: 1 }], more: false }), render: (m) => message(m.id), hasMore: true });
++ feed.scrollTop = 100; const viewportTop = anchor.getBoundingClientRect().top - feed.scrollTop; await ctl.load();
++ assert.deepEqual(feed.children.filter((x) => x.dataset).map((x) => Number(x.dataset.id)), [1, 2, 3, 4]);
++ assert.equal(anchor.getBoundingClientRect().top - feed.scrollTop, viewportTop, 'the prior top item stays at the same viewport position');
++ assert.equal(ctl.more, false);
++ assert.equal(status.textContent, 'The start of the chat');
++ ctl.dispose();
++ }],
['Vibe comparison sends models and records a pick and preference', async () => {
const srv = await chatStub();
const chat = createChatClient(createClient({ baseUrls: { chat: srv.url }, token: 'person-token' }));
ddiff --git a/types/chat.d.ts b/types/chat.d.ts
iindex 63952d0..1f78bc0 100644
---- a/types/chat.d.ts
++++ b/types/chat.d.ts
@@@ -17,13 +17,34 @@ export interface RoomInsight {
state: 'ready' | 'quiet' | 'off';
}
export type ChatMessageView = 'bubbles' | 'room';
++export interface ChatHistoryPage<T extends { id: number | string } = { id: number | string; [field: string]: unknown }> { messages: T[]; more: boolean; [field: string]: unknown; }
++export interface ChatHistoryOptions { limit?: number; before?: number | string | null; signal?: AbortSignal; }
++export interface ChatHistoryHelper {
++ /** Yield newest-first pages, following each page's oldest message ID until `more` is false. */
++ pages<T extends { id: number | string } = { id: number | string; [field: string]: unknown }>(
++ readPage: (query: { limit: number; before?: number | string }, opts: { signal?: AbortSignal }) => Promise<ChatHistoryPage<T>>,
++ options?: ChatHistoryOptions,
++ ): AsyncIterable<ChatHistoryPage<T>>;
++ /** Load older pages near the feed top, prepend in display order and preserve the visible anchor. */
++ attach<T extends { id: number | string }>(options: {
++ feed: HTMLElement;
++ status?: HTMLElement | null;
++ fetchPage: (before: number) => Promise<ChatHistoryPage<T>>;
++ render: (message: T) => HTMLElement;
++ hasMore?: boolean;
++ threshold?: number;
++ scrollToBottom?: boolean;
++ }): { load(): Promise<void>; readonly loading: boolean; readonly more: boolean; dispose(): void };
++}
++export const history: ChatHistoryHelper;
export interface ChatClient {
++ history: ChatHistoryHelper;
/** Ask Vibe using Auto, one catalogue model, or two to three models side by side. */
ask(input: { message: string; models?: string[]; slug?: string; fresh?: boolean; system_prompt?: string; temperature?: number }, opts?: Opts): Promise<{ chat: Json; message: Json }>;
pick(messageId: number, model: string, opts?: Opts): Promise<{ chat: Json; model: string }>;
prefer(messageId: number, model: string, opts?: Opts): Promise<{ recorded: boolean; model: string }>;
global: {
-- history(query?: { limit?: number; after_id?: number }, opts?: Opts): Promise<Json>;
++ history(query?: { limit?: number; before?: number; after_id?: number }, opts?: Opts): Promise<Json>;
send(message: string, extra?: { reply_to_id?: number; auto_delete_minutes?: number }, opts?: Opts): Promise<Json>;
search(query?: { q?: string; user_id?: number; stream_id?: number; limit?: number; offset?: number }, opts?: Opts): Promise<{ messages: Json[]; total?: number }>;
};