ui-calling

A system behind the screen fails

Use it whenever a screen loads from or writes to something you don't control: an orders API, a carrier, a scheduling system, a payment provider. Both the user and the agent should learn what failed, and "try again" should only appear when it can work.

Full example: the demo's outage switches (server/failures.ts), used by order_status, shift_picker and order_return.

Server

Throw SurfaceError with a code, a message for the agent, and retryable when trying again can help. The same call works in resolve (the screen can't load) and in handlers (an action failed).

resolve: async ({ order_id }, ctx) => {
  const res = await ordersApi.get(order_id).catch(() => null);
  if (!res) throw new SurfaceError("orders_api_unavailable", "Orders API responded 503 Service Unavailable", { retryable: true });
  return toData(res);
},
on: {
  reschedule_delivery: async (slot, ctx) => {
    try {
      return await carrier.book(slot);
    } catch {
      throw new SurfaceError("carrier_timeout", "Carrier API timed out after 10s while booking the new slot", { retryable: true });
    }
  },
},

List the codes each handler can throw on its event, so the screen can't miss one:

reschedule_delivery: event(slotPayload, { describe: (p) => `Asked to move delivery to ${p.date}`, reasons: ["carrier_timeout", "slot_taken"] }),

A code the event doesn't list still works, and the server logs a warning.

When only one part of the screen depends on the third party (pickup slots on step 4 of a return), don't throw in resolve: that takes the whole screen down, draft included. Catch it, return data that says the part isn't available, and tell the agent with ctx.reportError:

resolve: async ({ order_id }, ctx) => {
  const r = await loadReturn(order_id, ctx.subject);
  const slots = await carrier.slots(r.address).catch(async (err) => {
    await ctx.reportError(new SurfaceError("carrier_unavailable", "Carrier API timed out listing pickup slots", { retryable: true }), "loading pickup slots");
    return null;
  });
  return { ...r, pickupOptions: slots ?? [], pickupUnavailable: !slots };
},

The screen shows that step's own "can't load pickup times, your return is saved" with a "Try again" (reload()). The agent is woken once for that code, however often resolve runs, and not again when a later action fails with the same code.

What happens next, without more code:

Screen

SurfaceReason<typeof contract> is the union of the codes the contract declares: type your messages with it, and adding a code to the contract stops the build until the screen has a message for it.

type Reason = SurfaceReason<typeof orderStatus>;
const MESSAGES = {
  en: { errors: { carrier_timeout: "The carrier didn't answer.", slot_taken: "That slot just went." } satisfies Record<Reason, string>, /* … */ },
  es: { errors: { carrier_timeout: "El transportista no ha respondido.", slot_taken: "Esa franja se acaba de ocupar." } satisfies Record<Reason, string>, /* … */ },
};

const { status, errorCode, returnUrl } = useSurface(orderStatus);
if (status === "error" && errorCode === "upstream_error") {
  // The agent was told: send the user back to the chat instead of a dead end.
  return <Card>{t.unavailable} <a href={returnUrl}>{t.backToChat}</a></Card>;
}

try {
  await emit("reschedule_delivery", slot);
} catch (err) {
  const e = err instanceof SurfaceActionError ? err : null;
  const known = e?.reason ? (t.errors as Record<string, string | undefined>)[e.reason] : undefined; // in the user's language
  const offline = !e || e.code === "network";
  setProblem({
    message: known ?? (offline ? t.offline : t.actionFailed),
    retry: !known && (!e || e.retryable) ? () => void reschedule(slot) : undefined,
  });
}

Prompt

Events of type "error" mean something failed on the screen, usually a system behind it. Never say an action happened if it failed. Tell the customer plainly what didn't work, without technical jargon or internal codes, and offer a way forward.

Outages and refusals

An outage (the API is down, a timeout) is upstream_error (502), and can be retryable. A refusal (the slot filled up, the code was wrong) isn't an outage: throw it with { refused: true } and the screen gets 422 refused, so your monitoring only alerts on real failures. The screen handles both the same way: by reason, with "try again" only when retryable.

Watch out

In the ui-calling repo

Not in the package; for reading if you have the repo.

Source: packages/cli/recipes/third-party-failures.md