okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0215-asknotify: chat: an agent's question notifies like an approval does (#5617)e9a1215f0

main
4.7 KiB96 linesraw
1/**
2 * Telling the person that Strata needs them or has finished (#3586, #3477). Both are opt-in and off by default.
3 *
4 * - A short sound when an answer or task that took a while is finished, or when Strata is in the background (public/strata-done-sound.wav,
5 *   made for Strata from sine waves, no sample).
6 * - A desktop notification when Manual mode waits for an approval and Strata is in the background. The desktop app shows it through its own
7 *   shell (the host passes it on, so it also works while the window is hidden in the tray); a browser uses the page's notifications.
8 */
9import { api } from './client';
10import { tr } from './i18n';
11
12/** An answer that came back faster than this does not chime while the person is looking at the window. */
13export const QUICK_MS = 8000;
14const SOUND_URL = '/strata-done-sound.wav';
15const MIN_GAP_MS = 2000;
16let lastPlayed = 0;
17
18export interface DoneContext { enabled: boolean; durationMs: number; focused: boolean; now?: number }
19
20/** Whether the finished-work sound should play now: only when asked for, only for work that took a while or when the window is not in front. */
21export function shouldPlayDone({ enabled, durationMs, focused, now = Date.now() }: DoneContext): boolean {
22  if (!enabled) return false;
23  if (now - lastPlayed < MIN_GAP_MS) return false;
24  return !focused || durationMs >= QUICK_MS;
25}
26
27export const windowInFront = (): boolean => typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus();
28
29export function playDoneSound(make: (url: string) => { volume: number; play(): Promise<void> | void } = url => new Audio(url)): boolean {
30  try {
31    const audio = make(SOUND_URL);
32    audio.volume = 0.6;
33    lastPlayed = Date.now();
34    const started = audio.play();
35    if (started && typeof (started as Promise<void>).catch === 'function') (started as Promise<void>).catch(() => { /* the browser asked for a click first: no sound this time */ });
36    return true;
37  } catch {
38    return false;
39  }
40}
41
42/** Called when an answer or a task is finished. */
43export function workFinished(enabled: boolean, durationMs: number): void {
44  if (shouldPlayDone({ enabled, durationMs, focused: windowInFront() })) playDoneSound();
45}
46
47export interface Notice { title: string; body: string }
48
49/** The sentence of the approval notification, in the person's language. */
50export function approvalNotice(tool: string): Notice {
51  return { title: tr('Strata needs your answer'), body: tr('The assistant wants to use {0}. Open Strata to approve or deny.', [tool || tr('a tool')]) };
52}
53
54/** #5617: the agent asked the person a question (ask_user_question): the approval notification's own title, with no body (no new sentence). */
55export function questionNotice(): Notice {
56  return { title: tr('Strata needs your answer'), body: '' };
57}
58
59/** The question notification, under the same opt-in as the approval one ("Notify me when Strata needs an answer") and only when Strata is not in front. */
60export function questionAsked(enabled: boolean, focused = windowInFront()): Promise<boolean> {
61  if (!enabled || focused) return Promise.resolve(false);
62  return showNotice(questionNotice());
63}
64
65/** Shows a notification through the desktop shell when there is one, else through the page. Returns whether something was shown. */
66export async function showNotice(notice: Notice, deps: { post?: (body: Notice) => Promise<{ shown?: boolean }>; page?: (notice: Notice) => boolean } = {}): Promise<boolean> {
67  const post = deps.post ?? (body => api.post<{ shown?: boolean }>('/api/shell/notify', body));
68  try {
69    const result = await post(notice);
70    if (result?.shown) return true;
71  } catch { /* no shell here: the page's own notification below */ }
72  return (deps.page ?? pageNotification)(notice);
73}
74
75function pageNotification(notice: Notice): boolean {
76  try {
77    if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false;
78    new Notification(notice.title, { body: notice.body, tag: 'strata-approval' });
79    return true;
80  } catch {
81    return false;
82  }
83}
84
85/** Manual mode waits for an approval. Only a window that is not in front needs the notification. */
86export function approvalNeeded(enabled: boolean, tool: string, focused = windowInFront()): Promise<boolean> {
87  if (!enabled || focused) return Promise.resolve(false);
88  return showNotice(approvalNotice(tool));
89}
90
91/** Turning approval notifications on in a browser asks the page's permission once; the desktop shell needs none. */
92export async function askNotificationPermission(): Promise<void> {
93  try {
94    if (typeof Notification !== 'undefined' && Notification.permission === 'default') await Notification.requestPermission();
95  } catch { /* some web views have none */ }
96}