π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import type { WidgetManifest, WidgetOutput, WidgetOutputType, WidgetView } from '@lobechat/types';
import { validateCronPattern } from '@lobechat/utils/cronEval';
import type {
DashboardWidgetDetail,
DashboardWidgetRunItem,
DashboardWidgetVersionItem,
} from '@/services/dashboard';
import { isUsableRunStatus } from '../utils/widgetHealth';
type PreviewRun = Pick<
DashboardWidgetRunItem,
'error' | 'finishedAt' | 'output' | 'startedAt' | 'status' | 'versionId'
>;
/**
* The card model for one dry run: the widget row with that run's result in
* place of its live snapshot. A preview never touches `latestOutput`, so the
* card would otherwise show the (possibly empty) live state instead of what
* the agent just tried.
*/
export const toPreviewWidget = (widget: DashboardWidgetDetail, run: PreviewRun) => ({
...widget,
lastRunAt: run.startedAt,
lastRunError: run.error,
lastRunStatus: run.status,
latestOutput: isUsableRunStatus(run.status) ? run.output : null,
latestOutputAt: isUsableRunStatus(run.status) ? run.finishedAt : null,
// Stale / next-run judgement belongs to the live widget, not to a one-off preview.
nextRunAt: null,
schedulePattern: null,
});
/** The most recent usable (succeeded or partial) dry run of a version, from a newest-first run list. */
export const findSucceededPreviewRun = <T extends PreviewRun & { trigger: string }>(
runs: T[],
versionId?: string,
) =>
versionId
? runs.find(
(run) =>
run.versionId === versionId && run.trigger === 'preview' && isUsableRunStatus(run.status),
)
: undefined;
export interface ExpectedRun<T> {
run: T;
/** The run is of the version under review, not an earlier one shown for reference. */
sameVersion: boolean;
}
/**
* The run whose card best predicts what a version will show, from a
* newest-first run list: that version's latest usable run, else the widget's
* latest usable run of another version with the same output type β a stat
* run says nothing about how a table will look.
*/
export const findExpectedRun = <T extends Pick<PreviewRun, 'output' | 'status' | 'versionId'>>(
runs: T[],
target: Pick<DashboardWidgetVersionItem, 'id' | 'outputType'>,
): ExpectedRun<T> | undefined => {
const usable = runs.filter((run) => isUsableRunStatus(run.status) && !!run.output);
const own = usable.find((run) => run.versionId === target.id);
if (own) return { run: own, sameVersion: true };
const earlier = usable.find((run) => run.output?.type === target.outputType);
return earlier ? { run: earlier, sameVersion: false } : undefined;
};
/** Words a sample card shows, in the reader's language. */
export interface SampleLabels {
item: (index: number) => string;
name: string;
series: string;
value: string;
}
const SAMPLE_SERIES = [12, 15, 11, 18, 16, 21, 19];
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Illustrative output for a version that has never produced a result, shaped
* like its output type (and a table's chosen columns) so the approver sees the
* kind of card it will make. The values are placeholders; the review labels
* the card as sample data.
*/
export const sampleOutputFor = (
outputType: WidgetOutputType,
view: WidgetView | null | undefined,
labels: SampleLabels,
now = Date.now(),
): WidgetOutput => {
switch (outputType) {
case 'list': {
return {
items: [1, 2, 3].map((index) => ({ title: labels.item(index), value: 4 - index })),
type: 'list',
};
}
case 'series': {
const points = SAMPLE_SERIES.map((v, index) => ({
t: new Date(now - (SAMPLE_SERIES.length - 1 - index) * DAY_MS).toISOString().slice(0, 10),
v,
}));
return { series: [{ name: labels.series, points }], type: 'series' };
}
case 'table': {
const keys = view?.columns?.length ? view.columns : ['name', 'value'];
const last = keys.length - 1;
const columns = keys.map((key, index) => ({
key,
title: key === 'name' ? labels.name : key === 'value' ? labels.value : key,
type: index === last && keys.length > 1 ? ('number' as const) : ('string' as const),
}));
const rows = [1, 2, 3].map((row) =>
Object.fromEntries(
keys.map((key, index) => [
key,
index === last && keys.length > 1 ? (4 - row) * 10 : labels.item(row),
]),
),
);
return { columns, rows, type: 'table' };
}
default: {
return { delta: 12, trend: 'up', type: 'stat', value: 128 };
}
}
};
/**
* The card model for sample output: no run times, so the card shows no
* "updated" footer and no freshness state that the sample does not have.
*/
export const toSampleWidget = <T extends object>(widget: T, output: WidgetOutput) => ({
...widget,
lastRunAt: null,
lastRunError: null,
lastRunStatus: null,
latestOutput: output,
latestOutputAt: null,
nextRunAt: null,
schedulePattern: null,
});
export type PreviewPublishState =
/** This run's version is live. */
| 'live'
/** The run succeeded and its version can be published. */
| 'publishable'
/** The run did not succeed (yet); nothing to publish. */
| 'notReady'
/** Not the current draft; publishing it would roll the widget back. */
| 'outdated';
/**
* What the preview card offers for a dry run of `run.versionId`. Only the
* current draft is publishable: any other version β a superseded draft or an
* archived one β would silently roll the widget back to code the user never
* approved as a release, so it reads as outdated history.
*/
export const getPreviewPublishState = (
widget: Pick<DashboardWidgetDetail, 'draftVersionId' | 'publishedVersionId'>,
run: Pick<PreviewRun, 'status' | 'versionId'>,
): PreviewPublishState => {
if (widget.publishedVersionId === run.versionId) return 'live';
if (widget.draftVersionId !== run.versionId) return 'outdated';
return isUsableRunStatus(run.status) ? 'publishable' : 'notReady';
};
/**
* Whether the preview may offer publishing at all. Publishing goes through
* `WidgetService.publish`, which refuses everyone but the widget's creator β
* a teammate reading a public widget would only meet a guaranteed failure, so
* the action stays hidden from them. False until the current user is known.
*/
export const canPreviewPublish = (
widget: Pick<DashboardWidgetDetail, 'userId'>,
currentUserId?: string | null,
): boolean => !!currentUserId && currentUserId === widget.userId;
/**
* Boards offered as placement targets from a widget preview. Placing writes
* through `DashboardModel.addItem`, which only the board's creator can
* perform β in a workspace the readable list includes teammates' public
* boards, and offering them only ends in a refused write. While the current
* user is unknown (profile still loading) nothing is offered.
*/
export const placeableDashboards = <T extends { userId: string }>(
dashboards: T[],
currentUserId?: string | null,
): T[] =>
currentUserId ? dashboards.filter((dashboard) => dashboard.userId === currentUserId) : [];
/**
* Whether a widget preview may offer creating a new board. Creating lands on
* the widget's own level, and inside a workspace the home level has no UI at
* all β the home dashboard routes are disabled there β so a widget that lives
* outside a project gets no creation action; the board it would create could
* not be opened. Personal mode (no active workspace) can always create.
*/
export const canCreateDashboardFromPreview = (
projectId: string | null | undefined,
workspaceActive: boolean,
): boolean => !workspaceActive || !!projectId;
/**
* The boards a widget preview loads as placement candidates: the home
* level's boards, plus β for a widget that lives in a project β that
* project's boards, project first. The widget can be placed on either level
* (the dashboard tool scopes placements to exactly this set), so hiding the
* project's boards would lose real targets.
*
* While a workspace is active, workspace-root boards (no project, no agent)
* have no UI β the home routes are disabled there β so the home level
* offers nothing; in personal mode the home route works and stays listed.
*/
export const placementBoards = <T extends { agentId?: string | null; projectId?: string | null }>(
homeBoards: T[],
projectBoards: T[],
projectId?: string | null,
workspaceActive = false,
): T[] => {
const home = workspaceActive
? homeBoards.filter((board) => board.agentId != null || board.projectId != null)
: homeBoards;
return projectId ? [...projectBoards, ...home] : home;
};
/** Versions to compare by default: the one under review against the live one (or its parent). */
export const defaultDiffPair = (
versions: Pick<DashboardWidgetVersionItem, 'id' | 'parentVersionId' | 'status'>[],
targetId?: string,
): { baseId?: string; targetId?: string } => {
const target = versions.find((v) => v.id === targetId) ?? versions[0];
if (!target) return {};
const live = versions.find((v) => v.status === 'published' && v.id !== target.id);
const base =
live ??
versions.find((v) => v.id === target.parentVersionId) ??
versions[versions.indexOf(target) + 1];
return { baseId: base?.id, targetId: target.id };
};
/**
* The schedule that will actually be on the widget after the version under
* review goes live β exactly what `WidgetService.makeLive` persists: the
* widget's own schedule wins, and only a widget without one adopts the
* manifest's suggestion (when the pattern is valid). The review must show
* this, not the raw manifest suggestion, or the approver signs off a cadence
* the publish does not retain.
*/
export const resolvePublishSchedule = (
widget: Pick<DashboardWidgetDetail, 'schedulePattern' | 'scheduleTimezone'>,
manifest?: Pick<WidgetManifest, 'schedule'> | null,
): { pattern?: string; timezone?: string | null } => {
if (widget.schedulePattern) {
return { pattern: widget.schedulePattern, timezone: widget.scheduleTimezone };
}
const suggested = manifest?.schedule;
if (
suggested?.pattern &&
validateCronPattern(suggested.pattern, suggested.timezone ?? null).valid
) {
return { pattern: suggested.pattern, timezone: suggested.timezone ?? null };
}
return {};
};