Build your first feature
A feature that is not a conversation. A page takes a text, a background job summarises it for a price per page, and the result is there on return.
Most products built on a model are not a chat. Someone hands over a file, a URL or a form, the work takes a while, and they come back for the result. This page walks through one such feature as it ships in the registry, so every block below is the installed code and not a sketch of it.
pnpm exec intelligo sync summariesThat installs the page at /summaries with its action, its job and its messages. It needs the chat item for the model seam (lib/chat-model.ts) and pricing for money formatting. Without a model key it runs on the stub, so the whole path works on a fresh install.
The feature has four parts, and yours will have the same four:
- a price the person sees before they start
- an action that queues the work and returns at once
- a job that does the work inside an execution, so it is admitted, charged and recorded
- a list the page reads back, finished or not
A price known before the work
A summary is priced by the pages of the text, not by the model’s tokens. The form and the job read the same file, so the price shown is the price charged:
export function summaryPrice(pages: number): MoneyLike {
const price = multiply(SUMMARY_PRICE_PER_PAGE, pages);
return { amount: price.amount, currency: price.currency };
}lib/summary-config.ts is yours once installed: change the page size, the limit and the price there. Work whose size is only known afterwards (minutes transcribed, images made) begins with the most it can cost as price and settles the measured amount with complete({ charge }); the billing package page has that under “A fixed price per unit of work”.
Queue the work, return at once
The action checks its input, stores the text as a document, and enqueues a job that names the person who asked. It does not call the model:
export async function startSummary(input: {
title: string;
text: string;
}): Promise<ActionResult<{ id: string }>> {
const parsed = startSummarySchema.safeParse(input);
const t = await getTranslations("summaries");
if (!parsed.success) {
const issue = parsed.error.issues[0];
const key =
issue?.path[0] !== "text"
? "actions.invalidTitle"
: issue.code === "too_big"
? "actions.textTooLong"
: "actions.emptyText";
return { success: false, error: t(key) };
}
const { title, text } = parsed.data;
try {
const { workspace, user } = await requireWorkspace();
composeIntelligo();
const sourceId = `summary-source-${crypto.randomUUID()}`;
await saveDocument(
{ workspaceId: workspace.id, userId: user.id },
{ id: sourceId, kind: "text", title, content: text }
);
const payload: SummaryPayload = {
sourceId,
title,
summaryTitle: t("summaryTitle", { title }),
};
const id = await enqueue({
kind: SUMMARY_KIND,
workspaceId: workspace.id,
userId: user.id,
payload,
maxAttempts: 2,
});
// The first attempt now, after the response, not at the next
// scheduled drain. The queue hands out the oldest due job first,
// so this drains until none is due: an older summary waiting for
// its second attempt does not take this one's place. One that
// fails waits for the drain route.
runInBackground(
drain(summaryHandlers, {
kinds: [SUMMARY_KIND],
untilEmpty: true,
deadlineMs: FIRST_ATTEMPT_CLAIM_MS,
}).catch((error: unknown) => {
log.error("Running a queued summary failed", { error });
})
);
return { success: true, data: { id } };
} catch (error) {
if (!isAuthGuardError(error)) {
log.error("Starting a summary failed", { error });
}
return { success: false, error: t("actions.genericError") };
}
}Three things to copy:
- The input is parsed. A server action is a public endpoint; its arguments are whatever was sent.
- The job carries
userId. That is what lets the page list this person’s work and nobody else’s. - The first attempt starts now.
runInBackground(drain(...))runs it after the response instead of waiting for the next scheduled drain. An attempt that fails is run again by the drain route, below.
Do the work inside an execution
The handler reports where it is, runs the model call through runWithExecution, saves the result, and returns the id of what it made:
export const summaryHandlers: Record<string, JobHandler> = {
[SUMMARY_KIND]: async (job, signal) => {
composeIntelligo();
if (!job.workspaceId || !job.userId) {
throw new Error(
"A summary job carries its workspace and the person who asked."
);
}
const { sourceId, summaryTitle } = payloadOf(job.payload);
const actor = { workspaceId: job.workspaceId, userId: job.userId };
await reportProgress(job, { stage: "reading" satisfies SummaryStage });
const documentId = summaryDocumentId(job.id);
const [source, saved] = await Promise.all([
findDocument(actor, sourceId),
findDocument(actor, documentId),
]);
const text = source?.content ?? "";
const pages = summaryPages(text);
const price = summaryPrice(pages);
// An attempt that saved the summary and then lost its job: the
// work is done, so it is not done or charged again.
if (saved) {
return source ? { documentId, pages, charged: price } : { documentId };
}
// The text was deleted before the job reached it. Another attempt
// would find the same, so the job ends and says why.
if (!source) return { refused: SOURCE_MISSING };
await reportProgress(job, { stage: "writing" satisfies SummaryStage });
try {
await runWithExecution(
{
executions,
workspaceId: actor.workspaceId,
userId: actor.userId,
capability: SUMMARY_CAPABILITY,
model: CHAT_MODEL_ID,
// Held when the run begins, charged when it completes, and
// released if the model call or the save throws: the summary
// is saved inside the run, so one that is not kept is not
// charged.
price: money(price.amount, price.currency),
},
async () => {
const stream = streamText({
model: getChatModel(CHAT_MODEL_ID),
system: SUMMARY_SYSTEM,
prompt: text,
abortSignal: signal,
});
const [answer, usage] = await Promise.all([
stream.text,
stream.totalUsage,
]);
if (!answer.trim()) throw new Error("The model wrote nothing.");
await reportProgress(job, {
stage: "saving" satisfies SummaryStage,
});
await saveDocument(actor, {
id: documentId,
kind: "text",
title: summaryTitle,
content: answer,
});
return { usage };
}
);
} catch (error) {
if (error instanceof ExecutionRefusedError) {
// The workspace's lock was busy and nothing was decided: the
// next attempt asks again.
if (error.reasonCode === "workspace_busy") throw error;
// Not enough credit, or a limit reached. Running it again
// changes nothing, so the job ends and says why.
return { refused: error.reasonCode ?? "refused" };
}
throw error;
}
// The text has served: left in place it would sit beside its
// summary on the documents page. A text that cannot be removed is
// only clutter, so the summary stands either way.
await deleteDocumentVersions(
actor,
sourceId,
new Date(job.createdAt.getTime() - SOURCE_SAVED_WITHIN_MS).toISOString()
).catch(() => undefined);
return { documentId, pages, charged: price };
},
};What each part buys you:
priceis held when the run begins and charged when it completes. The summary is saved inside the run, so if the model call or the save throws, the hold is released and nothing is charged.- A refusal is an answer, not a failure. A workspace without credit is refused at
begin. Running the job again would be refused again, so the handler returns{ refused }and the page says why. The one refusal that decided nothing,workspace_busy, is thrown again so the next attempt asks. - The result is saved under the job’s id. A handler runs once per attempt. If an attempt saved the summary and then lost its job, the next one finds the document and neither runs nor charges again.
- The stored text is removed once it has served, so it does not sit beside its summary on the documents page.
reportProgresswrites the stage onto the job, where the page reads it.- What it returns is the job’s
result: the document’s id, the page count and the charge. The summary itself lives in a document, because finished jobs are pruned.
For attempts after the first, the drain route has to know the handler. Install the route once and add the item’s handlers to its map:
pnpm exec intelligo add jobsimport type { JobHandler } from "@intelligo-dev/jobs";
import { summaryHandlers } from "@/lib/summaries";
export const handlers: Record<string, JobHandler> = {
...summaryHandlers,
};Background jobs covers scheduling the route.
Read it back
The page lists the caller’s own jobs of this kind and turns each into what it shows:
export async function listSummaries(): Promise<ActionResult<SummaryItem[]>> {
try {
const { workspace, user } = await requireWorkspace();
const jobs = await listJobs({
workspaceId: workspace.id,
userId: user.id,
kinds: [SUMMARY_KIND],
limit: LIST_LIMIT,
});
return { success: true, data: jobs.map(toItem) };
} catch (error) {
if (!isAuthGuardError(error)) {
log.error("Listing summaries failed", { error });
}
const t = await getTranslations("summaries");
return { success: false, error: t("actions.genericError") };
}
}listJobs requires the workspace and narrows to the person, so the list cannot hold another tenant’s work. The job’s lastError never reaches the page: it is the handler’s own message, written for an operator.
The client reads the list again after a summary is started and every two seconds while one is unfinished, and stops once all have ended:
export function SummariesPanel({ initial }: { initial: SummaryItem[] }) {
const t = useTranslations("summaries");
const [items, setItems] = useState(initial);
const [stale, setStale] = useState(false);
const failedReads = useRef(0);
const refresh = useCallback(async () => {
const result = await listSummaries().catch(() => null);
if (result?.success) {
failedReads.current = 0;
setStale(false);
setItems(result.data);
return true;
}
failedReads.current += 1;
if (failedReads.current >= MAX_FAILED_READS) setStale(true);
return false;
}, []);
const waiting = unfinished(items);
useEffect(() => {
if (!waiting || stale) return;
const timer = setInterval(() => {
if (document.visibilityState === "visible") void refresh();
}, POLL_MS);
return () => clearInterval(timer);
}, [waiting, stale, refresh]);
/** The job just started, shown at once and then read from the server. */
const handleStarted = useCallback(
(started: { id: string; title: string }) => {
setItems((current) =>
current.some((item) => item.id === started.id)
? current
: [
{
id: started.id,
title: started.title,
status: "pending",
refusal: null,
stage: null,
documentId: null,
pages: null,
charged: null,
createdAt: new Date().toISOString(),
},
...current,
]
);
void refresh();
},
[refresh]
);
function retry() {
failedReads.current = 0;
setStale(false);
void refresh();
}
return (
<div className="space-y-8">
<SummaryForm onStarted={handleStarted} />
{stale && (
<div
role="alert"
className="flex flex-wrap items-center justify-between gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive"
>
<span>{t("list.stale")}</span>
<Button variant="outline" size="sm" onClick={retry}>
{t("list.refresh")}
</Button>
</div>
)}
<SummaryList items={items} />
</div>
);
}Leaving the page stops the reading and nothing else. The work runs in the background, and coming back shows where it got to.
A written summary opens on a page of its own, /summaries/<job id>, which reads the document with getDocument for the caller in the active workspace. The item shows what it made itself and needs no other page for it.
What you get without writing it
Because the model call went through an execution, the run is on the usage page with its charge, in the admin console with its provider cost, counted against the workspace’s credit and against a deployment-wide spend cap if you set one. Because the job went through the queue, a failed attempt is retried and one out of attempts is on the admin console’s operations page with a retry button.
Make it yours
Rename the kind and the capability, replace the prompt and the model call in lib/summaries.ts with your own work, and keep the shape: price, action, job, list. To gate the feature to a plan, call requireFeature in the action before you enqueue; see Plans, features and quotas.