Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

18.5 KB
Raw Blame
import toast from '../components/ui/Toast';
import { request, API_BASE } from './apiCore.js';

export const createAppLaunchVideo = (id, body, options) => request(`/apps/${encodeURIComponent(id)}/launch-videos`, { method: 'POST', body: JSON.stringify(body), ...options });
export const publishAppLaunchVideo = (id, body, options) => request(`/apps/${encodeURIComponent(id)}/launch-videos/publish`, { method: 'POST', body: JSON.stringify(body), ...options });
export const getAppLaunchVideos = (id, options) => request(`/apps/${encodeURIComponent(id)}/launch-videos`, options);
// Installed motion toolkit (ffmpeg, optional agent skill packs) for launch-video options.
export const getMotionToolkit = (options) => request('/html-composition/toolkit', options);

export const installMotionSkills = (options) => request('/html-composition/toolkit/skills/install', { method: 'POST', ...options });

// Apps. The default response remains the PM2-enriched list; `view=nav` and
// `view=probe` are explicit projections for hot name-only and peer callers.
export const getApps = ({ includeQuality = false, view, ...options } = {}) => {
  const query = new URLSearchParams();
  if (includeQuality) query.set('includeQuality', 'true');
  if (view) query.set('view', view);
  const suffix = query.toString() ? `?${query}` : '';
  return request(`/apps${suffix}`, options);
};
export const getApp = (id, { includeQuality = false, ...options } = {}) => request(includeQuality ? `/apps/${id}?includeQuality=true` : `/apps/${id}`, options);
export const getAppQualityHistory = (id, days, options) => request(`/apps/${id}/quality-history?days=${days}`, { silent: true, ...options });
// Per-lane outcome of filed audit issues (#12088); the table renders its own
// unavailable state, so the wrapper is silent.
export const getAppLaneHealth = (id, options) => request(`/apps/${id}/lane-health`, { silent: true, ...options });
// Land the app's numeric quality scores as `.quality.json` through an
// immediately-merged pull request, so other PortOS installs running this app start
// with the latest scores. Opt-in per app (`publishQualitySnapshot`) and
// user-initiated from the Quality tab, which toasts every outcome itself — so
// default to silent.
// Response: { success, published, reason?, hash?, path, prUrl?, prNumber? }.
export const publishAppQualitySnapshot = (id, options = {}) =>
  request(`/apps/${id}/quality-snapshot`, { method: 'POST', silent: true, ...options });
// The Quality tab's weekly-schedule form. `get` returns the applicable checks,
// the repo shapes that verdict came from, the cron expressions already spoken
// for, and the plan the shipped defaults produce; `preview` re-plans an edited
// form without writing; `apply` persists the plan as per-app task overrides.
// All three are silent — the form renders its own errors and warnings inline.
export const getAppQualitySchedule = (id, options = {}) =>
  request(`/apps/${id}/quality-schedule`, { silent: true, ...options });
export const previewAppQualitySchedule = (id, body, options = {}) =>
  request(`/apps/${id}/quality-schedule/preview`, { method: 'POST', body: JSON.stringify(body), silent: true, ...options });
export const applyAppQualitySchedule = (id, body, options = {}) =>
  request(`/apps/${id}/quality-schedule/apply`, { method: 'POST', body: JSON.stringify(body), silent: true, ...options });
// Managed checkout topology: returns sanitized local/fork/upstream revision
// state without exposing machine-local repo paths.
export const getAppRepositorySources = (id, options = {}) =>
  request(`/apps/${id}/repository-sources`, { silent: true, ...options });
// Fast-forward the app's configured GitHub fork from canonical
// upstream. The server deliberately refuses divergence and never forces.
export const syncAppRepositoryFork = (id, options = {}) =>
  request(`/apps/${id}/repository-sources/sync-fork`, {
    method: 'POST',
    silent: true,
    ...options,
  });
// Reverse lookup (#2991): sprite records whose publishBinding.appId targets this
// app. Read-only; the caller owns a .catch fallback, so default to silent.
export const getAppSpriteBindings = (id, options) =>
  request(`/apps/${id}/sprite-bindings`, { silent: true, ...options });
// Resolves what the app's `workTracker` field ('auto' or explicit) actually
// points to: { configured, resolved, host, forge, source }. Read-only — the
// caller (EditAppDrawer) owns its own .catch fallback, so default to silent.
export const getAppWorkTracker = (id, options) =>
  request(`/apps/${id}/work-tracker`, { silent: true, ...options });
