Build an integration with Roam Research

This commit is contained in:
James Babcock committed 2026-08-03 15:21:52 -07:00
1 parent 63f515b8a6
commit 4022f06d49
12 files changed
+1575

No files matched your search

+2
View File
@@ -10,6 +10,7 @@ import notificationsApp from "./notifications";
import calendarApp from "./calendar";
import weatherApp from "./weather";
import navigateApp from "./navigate";
import roamApp from "./roam";
import blocksApp from "./blocks";
import minesweeperApp from "./minesweeper";
import freecellApp from "./freecell";
@@ -34,6 +35,7 @@ export const ALL_APPS: readonly AppDefinition[] = [
calendarApp,
weatherApp,
navigateApp,
roamApp,
blocksApp,
minesweeperApp,
freecellApp,
+17
View File
@@ -0,0 +1,17 @@
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
const roamApp: AppDefinition = {
appId: "roam",
title: "Roam",
icon: "roam",
launch: (ctx) =>
launchWorkerAppWindow(ctx, {
createWorker: () => new Worker("./roam-app.worker"),
windowId: "roam:main",
title: "Roam",
iconLetter: "R",
icon: "roam",
}),
};
export default roamApp;
+200
View File
@@ -0,0 +1,200 @@
/**
* Minimal client for the Roam Research backend API
* (https://roamresearch.com/#/app/developer-documentation): pull a page's
* block tree, run datalog queries, and apply block writes. Configured by the
* Roam graph/token settings; all calls are plain JSON POSTs from the app
* worker via fetch.
*/
import { roamApiTokenSetting, roamGraphNameSetting } from "../../ui/dashboard-settings";
const API_BASE = "https://api.roamresearch.com";
const FETCH_TIMEOUT_MS = 12_000;
export type RoamBlock = {
uid: string;
string: string;
order: number;
/** Roam heading level 1-3, when set on the block. */
heading?: number;
children: RoamBlock[];
};
export type RoamPage = {
uid: string;
title: string;
children: RoamBlock[];
};
export function isRoamConfigured(): boolean {
return roamGraphNameSetting.get().length > 0 && roamApiTokenSetting.get().length > 0;
}
/** Daily-note page uid for a date (Roam's fixed MM-DD-YYYY convention). */
export function dailyPageUid(date: Date): string {
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${month}-${day}-${date.getFullYear()}`;
}
/** Daily-note page title for a date, e.g. "August 3rd, 2026". */
export function dailyPageTitle(date: Date): string {
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
];
const day = date.getDate();
const teens = day % 100 >= 11 && day % 100 <= 13;
const suffix = teens ? "th" : day % 10 === 1 ? "st" : day % 10 === 2 ? "nd" : day % 10 === 3 ? "rd" : "th";
return `${months[date.getMonth()]} ${day}${suffix}, ${date.getFullYear()}`;
}
/** Pull a page (or block) and its whole subtree; null when the uid doesn't exist. */
export async function fetchPageByUid(uid: string): Promise<RoamPage | null> {
const selector = "[:block/uid :node/title :block/string :block/order :block/heading {:block/children ...}]";
const response = await roamPost("pull", { eid: `[:block/uid "${uid.replace(/["\\]/g, "")}"]`, selector });
const pulled = response?.result;
if (!pulled) return null;
return {
uid: pulled[":block/uid"] ?? uid,
title: pulled[":node/title"] ?? pulled[":block/string"] ?? "",
children: pulledChildren(pulled),
};
}
/** Look up a page's uid by exact title; null when no such page exists. */
export async function findPageUidByTitle(title: string): Promise<string | null> {
const response = await roamPost("q", {
query: "[:find ?uid :in $ ?title :where [?p :node/title ?title] [?p :block/uid ?uid]]",
args: [title],
});
const rows = response?.result;
return Array.isArray(rows) && rows.length > 0 ? String(rows[0][0]) : null;
}
export async function updateBlockString(uid: string, text: string): Promise<void> {
await roamPost("write", { action: "update-block", block: { uid, string: text } });
}
export async function createBlock(parentUid: string, order: number | "last", text: string): Promise<void> {
await roamPost("write", {
action: "create-block",
location: { "parent-uid": parentUid, order },
block: { string: text },
});
}
export async function createPage(title: string, uid?: string): Promise<void> {
const page: Record<string, string> = { title };
if (uid) page.uid = uid;
await roamPost("write", { action: "create-page", page });
}
// ---------------------------------------------------------------------------
// Transport
// The API 308-redirects each request to a per-graph peer host. Whether the
// HTTP stack replays the POST across hosts varies, so on a redirect status we
// follow the Location header ourselves and remember the peer for next time.
// The token rides in x-authorization as well, because Authorization is what
// redirect-following stacks are most likely to strip.
let cachedPeerBase: string | null = null;
async function roamPost(endpoint: "q" | "pull" | "write", body: object): Promise<any> {
const graph = roamGraphNameSetting.get();
const token = roamApiTokenSetting.get();
if (!graph || !token) {
throw new Error("Set the Roam graph name and API token in Settings > Roam.");
}
const path = `/api/graph/${encodeURIComponent(graph)}/${endpoint}`;
const payload = JSON.stringify(body);
let base = cachedPeerBase ?? API_BASE;
for (let attempt = 0; attempt < 3; attempt++) {
let response: Response;
try {
response = await fetchWithTimeout(`${base}${path}`, payload, token);
} catch (error) {
if (base !== API_BASE) {
// A stale peer host is the likely cause; retry once from the top.
cachedPeerBase = null;
base = API_BASE;
continue;
}
throw new Error(`Roam API request failed: ${(error as Error)?.message ?? error}`);
}
if (response.status >= 300 && response.status < 400) {
const location = response.headers?.get?.("Location") ?? response.headers?.get?.("location");
if (!location) throw new Error(`Roam API redirected without a Location header (HTTP ${response.status}).`);
const match = /^(https:\/\/[^/]+)/.exec(location);
if (!match) throw new Error(`Roam API redirect target not understood: ${location}`);
cachedPeerBase = match[1]!;
base = cachedPeerBase;
continue;
}
if (!response.ok) {
throw new Error(await describeHttpError(response));
}
try {
return await response.json();
} catch {
return null; // Writes may return an empty body.
}
}
throw new Error("Roam API request failed: too many redirects.");
}
async function fetchWithTimeout(url: string, payload: string, token: string): Promise<Response> {
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const request = fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
Authorization: `Bearer ${token}`,
"x-authorization": `Bearer ${token}`,
},
body: payload,
});
const timeout = new Promise<never>((_resolve, reject) => {
timeoutHandle = setTimeout(() => reject(new Error("timed out")), FETCH_TIMEOUT_MS);
});
try {
return await Promise.race([request, timeout]);
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
}
async function describeHttpError(response: Response): Promise<string> {
if (response.status === 401) return "Roam API rejected the token (check Settings > Roam).";
if (response.status === 404) return "Roam graph not found (check the graph name in Settings > Roam).";
if (response.status === 429) return "Roam API rate limit hit; try again shortly.";
if (response.status === 503) return "Roam graph is not ready yet; try again shortly.";
let detail = "";
try {
const body = await response.json();
detail = body?.message ? `: ${body.message}` : "";
} catch {
// Body wasn't JSON; the status alone will do.
}
return `Roam API error (HTTP ${response.status})${detail}`;
}
function pulledChildren(pulled: any): RoamBlock[] {
const children = pulled?.[":block/children"];
if (!Array.isArray(children)) return [];
const blocks = children.map(pulledBlock);
blocks.sort((a, b) => a.order - b.order);
return blocks;
}
function pulledBlock(pulled: any): RoamBlock {
const block: RoamBlock = {
uid: String(pulled?.[":block/uid"] ?? ""),
string: String(pulled?.[":block/string"] ?? ""),
order: Number(pulled?.[":block/order"] ?? 0),
children: pulledChildren(pulled),
};
const heading = Number(pulled?.[":block/heading"] ?? 0);
if (heading >= 1 && heading <= 3) block.heading = heading;
return block;
}
+612
View File
@@ -0,0 +1,612 @@
/**
* Roam app worker. Shows a Roam Research page (today's daily note by default)
* as a selectable outline: ring scroll moves the selection, click toggles a
* todo or follows a [[page]] link, double-click walks back through visited
* pages then yields focus. Edits (check/uncheck, add todo, edit block) go
* through the Roam backend API and are also exposed as assistant tools.
*/
import "@nativescript/core/globals";
import { GrayImage } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { truncateText, wrapText } from "../../graphics/textwrap";
import * as frameTimings from "../../native/frame-timings";
import type { DashboardInputEvent } from "../../ui/layers";
import type { MenuItem } from "../../ui/menu";
import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
import {
GESTURE_CLICK,
GESTURE_DOUBLE_CLICK,
GESTURE_LONG_PRESS,
GESTURE_SCROLL,
gestureHints,
} from "../../ui/gestures";
import { DocumentView } from "../../ui/document/document-view";
import { docNodePageLink, type DocNode } from "../../ui/document/document-model";
import {
createBlock,
createPage,
dailyPageTitle,
dailyPageUid,
fetchPageByUid,
findPageUidByTitle,
isRoamConfigured,
updateBlockString,
type RoamPage,
} from "./roam-api";
import {
findBlockMatching,
findTodoParentUid,
flattenBlocks,
isTodoBlock,
pageToDocument,
pageToToolText,
plainBlockText,
setTodoMarker,
} from "./roam-doc";
declare const global: any;
declare const com: any;
const HEADER_HEIGHT = 26;
const FOOTER_HEIGHT = 18;
const DOC_MARGIN = 6;
/** Reload the shown page when it is foregrounded and older than this. */
const STALE_AFTER_MS = 60_000;
const smallFont = getDefaultSmallFont();
type RoamWindow = {
windowId: string;
surfaceId: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
focused: boolean;
menu: WindowMenu | null;
view: DocumentView;
lastSubmittedFingerprint: string;
};
type PageRef = { uid: string | null; title: string };
const ROAM_TOOLS: ToolSpec[] = [
{
name: "read_page",
description:
"Read the Roam page currently shown on the glasses (today's daily note by default), as an indented outline. Todo items are marked [ ] (open) or [x] (done).",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
availability: "open",
timeoutMs: 14_000,
},
{
name: "add_todo",
description: "Add a new TODO item to today's Roam daily page (under its Todo section when one exists).",
inputSchema: {
type: "object",
properties: { text: { type: "string", description: "The todo item's text." } },
required: ["text"],
additionalProperties: false,
},
availability: "open",
timeoutMs: 14_000,
},
{
name: "set_todo_done",
description:
"Check off (or uncheck) a todo item on the Roam page currently shown, found by matching its text. Returns the item's new state.",
inputSchema: {
type: "object",
properties: {
match: { type: "string", description: "Text of the todo to change (partial matches allowed)." },
done: { type: "boolean", description: "True to mark done (default), false to reopen." },
},
required: ["match"],
additionalProperties: false,
},
availability: "open",
timeoutMs: 14_000,
},
{
name: "edit_block",
description:
"Rewrite the text of a block on the Roam page currently shown, found by matching its current text. A todo block keeps its todo status.",
inputSchema: {
type: "object",
properties: {
match: { type: "string", description: "Current text of the block to edit (partial matches allowed)." },
new_text: { type: "string", description: "Replacement text for the block." },
},
required: ["match", "new_text"],
additionalProperties: false,
},
availability: "open",
timeoutMs: 14_000,
},
];
let window: RoamWindow | null = null;
let screenOn = true;
let currentPage: RoamPage | null = null;
let currentRef: PageRef | null = null;
/** The current page exists only locally (an empty daily note not yet in Roam). */
let pageMissing = false;
let backStack: PageRef[] = [];
let loading = false;
let errorMessage = "";
let lastFetchMs = 0;
let loadSerial = 0;
function post(message: WorkerAppReply): void {
global.postMessage(message);
}
global.onmessage = (event: { data: WorkerAppMessage }) => {
const message = event.data;
switch (message.type) {
case "open-window":
window = {
windowId: message.windowId,
surfaceId: message.surfaceId,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
focused: false,
menu: null,
view: new DocumentView(
message.viewport.width - DOC_MARGIN * 2,
message.viewport.height - HEADER_HEIGHT - FOOTER_HEIGHT,
),
lastSubmittedFingerprint: "",
};
post({ type: "set-tools", windowId: message.windowId, tools: ROAM_TOOLS });
void loadPage(todayRef(), { resetStack: true });
break;
case "close-window":
window = null;
break;
case "input":
if (!window || window.windowId !== message.windowId) {
frameTimings.finishFrame(message.frameId, "discarded: unknown roam window");
break;
}
window.focused = message.focused;
inferForeground(message.focused);
handleInput(window, message.event as DashboardInputEvent, message.frameId);
break;
case "text-input":
// Voice input / typed text becomes a new todo on the shown page.
if (message.text.trim()) {
void addTodoFromText(message.text.trim());
}
break;
case "render":
if (!window) break;
window.focused = message.focused;
inferForeground(message.focused);
render();
break;
case "foreground":
if (!window) break;
window.foreground = message.foreground;
window.focused = message.focused;
if (window.foreground) {
maybeRefreshStalePage();
render();
}
break;
case "screen":
screenOn = message.on;
break;
case "tool-call": {
const callId = message.callId;
Promise.resolve(handleRoamTool(message.name, message.args))
.then((result) => post({ type: "tool-result", callId, result }))
.catch((error) =>
post({
type: "tool-result",
callId,
result: { ok: false, error: String((error as Error)?.message ?? error) },
}),
);
break;
}
}
};
/**
* Input and render messages only target the foreground window, so a focused
* message proves foreground; backstops a "foreground" message lost while the
* freshly spawned worker was still evaluating its bundle.
*/
function inferForeground(focused: boolean): void {
if (!focused || !window || window.foreground) return;
window.foreground = true;
maybeRefreshStalePage();
}
// ---------------------------------------------------------------------------
// Page loading
function todayRef(): PageRef {
const now = new Date();
return { uid: dailyPageUid(now), title: dailyPageTitle(now) };
}
async function loadPage(ref: PageRef, options: { resetStack?: boolean; pushCurrent?: boolean } = {}): Promise<void> {
if (!isRoamConfigured()) {
errorMessage = "";
render();
return;
}
const serial = ++loadSerial;
if (options.resetStack) backStack = [];
if (options.pushCurrent && currentRef) backStack.push(currentRef);
currentRef = ref;
loading = true;
errorMessage = "";
render();
try {
let uid = ref.uid;
if (!uid) {
uid = await findPageUidByTitle(ref.title);
if (serial !== loadSerial) return;
if (!uid) throw new Error(`No page named "${ref.title}" in the graph.`);
ref.uid = uid;
}
const page = await fetchPageByUid(uid);
if (serial !== loadSerial) return;
if (page) {
currentPage = page;
pageMissing = false;
} else if (uid === dailyPageUid(new Date())) {
// Today's daily note isn't created until something is written to it.
currentPage = { uid, title: ref.title, children: [] };
pageMissing = true;
} else {
throw new Error(`Page "${ref.title}" no longer exists.`);
}
lastFetchMs = Date.now();
window?.view.setDocument(pageToDocument(currentPage));
} catch (error) {
if (serial !== loadSerial) return;
errorMessage = String((error as Error)?.message ?? error);
} finally {
if (serial === loadSerial) {
loading = false;
render();
}
}
}
async function reloadCurrentPage(): Promise<void> {
if (currentRef) await loadPage({ ...currentRef }, {});
}
function maybeRefreshStalePage(): void {
if (loading || !currentRef || !isRoamConfigured()) return;
if (Date.now() - lastFetchMs < STALE_AFTER_MS) return;
void reloadCurrentPage();
}
// ---------------------------------------------------------------------------
// Input
function windowMenu(win: RoamWindow): WindowMenu {
if (!win.menu) {
win.menu = new WindowMenu({
size: { width: win.viewportWidth, height: win.viewportHeight },
paintBase: () => paintContent(win),
isFocused: () => win.focused,
});
}
return win.menu;
}
function menuItems(win: RoamWindow): MenuItem[] {
const items: MenuItem[] = [];
const today = todayRef();
if (currentRef?.uid !== today.uid) {
items.push({
label: "Today's page",
onSelect: (ctx) => {
ctx.stack.pop();
void loadPage(today, { resetStack: true });
},
});
}
items.push({
label: "Refresh",
onSelect: (ctx) => {
ctx.stack.pop();
void reloadCurrentPage();
},
});
if (backStack.length > 0) {
items.push({
label: "Back",
onSelect: (ctx) => {
ctx.stack.pop();
goBack();
},
});
}
items.push({
label: "Roam settings",
onSelect: (ctx) => {
ctx.stack.pop();
post({ type: "open-settings", section: "Roam" });
},
});
return [...items, ...defaultWindowMenuItems(win.windowId, post)];
}
function handleInput(win: RoamWindow, event: DashboardInputEvent, frameId: number): void {
if (win.menu?.isOpen()) {
win.menu
.handleInput(event)
.catch((error) => console.error(`roam menu input failed: ${error}`))
.then(() => renderAndSubmit(win, frameId));
return;
}
if (event.type === "long-press") {
windowMenu(win).open(menuItems(win));
renderAndSubmit(win, frameId);
return;
}
if (event.type === "double-click") {
if (backStack.length > 0) {
frameTimings.finishFrame(frameId, "discarded: roam back navigation");
goBack();
} else {
frameTimings.finishFrame(frameId, "discarded: roam yielded focus");
post({ type: "yield-focus", windowId: win.windowId });
}
return;
}
if (event.type === "scroll-up" || event.type === "scroll-down") {
win.view.moveSelection(event.type === "scroll-down" ? 1 : -1);
renderAndSubmit(win, frameId);
return;
}
if (event.type === "click") {
if (errorMessage) {
frameTimings.finishFrame(frameId, "discarded: roam retry");
void reloadCurrentPage();
return;
}
const node = win.view.selectedNode();
if (node?.kind === "todo") {
frameTimings.finishFrame(frameId, "discarded: roam todo toggle renders async");
void toggleTodo(node);
return;
}
const link = node ? docNodePageLink(node) : null;
if (link) {
frameTimings.finishFrame(frameId, "discarded: roam link follow renders async");
void loadPage({ uid: null, title: link }, { pushCurrent: true });
return;
}
frameTimings.finishFrame(frameId, "discarded: roam ignored click");
return;
}
frameTimings.finishFrame(frameId, "discarded: roam ignored input");
}
function goBack(): void {
const previous = backStack.pop();
if (previous) void loadPage(previous, {});
}
// ---------------------------------------------------------------------------
// Edits
async function toggleTodo(node: DocNode): Promise<void> {
if (!currentPage) return;
const flat = flattenBlocks(currentPage);
const entry = flat.find(({ block }) => block.uid === node.id);
if (!entry) return;
const block = entry.block;
const previousText = block.string;
const nowDone = !node.checked;
block.string = setTodoMarker(previousText, nowDone);
window?.view.setDocument(pageToDocument(currentPage));
render();
try {
await updateBlockString(block.uid, block.string);
} catch (error) {
block.string = previousText;
errorMessage = `Sync failed: ${(error as Error)?.message ?? error}`;
window?.view.setDocument(pageToDocument(currentPage));
if (window) post({ type: "set-attention", windowId: window.windowId, attention: true });
render();
}
}
/** Create today's daily page if it only exists locally. */
async function ensureCurrentPageExists(): Promise<void> {
if (!currentPage || !pageMissing) return;
await createPage(currentPage.title, currentPage.uid);
pageMissing = false;
}
async function addTodoToPage(page: RoamPage, text: string): Promise<void> {
await createBlock(findTodoParentUid(page), "last", `{{[[TODO]]}} ${text}`);
}
async function addTodoFromText(text: string): Promise<void> {
try {
if (!currentPage) throw new Error("No page is loaded.");
await ensureCurrentPageExists();
await addTodoToPage(currentPage, text);
await reloadCurrentPage();
} catch (error) {
errorMessage = `Add failed: ${(error as Error)?.message ?? error}`;
render();
}
}
// ---------------------------------------------------------------------------
// Tools
async function handleRoamTool(name: string, args: any): Promise<ToolResult> {
if (!isRoamConfigured()) {
return { ok: false, error: "Roam is not configured; set the graph name and API token in Settings > Roam." };
}
switch (name) {
case "read_page": {
if (currentRef) await reloadCurrentPage();
else await loadPage(todayRef(), { resetStack: true });
if (errorMessage) return { ok: false, error: errorMessage };
if (!currentPage) return { ok: false, error: "No page is loaded." };
return { ok: true, content: pageToToolText(currentPage) };
}
case "add_todo": {
const text = String(args?.text ?? "").trim();
if (!text) return { ok: false, error: "add_todo requires text." };
const today = todayRef();
let page = currentPage && currentPage.uid === today.uid ? currentPage : await fetchPageByUid(today.uid!);
if (!page) {
await createPage(today.title, today.uid!);
page = { uid: today.uid!, title: today.title, children: [] };
} else if (page === currentPage) {
await ensureCurrentPageExists();
}
await addTodoToPage(page, text);
if (currentRef?.uid === today.uid) await reloadCurrentPage();
return { ok: true, content: `Added todo: ${text}` };
}
case "set_todo_done": {
const match = String(args?.match ?? "").trim();
if (!match) return { ok: false, error: "set_todo_done requires match text." };
if (!currentPage) return { ok: false, error: "No page is loaded." };
const done = args?.done !== false;
const block = findBlockMatching(currentPage, match, (candidate) => isTodoBlock(candidate.string));
if (!block) return { ok: false, error: `No todo matching "${match}" on ${currentPage.title}.` };
await updateBlockString(block.uid, setTodoMarker(block.string, done));
await reloadCurrentPage();
return {
ok: true,
content: `Marked "${plainBlockText(block.string).trim()}" as ${done ? "done" : "not done"}.`,
};
}
case "edit_block": {
const match = String(args?.match ?? "").trim();
const newText = String(args?.new_text ?? "").trim();
if (!match || !newText) return { ok: false, error: "edit_block requires match and new_text." };
if (!currentPage) return { ok: false, error: "No page is loaded." };
const block = findBlockMatching(currentPage, match);
if (!block) return { ok: false, error: `No block matching "${match}" on ${currentPage.title}.` };
const marker = /^\s*\{\{(?:\[\[)?DONE/.test(block.string) ? true : isTodoBlock(block.string) ? false : null;
const replacement = marker === null || isTodoBlock(newText) ? newText : setTodoMarker(newText, marker);
await updateBlockString(block.uid, replacement);
await reloadCurrentPage();
return { ok: true, content: `Rewrote block to: ${plainBlockText(replacement).trim()}` };
}
default:
return { ok: false, error: `Unknown roam tool: ${name}` };
}
}
// ---------------------------------------------------------------------------
// Painting
function paint(win: RoamWindow): GrayImage {
if (win.menu?.isOpen()) return win.menu.paint();
return paintContent(win);
}
function paintContent(win: RoamWindow): GrayImage {
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
const title = currentRef?.title ?? "Roam";
const status = loading ? "Loading..." : pageMissing ? "(new page)" : "";
const statusWidth = status ? smallFont.measureText(status) + 12 : 0;
image.drawText(
smallFont,
DOC_MARGIN + 2,
6,
truncateText(smallFont, title, win.viewportWidth - DOC_MARGIN * 2 - statusWidth - 4),
225,
);
if (status) {
image.drawText(smallFont, win.viewportWidth - DOC_MARGIN - smallFont.measureText(status), 6, status, 130);
}
image.drawLine(DOC_MARGIN, HEADER_HEIGHT - 4, win.viewportWidth - DOC_MARGIN, HEADER_HEIGHT - 4, 40);
if (!isRoamConfigured()) {
drawBodyMessage(image, win, "Set the Roam graph name and API token in Settings > Roam. Long-press for the menu, then pick Roam settings.");
} else if (errorMessage) {
drawBodyMessage(image, win, `${errorMessage}\n\n${GESTURE_CLICK} retry`);
} else if (currentPage && currentPage.children.length === 0 && !loading) {
drawBodyMessage(image, win, "Nothing here yet. Use voice input to add a todo.");
} else {
win.view.paint(image, DOC_MARGIN, HEADER_HEIGHT, win.focused);
}
const footer = gestureHints([
[GESTURE_SCROLL, "move"],
[GESTURE_CLICK, "toggle/open"],
[GESTURE_DOUBLE_CLICK, backStack.length > 0 ? "back" : "leave"],
[GESTURE_LONG_PRESS, "menu"],
]);
image.drawText(
smallFont,
Math.max(DOC_MARGIN, Math.round((win.viewportWidth - smallFont.measureText(footer)) / 2)),
win.viewportHeight - FOOTER_HEIGHT + 3,
footer,
110,
);
return image;
}
function drawBodyMessage(image: GrayImage, win: RoamWindow, message: string): void {
const lines = wrapText(smallFont, message, win.viewportWidth - DOC_MARGIN * 2 - 24);
let y = HEADER_HEIGHT + 16;
for (const line of lines) {
image.drawText(smallFont, DOC_MARGIN + 12, y, line, 190);
y += smallFont.lineHeight + 2;
}
}
function render(): void {
if (window && window.foreground && screenOn) renderAndSubmit(window, 0);
}
function renderAndSubmit(win: RoamWindow, inputFrameId: number): void {
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
try {
const paintStartedAtMs = Date.now();
const image = frameTimings.span(frameId, "paint", () =>
frameTimings.runWithFrame(frameId, () => paint(win)),
);
const paintMs = Date.now() - paintStartedAtMs;
const fingerprint = image.fingerprint();
if (fingerprint === win.lastSubmittedFingerprint) {
frameTimings.finishFrame(frameId, "discarded: roam content unchanged");
return;
}
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
if (!communicator) {
frameTimings.finishFrame(frameId, "discarded: no active communicator");
return;
}
const buffer = image.to8bppBuffer();
communicator.submitSurfaceFrame(
buffer.buffer,
win.surfaceId,
0,
0,
image.width,
image.height,
fingerprint,
paintMs,
frameId,
);
win.lastSubmittedFingerprint = fingerprint;
} catch (error) {
frameTimings.finishFrame(frameId, "discarded: roam render failed");
console.error(`roam worker render failed: ${error}`);
}
}
+213
View File
@@ -0,0 +1,213 @@
/**
* Maps Roam block trees (roam-api.ts) into the shared document model
* (ui/document): parses the subset of Roam markup the glasses can render —
* {{[[TODO]]}} / {{[[DONE]]}} markers, [[page]] / #tag / [text](url) links,
* `inline code` and ```code blocks``` — and strips emphasis markers it can't.
* Also the block-lookup helpers the voice tools use.
*/
import type { DocInline, DocNode, DocumentRoot } from "../../ui/document/document-model";
import type { RoamBlock, RoamPage } from "./roam-api";
const TODO_MARKER = /^\s*\{\{(?:\[\[)?(TODO|DONE)(?:\]\])?\}\}\s*/;
const CODE_BLOCK = /^```([^\n`]*)\n?([\s\S]*?)```\s*$/;
export function pageToDocument(page: RoamPage): DocumentRoot {
return { title: page.title, nodes: page.children.map(blockToNode) };
}
function blockToNode(block: RoamBlock): DocNode {
const children = block.children.map(blockToNode);
const text = block.string;
const codeMatch = CODE_BLOCK.exec(text.trim());
if (codeMatch) {
return { id: block.uid, kind: "code", inlines: [], codeText: codeMatch[2] ?? "", children };
}
const todoMatch = TODO_MARKER.exec(text);
if (todoMatch) {
return {
id: block.uid,
kind: "todo",
checked: todoMatch[1] === "DONE",
inlines: parseInlineMarkup(text.slice(todoMatch[0].length)),
children,
};
}
if (block.heading) {
return { id: block.uid, kind: "heading", level: block.heading, inlines: parseInlineMarkup(text), children };
}
return { id: block.uid, kind: "text", bullet: true, inlines: parseInlineMarkup(text), children };
}
/** Flip a block string's {{[[TODO]]}} / {{[[DONE]]}} marker (adding one if absent). */
export function setTodoMarker(text: string, done: boolean): string {
const marker = done ? "{{[[DONE]]}}" : "{{[[TODO]]}}";
const match = TODO_MARKER.exec(text);
if (match) return `${marker} ${text.slice(match[0].length)}`;
return `${marker} ${text}`;
}
export function isTodoBlock(text: string): boolean {
return TODO_MARKER.test(text);
}
/** The block's text with todo marker and inline markup stripped. */
export function plainBlockText(text: string): string {
const withoutMarker = text.replace(TODO_MARKER, "");
const codeMatch = CODE_BLOCK.exec(withoutMarker.trim());
if (codeMatch) return codeMatch[2] ?? "";
return parseInlineMarkup(withoutMarker)
.map((inline) => inline.text)
.join("");
}
// ---------------------------------------------------------------------------
// Inline markup
export function parseInlineMarkup(text: string): DocInline[] {
// Emphasis renders no differently on the glasses; drop the markers.
const source = text.replace(/\*\*|__|\^\^|~~/g, "");
const inlines: DocInline[] = [];
let plain = "";
const flush = (): void => {
if (plain.length > 0) inlines.push({ kind: "text", text: plain });
plain = "";
};
let index = 0;
while (index < source.length) {
if (source.startsWith("[[", index) || source.startsWith("#[[", index)) {
const open = source[index] === "#" ? index + 3 : index + 2;
const close = matchDoubleBracket(source, open);
if (close >= 0) {
const target = source.slice(open, close);
flush();
inlines.push({ kind: "link", text: target.replace(/\[\[|\]\]/g, ""), target });
index = close + 2;
continue;
}
}
if (source[index] === "#" && /[\w/]/.test(source[index + 1] ?? "")) {
const tagMatch = /^[\w/-]+/.exec(source.slice(index + 1));
if (tagMatch) {
flush();
inlines.push({ kind: "link", text: tagMatch[0], target: tagMatch[0] });
index += 1 + tagMatch[0].length;
continue;
}
}
if (source[index] === "`") {
const close = source.indexOf("`", index + 1);
if (close >= 0) {
flush();
inlines.push({ kind: "code", text: source.slice(index + 1, close) });
index = close + 1;
continue;
}
}
if (source[index] === "[" && !source.startsWith("[[", index)) {
const labelEnd = source.indexOf("](", index + 1);
const urlEnd = labelEnd >= 0 ? source.indexOf(")", labelEnd + 2) : -1;
if (labelEnd >= 0 && urlEnd >= 0) {
flush();
inlines.push({
kind: "link",
text: source.slice(index + 1, labelEnd),
target: source.slice(labelEnd + 2, urlEnd),
external: true,
});
index = urlEnd + 1;
continue;
}
}
plain += source[index];
index++;
}
flush();
return inlines;
}
/** Offset of the "]]" closing a "[[" whose contents start at `start`, honoring nesting. */
function matchDoubleBracket(source: string, start: number): number {
let depth = 1;
for (let index = start; index < source.length - 1; index++) {
if (source.startsWith("[[", index)) {
depth++;
index++;
} else if (source.startsWith("]]", index)) {
depth--;
if (depth === 0) return index;
index++;
}
}
return -1;
}
// ---------------------------------------------------------------------------
// Block lookup helpers (voice tools)
export type FlatBlock = { block: RoamBlock; depth: number };
export function flattenBlocks(page: RoamPage): FlatBlock[] {
const out: FlatBlock[] = [];
const visit = (block: RoamBlock, depth: number): void => {
out.push({ block, depth });
for (const child of block.children) visit(child, depth + 1);
};
for (const block of page.children) visit(block, 0);
return out;
}
/**
* The uid new todos should be created under: the first block that reads like
* a todo-section header ("Todo", "Todos", "TODO:"), else the page itself.
*/
export function findTodoParentUid(page: RoamPage): string {
for (const { block } of flattenBlocks(page)) {
if (/^todos?:?$/i.test(plainBlockText(block.string).trim())) return block.uid;
}
return page.uid;
}
/**
* Find the block best matching a spoken/typed query: exact plain-text match
* first, then prefix, then substring, all case-insensitive, in document order.
*/
export function findBlockMatching(
page: RoamPage,
query: string,
filter?: (block: RoamBlock) => boolean,
): RoamBlock | null {
const needle = query.trim().toLowerCase();
if (!needle) return null;
let prefix: RoamBlock | null = null;
let substring: RoamBlock | null = null;
for (const { block } of flattenBlocks(page)) {
if (filter && !filter(block)) continue;
const plain = plainBlockText(block.string).trim().toLowerCase();
if (plain === needle) return block;
if (!prefix && plain.startsWith(needle)) prefix = block;
if (!substring && plain.includes(needle)) substring = block;
}
return prefix ?? substring;
}
/** Render the page as indented text with [ ]/[x] markers, for the assistant. */
export function pageToToolText(page: RoamPage): string {
const lines: string[] = [];
for (const { block, depth } of flattenBlocks(page)) {
const indent = " ".repeat(depth);
const text = plainBlockText(block.string).trim();
if (!text) continue;
if (isTodoBlock(block.string)) {
const done = /^\s*\{\{(?:\[\[)?DONE/.test(block.string);
lines.push(`${indent}- [${done ? "x" : " "}] ${text}`);
} else {
lines.push(`${indent}- ${text}`);
}
}
return lines.length > 0 ? `${page.title}\n${lines.join("\n")}` : `${page.title}\n(page is empty)`;
}