openvibers/openvibe.sdk Commits
SDK: add shared paged chat history helpers (#190)
Changes
@@@ -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.@@@ -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/tagsAfter 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).@@@ -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",@@@ -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 = 'openmodule.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 = 'opemodule.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';/**@@@ -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": {@@@ -2,6 +2,6 @@import cjs from '../src/chat.js';export const {-- createChatClient, createInboxVisitor, createFeedPublisher,++ createChatClient, createInboxVisitor, createFeedPublisher, history,} = cjs;export default cjs;@@@ -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"@@@ -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",nnew file mode 100644@@@ -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 };@@@ -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 };@@@ -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,@@@ -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' }));@@@ -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 }>;};
@@ -1,5 +1,9 @@
@@ -1,5 +1,9 @@
# Changelog
# 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)
## 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.
- `community.comments`: shared comment thread resolve/read/write/edit/delete and visibility methods, including ordered pages and paged replies.
@@ -13,7 +13,7 @@ npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags
@@ -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.
> 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.
**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.
**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
@@ -22,7 +22,7 @@ npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags
After v0.97.1 is tagged:
After v0.97.1 is tagged:
```bash
```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).
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).
@@ -3,7 +3,7 @@
@@ -3,7 +3,7 @@
"stage": "alpha",
"stage": "alpha",
"code": true,
"code": true,
"wave": "W2",
"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",
"plan": "OpenVibe End-to-End Realignment & Implementation Plan, revision 3 (20 Sep 2026), \u00a73.2; roadmap \u00a730",
"deployed": false,
"deployed": false,
"deployment": "none: a package released as git tags; services and apps pin a tag",
"deployment": "none: a package released as git tags; services and apps pin a tag",
@@ -1,4 +1,4 @@
@@ -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
// 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.
// (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 */
/* eslint-disable */
@@ -37,12 +37,12 @@ module.exports = {
@@ -37,12 +37,12 @@ module.exports = {
design: __load(39),
design: __load(39),
redact: __load(40),
redact: __load(40),
chat: __load(41),
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 ───────────────────────────────────────────
// ── 1: src/core/index.js ───────────────────────────────────────────
@@ -57,7 +57,7 @@ const { paginate, offsetPager } = __load(7);
@@ -57,7 +57,7 @@ const { paginate, offsetPager } = __load(7);
const semver = __load(6);
const semver = __load(6);
/** The package version (test/version.test.js keeps it equal to package.json). */
/** 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 = {
module.exports = {
createClient,
createClient,
@@ -4801,6 +4801,7 @@ function (module, exports) {
@@ -4801,6 +4801,7 @@ function (module, exports) {
const { isOpenVibeError } = __load(3);
const { isOpenVibeError } = __load(3);
const enc = encodeURIComponent;
const enc = encodeURIComponent;
+const history = __load(42);
function createChatClient(client, defaults = {}) {
function createChatClient(client, defaults = {}) {
const { baseUrl } = defaults;
const { baseUrl } = defaults;
@@ -4813,12 +4814,14 @@ function createChatClient(client, defaults = {}) {
@@ -4813,12 +4814,14 @@ function createChatClient(client, defaults = {}) {
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
return {
return {
+ /** Shared async page iterator and scroll-preserving DOM history controller. */
+ history,
/** Vibe's model comparison API, authenticated as the person. */
/** Vibe's model comparison API, authenticated as the person. */
ask: (input, o = {}) => call({ method: 'POST', path: '/api/vibe/ask', json: input, ...once }, o),
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),
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),
prefer: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/prefer', json: { message_id: messageId, model }, ...once }, o),
global: {
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),
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? } */
/** 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),
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 } = {}) {
@@ -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) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -5212,7 +5294,7 @@ function createAiClient(client, defaults = {}) {
@@ -5212,7 +5294,7 @@ function createAiClient(client, defaults = {}) {
module.exports = { createAiClient, TERMINAL, OPS, CLASSES };
module.exports = { createAiClient, TERMINAL, OPS, CLASSES };
},
},
-// ── 43: src/credentials.js ──────────────────────────────────────────
+// ── 44: src/credentials.js ──────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
@@ -5230,7 +5312,7 @@ function createCredentialsClient(client, defaults = {}) {
@@ -5230,7 +5312,7 @@ function createCredentialsClient(client, defaults = {}) {
module.exports = { createCredentialsClient };
module.exports = { createCredentialsClient };
},
},
-// ── 44: src/jobs.js ─────────────────────────────────────────────────
+// ── 45: src/jobs.js ─────────────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -5268,7 +5350,7 @@ function (module, exports) {
@@ -5268,7 +5350,7 @@ function (module, exports) {
*/
*/
const { OpenVibeError, isOpenVibeError } = __load(3);
const { OpenVibeError, isOpenVibeError } = __load(3);
const { newIdempotencyKey } = __load(5);
const { newIdempotencyKey } = __load(5);
-const { appendFiles } = __load(45);
+const { appendFiles } = __load(46);
const { parseSSE } = __load(25);
const { parseSSE } = __load(25);
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);
@@ -5432,7 +5514,7 @@ function createJobsClient(client, { baseUrl, service = 'tools', audience = 'open
@@ -5432,7 +5514,7 @@ function createJobsClient(client, { baseUrl, service = 'tools', audience = 'open
module.exports = { createJobsClient, isTerminal, TERMINAL_STATES: [...TERMINAL] };
module.exports = { createJobsClient, isTerminal, TERMINAL_STATES: [...TERMINAL] };
},
},
-// ── 45: src/core/form.js ────────────────────────────────────────────
+// ── 46: src/core/form.js ────────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -5466,7 +5548,7 @@ function appendFiles(form, list, where) {
@@ -5466,7 +5548,7 @@ function appendFiles(form, list, where) {
module.exports = { isBlob, isUpload, appendFiles };
module.exports = { isBlob, isUpload, appendFiles };
},
},
-// ── 46: src/tools.js ────────────────────────────────────────────────
+// ── 47: src/tools.js ────────────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -5500,8 +5582,8 @@ function (module, exports) {
@@ -5500,8 +5582,8 @@ function (module, exports) {
*/
*/
const { OpenVibeError, isOpenVibeError } = __load(3);
const { OpenVibeError, isOpenVibeError } = __load(3);
const { newIdempotencyKey } = __load(5);
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 enc = encodeURIComponent;
const ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
const ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
@@ -5761,7 +5843,7 @@ function createToolsClient(client, { baseUrl, service = 'tools', audience = 'ope
@@ -5761,7 +5843,7 @@ function createToolsClient(client, { baseUrl, service = 'tools', audience = 'ope
module.exports = { createToolsClient, ToolRunError, isToolRunError };
module.exports = { createToolsClient, ToolRunError, isToolRunError };
},
},
-// ── 47: src/projects.js ─────────────────────────────────────────────
+// ── 48: src/projects.js ─────────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -5877,7 +5959,7 @@ function createProjectsClient(client, { baseUrl } = {}) {
@@ -5877,7 +5959,7 @@ function createProjectsClient(client, { baseUrl } = {}) {
module.exports = { createProjectsClient };
module.exports = { createProjectsClient };
},
},
-// ── 48: src/geo.js ──────────────────────────────────────────────────
+// ── 49: src/geo.js ──────────────────────────────────────────────────
function (module, exports) {
function (module, exports) {
'use strict';
'use strict';
/**
/**
@@ -73,7 +73,8 @@
@@ -73,7 +73,8 @@
"object": [
"object": [
"createChatClient",
"createChatClient",
"createFeedPublisher",
"createFeedPublisher",
- "createInboxVisitor"
+ "createInboxVisitor",
+ "history"
]
]
},
},
"chatApps": {
"chatApps": {
@@ -587,7 +588,13 @@
@@ -587,7 +588,13 @@
"openvibe-sdk/chat": {
"openvibe-sdk/chat": {
"createChatClient": "function",
"createChatClient": "function",
"createFeedPublisher": "function",
"createFeedPublisher": "function",
- "createInboxVisitor": "function"
+ "createInboxVisitor": "function",
+ "history": {
+ "object": [
+ "attach",
+ "pages"
+ ]
+ }
},
},
"openvibe-sdk/chat-apps": {
"openvibe-sdk/chat-apps": {
"APP_LIMITS": {
"APP_LIMITS": {
@@ -2,6 +2,6 @@
@@ -2,6 +2,6 @@
import cjs from '../src/chat.js';
import cjs from '../src/chat.js';
export const {
export const {
- createChatClient, createInboxVisitor, createFeedPublisher,
+ createChatClient, createInboxVisitor, createFeedPublisher, history,
} = cjs;
} = cjs;
export default cjs;
export default cjs;
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-sdk",
"name": "openvibe-sdk",
- "version": "0.139.0",
+ "version": "0.140.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-sdk",
"name": "openvibe-sdk",
- "version": "0.139.0",
+ "version": "0.140.0",
"license": "MIT",
"license": "MIT",
"bin": {
"bin": {
"openvibe-download": "bin/openvibe-download.js"
"openvibe-download": "bin/openvibe-download.js"
@@ -1,6 +1,6 @@
@@ -1,6 +1,6 @@
{
{
"name": "openvibe-sdk",
"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.",
"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",
"main": "index.js",
"types": "types/index.d.ts",
"types": "types/index.d.ts",
new file mode 100644
new file mode 100644
@@ -0,0 +1,76 @@
@@ -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 };
@@ -29,6 +29,7 @@
@@ -29,6 +29,7 @@
const { isOpenVibeError } = require('./core/errors');
const { isOpenVibeError } = require('./core/errors');
const enc = encodeURIComponent;
const enc = encodeURIComponent;
+const history = require('./chat-history');
function createChatClient(client, defaults = {}) {
function createChatClient(client, defaults = {}) {
const { baseUrl } = defaults;
const { baseUrl } = defaults;
@@ -41,12 +42,14 @@ function createChatClient(client, defaults = {}) {
@@ -41,12 +42,14 @@ function createChatClient(client, defaults = {}) {
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
const feed = (id) => `/api/chat/feeds/${enc(id)}`;
return {
return {
+ /** Shared async page iterator and scroll-preserving DOM history controller. */
+ history,
/** Vibe's model comparison API, authenticated as the person. */
/** Vibe's model comparison API, authenticated as the person. */
ask: (input, o = {}) => call({ method: 'POST', path: '/api/vibe/ask', json: input, ...once }, o),
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),
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),
prefer: (messageId, model, o = {}) => call({ method: 'POST', path: '/api/vibe/prefer', json: { message_id: messageId, model }, ...once }, o),
global: {
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),
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? } */
/** 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),
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 } = {}) {
@@ -248,4 +251,4 @@ function createFeedPublisher(client, { feed, key, baseUrl } = {}) {
};
};
}
}
-module.exports = { createChatClient, createInboxVisitor, createFeedPublisher };
+module.exports = { createChatClient, createInboxVisitor, createFeedPublisher, history };
@@ -8,7 +8,7 @@ const { paginate, offsetPager } = require('./paginate');
@@ -8,7 +8,7 @@ const { paginate, offsetPager } = require('./paginate');
const semver = require('./semver');
const semver = require('./semver');
/** The package version (test/version.test.js keeps it equal to package.json). */
/** 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 = {
module.exports = {
createClient,
createClient,
@@ -7,7 +7,7 @@
@@ -7,7 +7,7 @@
const assert = require('node:assert/strict');
const assert = require('node:assert/strict');
const { stubServer, send, run } = require('./helpers');
const { stubServer, send, run } = require('./helpers');
const { createClient } = require('../src/core');
const { createClient } = require('../src/core');
-const { createChatClient, createInboxVisitor, createFeedPublisher } = require('../src/chat');
+const { createChatClient, createInboxVisitor, createFeedPublisher, history } = require('../src/chat');
async function chatStub() {
async function chatStub() {
let busy = 0;
let busy = 0;
@@ -20,6 +20,36 @@ async function chatStub() {
@@ -20,6 +20,36 @@ async function chatStub() {
}
}
run([
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 () => {
['Vibe comparison sends models and records a pick and preference', async () => {
const srv = await chatStub();
const srv = await chatStub();
const chat = createChatClient(createClient({ baseUrls: { chat: srv.url }, token: 'person-token' }));
const chat = createChatClient(createClient({ baseUrls: { chat: srv.url }, token: 'person-token' }));
@@ -17,13 +17,34 @@ export interface RoomInsight {
@@ -17,13 +17,34 @@ export interface RoomInsight {
state: 'ready' | 'quiet' | 'off';
state: 'ready' | 'quiet' | 'off';
}
}
export type ChatMessageView = 'bubbles' | 'room';
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 {
export interface ChatClient {
+ history: ChatHistoryHelper;
/** Ask Vibe using Auto, one catalogue model, or two to three models side by side. */
/** 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 }>;
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 }>;
pick(messageId: number, model: string, opts?: Opts): Promise<{ chat: Json; model: string }>;
prefer(messageId: number, model: string, opts?: Opts): Promise<{ recorded: boolean; model: string }>;
prefer(messageId: number, model: string, opts?: Opts): Promise<{ recorded: boolean; model: string }>;
global: {
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>;
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 }>;
search(query?: { q?: string; user_id?: number; stream_id?: number; limit?: number; offset?: number }, opts?: Opts): Promise<{ messages: Json[]; total?: number }>;
};
};