// Work items a `/do:next` run could claim, from whichever tracker the app
// resolves to: { tracker, items: [{ ref, title, url? }], reason, transient }.
// `issueAuthorFilter` previews a filter other than the app's configured one.
// Read-only; the /do:next drawer owns its own error UI, so default to silent.
export const getAppWorkItems = (id, { issueAuthorFilter } = {}, options) => {
  const qs = issueAuthorFilter ? `?issueAuthorFilter=${encodeURIComponent(issueAuthorFilter)}` : '';
  return request(`/apps/${id}/work-items${qs}`, { silent: true, ...options });
};
// The reviewers a `/do:next` claim will ACTUALLY run for this app, resolved
// server-side through the claim-work task metadata layered OVER the install-wide
// Code Review Defaults: `{ source, reviewers, usernames, optionalReviewers,
// reviewerMaxRounds, reviewerModels, reviewerEfforts, csv }`. `source` is
// 'task-override' when the claim-work override supplied any part of the list,
// else 'defaults'. Note the fallback is per FIELD — a task pinning only
// `reviewers` still takes its models and usernames from the defaults — so
// 'task-override' means "an override is in play", not "the defaults were
// ignored". Seed a claim surface from THIS, not from getCodeReviewDefaults —
// the latter can't see the override and so shows reviewers the run won't use.
// Read-only; callers own their fallback, so default to silent.
export const getAppClaimReviewers = (id, options) =>
  request(`/apps/${id}/claim-reviewers`, { silent: true, ...options });
// Every OPEN issue on the forge this app's git origin points at (GitHub via gh,
// GitLab via glab): { forge, fullName, issues: [{ number, title, body, labels,
// assignees, author, url, createdAt, updatedAt }], reason, transient }. Backs the
// app Issues tab; a manual claim reuses the selected row's title/body as
// `issueContext` so the agent does not fetch the same issue content again.
// Read-only; the tab owns its own error UI, so default to silent.
export const getAppIssues = (id, options) =>
  request(`/apps/${id}/issues`, { silent: true, ...options });
// Every OPEN PR/MR on the app's GitHub/GitLab origin, including review/check
// state and any active PortOS resolve action. The tab owns its error UI, so
// default to silent.
export const getAppPullRequests = (id, options) =>
  request(`/apps/${id}/pull-requests`, { silent: true, ...options });
// ADVISORY ONLY: score one issue or PR against the app checkout's own PRD.md /
// GOALS.md with the local entailment scorer, and get back a verdict plus the
// clause it was scored against. Nothing branches on the answer — it is rendered
// beside the row and never gates a claim, a merge, or a label. POST because a
// body does not fit a query string, and because waking the scorer has to be an
// explicit operator action in the same request. The caller owns its own error
// UI (an uninstalled scorer is an ordinary answer here), so default to silent.
export const scoreAppScopeAdherence = (id, change, options = {}) =>
  request(`/apps/${id}/scope-adherence`, {
    method: 'POST',
    body: JSON.stringify(change),
    silent: true,
    ...options,
  });
// Queue the shared review-loop follow-up for one freshly verified open PR/MR.
// The server, not the browser, owns the forge URL/branch and duplicate guard.
// `settings` is the Pull Requests tab's run-settings panel: the same
// provider/model/effort pin `createSlashdoTask` takes, plus this run's review
// settings — `reviewMode` (`delegated` spawns the reviewer roster, `self` leaves
// the review to the agent itself) and, for a delegated run the user overrode, the
// same reviewer fields (`reviewers`, `usernames`, `optionalReviewers`,
// `reviewerMaxRounds`, `reviewerModels`, `reviewerEfforts`). Left blank it
// resolves the install's active provider and Code Review Defaults.
export const resolveAppPullRequest = (id, number, settings = {}, options = {}) =>
  request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/resolve`, {
    method: 'POST',
    body: JSON.stringify(settings),
    silent: true,
    ...options,
  });
// Queue the `pr-reviewer` scheduled task narrowed to ONE open PR/MR instead of
// letting it pick from the app's whole external open set. The server owns the
// eligibility check (open, GitHub, opened by someone else) and the duplicate
// guard, so a refusal comes back as an explained error rather than a run that
// silently reviews nothing. `settings` is the provider/model/effort pin ALONE —
// the server still gates the resolved provider to the pr-reviewer posture's
// eligible set. Deliberately not the review settings the other two take: this
// queues a `pr-reviewer` run, whose reviewers come from that scheduled task's
// own stages, so a `reviewMode` sent here would be a setting nothing applies.
export const reviewAppPullRequest = (id, number, settings = {}, options = {}) =>
  request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/review`, {
    method: 'POST',
    body: JSON.stringify(settings),
    silent: true,
    ...options,
  });
// Run the bundled `/do:review` workflow against ONE open GitHub PR, review-only.
// Unlike `reviewAppPullRequest` this is offered on every open GitHub request
// whoever opened it — `pr-reviewer` covers untrusted contributors alone.
// `settings` is the same run-settings body `resolveAppPullRequest` takes, review
// mode and reviewer override included; untouched, the run resolves the install's
// Code Review Defaults when the prompt is built.
export const doReviewAppPullRequest = (id, number, settings = {}, options = {}) =>
  request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/do-review`, {
    method: 'POST',
    body: JSON.stringify(settings),
    silent: true,
    ...options,
  });
// Merge ONE open PR/MR right now with no agent and no model spend — the forge's
// own merge button, for a change the user has already read. `deleteBranch` is a
// request, not a promise: the server keeps a long-lived head (a `main → release`
// request) and answers with the `deletedBranch` it actually did.
export const mergeAppPullRequest = (id, number, { method, deleteBranch } = {}, options = {}) =>
  request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/merge`, {
    method: 'POST',
    body: JSON.stringify({ method, deleteBranch }),
    silent: true,
    ...options,
  });
// Repair a forge token's missing OAuth scope: start `gh auth refresh` for the
// app's own forge host (the server derives it — never sent). Kickoff returns
// `{ jobId }`; the device code and outcome stream over SSE (`useForgeScopeRefresh`).
export const startAppForgeRefresh = (id, scopes, options = {}) =>
  request(`/apps/${id}/forge-auth/refresh`, {
    method: 'POST',
    body: JSON.stringify({ scopes }),
    ...options,
  });
export const appForgeRefreshEventsUrl = (id, jobId) =>
  `/api/apps/${id}/forge-auth/refresh/${encodeURIComponent(jobId)}/events`;
export const cancelAppForgeRefresh = (id, jobId, options = {}) =>
  request(`/apps/${id}/forge-auth/refresh/${encodeURIComponent(jobId)}/cancel`, {
    method: 'POST',
    ...options,
  });
// Effective Layered Intelligence config (self-improvement loop) for an app —
// stored partial merged over the shipped defaults. Read-only; saved through
// updateApp (the `layeredIntelligence` key routes to the merge helper server-
// side). Caller owns its own .catch fallback, so default to silent.
export const getAppLayeredIntelligence = (id, options) =>
  request(`/apps/${id}/layered-intelligence`, { silent: true, ...options });
// Read-only LI proposal-outcome dashboard data (#2689): merge-rate stats, the
// rejection-reason tally, and a capped recent list. The panel owns its own error
// UI, so default to silent.
export const getAppLayeredIntelligenceOutcomes = (id, options) =>
  request(`/apps/${id}/layered-intelligence/outcomes`, { silent: true, ...options });
export const createApp = (data) => request('/apps', {
  method: 'POST',
  body: JSON.stringify(data)
});
// Partial update — the server shallow-merges, so a body carrying one slice (e.g.
// `{ jira }` from the JIRA tab) leaves every other field untouched. Pass
// `{ silent: true }` when the caller renders its own error UI.
export const updateApp = (id, data, options = {}) => request(`/apps/${id}`, {
  method: 'PUT',
  body: JSON.stringify(data),
  ...options
});
export const deleteApp = (id) => request(`/apps/${id}`, { method: 'DELETE' });

// App actions
export const launchNativeApp = (id, options = {}) =>
  request(`/apps/${id}/native-launch`, { method: 'POST', ...options });

export const startApp = (id, options = {}) =>
  request(`/apps/${id}/start`, { method: 'POST', ...options });
export const stopApp = (id) => request(`/apps/${id}/stop`, { method: 'POST' });
export const restartApp = (id, options = {}) =>
  request(`/apps/${id}/restart`, { method: 'POST', ...options });
export const upgradeAppTls = (id, body) => request(`/apps/${id}/upgrade-tls`, {
  method: 'POST',
  body: JSON.stringify(body),
  silent: true  // caller shows custom toasts (ALREADY_EXISTS steers to overwrite button)
});

/**
 * Handle PortOS self-restart: show a loading toast, poll for server recovery,
 * then reload. When a restart changes HTTP to HTTPS, `targetOrigin` points the
 * health probe and final navigation at the newly-secured listener.
 * Call this after restartApp() returns { selfRestart: true }.
 */
export function handleSelfRestart({ targetOrigin = null } = {}) {
  const restartOrigin = targetOrigin?.replace(/\/+$/, '') || null;
  const healthUrl = restartOrigin
    ? `${restartOrigin}${API_BASE}/system/health`
    : `${API_BASE}/system/health`;

  toast.loading('Restarting PortOS...', { id: 'self-restart', duration: Infinity });
  const poll = async () => {
    for (let i = 0; i < 30; i++) {
      await new Promise(r => setTimeout(r, 2000));
      const healthRequest = restartOrigin
        ? fetch(healthUrl, { mode: 'no-cors' })
        : fetch(healthUrl);
      const ok = await healthRequest.then(() => true).catch(() => false);
      if (ok) {
        toast.success('PortOS restarted successfully', { id: 'self-restart' });
        setTimeout(() => {
          if (restartOrigin) {
            const currentRoute = `${window.location.pathname}${window.location.search}${window.location.hash}`;
            window.location.assign(`${restartOrigin}${currentRoute}`);
            return;
          }
          window.location.reload();
        }, 1000);
        return;
      }
    }
    toast.error('PortOS restart timed out — try reloading manually', { id: 'self-restart' });
  };
  poll();
}
// Vite Dev-UI host check / remediation. Read-only status check is silent (the
// detail view owns its own inline warning UI); the fix call's caller shows
// custom success/error toasts.
export const getAppViteHostStatus = (id, host) =>
  request(`/apps/${id}/vite-host-check?host=${encodeURIComponent(host || '')}`, { silent: true });
export const fixAppViteHosts = (id, body) => request(`/apps/${id}/fix-vite-hosts`, {
  method: 'POST',
  body: JSON.stringify(body),
  silent: true
});
export const archiveApp = (id) => request(`/apps/${id}/archive`, { method: 'POST' });
export const unarchiveApp = (id) => request(`/apps/${id}/unarchive`, { method: 'POST' });
export const openAppInEditor = (id) => request(`/apps/${id}/open-editor`, { method: 'POST' });
export const openAppFolder = (id) => request(`/apps/${id}/open-folder`, { method: 'POST' });
// The server resolves the real .xcworkspace/.xcodeproj name and opens it on the
// machine Xcode runs on — so this works from a phone, and a missing project
// comes back as a real error instead of a silent `xcode://` no-op.
export const openAppInXcode = (id, options = {}) => request(`/apps/${id}/open-xcode`, { method: 'POST', ...options });
export const refreshAppConfig = (id) => request(`/apps/${id}/refresh-config`, { method: 'POST' });
// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`
// when it already renders its own error UI.
export const buildApp = (id, options = {}) => request(`/apps/${id}/build`, { method: 'POST', ...options });
export const getAppTaskTypes = (id, options = {}) => request(`/apps/${id}/task-types`, options);
export const toggleAllAppTaskTypes = (id, enabled, options = {}) => request(`/apps/${id}/task-types/all`, {
  method: 'PUT',
  body: JSON.stringify({ enabled }),
  ...options
});
// `intervalMs` / `providerId` / `model` are the per-app scheduling fields for
// handler-backed task types (layered-intelligence). Sent only when defined so
// existing callers (enabled/interval-only toggles) are unaffected.
export const updateAppTaskTypeOverride = (id, taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata } = {}, options = {}) => request(`/apps/${id}/task-types/${taskType}`, {
  method: 'PUT',
  body: JSON.stringify({ enabled, interval, intervalMs, providerId, model, taskMetadata }),
  ...options
});
export const bulkUpdateAppTaskTypeOverride = (taskType, { enabled }, options = {}) => request(`/apps/bulk-task-type/${taskType}`, {
  method: 'PUT',
  body: JSON.stringify({ enabled }),
  ...options
});
export const detectAppIcon = (id) => request(`/apps/${id}/detect-icon`, { method: 'POST' });

export const installXcodeScripts = (id, scripts) => request(`/apps/${id}/xcode-scripts/install`, {
  method: 'POST',
  body: JSON.stringify({ scripts })
});
export const getAppDocuments = (id, options) => request(`/apps/${id}/documents`, options);
// Document paths are repo-relative and may be nested (`docs/decisions/x.md`), so
// encode per segment — encodeURIComponent on the whole path would escape the
// separators the wildcard route splits on.
const documentPath = (id, filename) =>
  `/apps/${id}/documents/${String(filename).split('/').map(encodeURIComponent).join('/')}`;
export const getAppDocument = (id, filename, options) => request(documentPath(id, filename), options);
export const saveAppDocument = (id, filename, content, commitMessage, options) =>
  request(documentPath(id, filename), {
    ...options,
    method: 'PUT',
    body: JSON.stringify({ content, ...(commitMessage && { commitMessage }) })
  });
export const getAppAgents = (id, limit = 50, options = {}) => request(`/apps/${id}/agents?limit=${limit}`, options);