From 3f8f84b86e27e6007d955ba493c441ff812ee510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 28 Nov 2026 13:27:31 +0100 Subject: [PATCH] refactor(missions): the creation form keeps schedules above events and reads no schedule route A programmed Mission carries date rules, Git and forge events, and events that condition a date. The form still offered what its save refuses: a date placed after events (a fallback, shown as "else"), the success of another schedule and the completion of another Mission. It also asked the recurring engine's capability route whether criteria could be added, and its source lists for those two Mission events. The form now keeps schedules above events, so the "else" connector cannot be produced: a card that becomes a schedule joins the schedules, a dragged event stays below them, and a card added after an event is an event. The two Mission events leave the list of criteria; a stored policy naming one is kept under "Stored scheduling policy" until replaced. Followed conversations show for a Mission launched once only. The service directory the sources need comes from the native Location, read once a source needs it, and no form request reaches the schedule routes any more. Recurring instructions take the same 20,000 characters as a one-time objective. Help in the ten languages loses the "else" combination, the two Mission events and the claim that followed conversations apply to scheduled Missions. Validation: UI typecheck; the Missions UI unit and contract tests; the creation-form browser tests one file at a time; npm run test:help. --- dev-docs/MISSIONS.md | 12 +- docs/help/de/missions.md | 6 +- docs/help/en/missions.md | 5 +- docs/help/es/missions.md | 6 +- docs/help/fr/missions.md | 5 +- docs/help/he/missions.md | 6 +- docs/help/ja/missions.md | 6 +- docs/help/ne/missions.md | 6 +- docs/help/ru/missions.md | 6 +- docs/help/tr/missions.md | 6 +- docs/help/zh-Hans/missions.md | 6 +- .../mission-backend-consumers.test.ts | 25 +-- .../src/components/mission-editor-schedule.ts | 53 +---- .../src/components/mission-editor-sources.ts | 38 +--- packages/ui/src/components/mission-editor.tsx | 102 +++++---- .../mission-scheduling-data.test.ts | 28 +-- .../src/components/mission-scheduling-data.ts | 10 +- .../mission-scheduling-decode.test.ts | 28 +-- .../components/mission-scheduling-decode.ts | 2 +- .../components/mission-scheduling-sources.tsx | 2 +- .../mission-scheduling-summary.test.ts | 4 +- .../components/mission-scheduling-summary.ts | 2 +- .../ui/src/components/mission-scheduling.tsx | 32 ++- .../i18n/messages/de/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/de/missions.ts | 1 - .../i18n/messages/en/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/en/missions.ts | 1 - .../i18n/messages/es/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/es/missions.ts | 1 - .../i18n/messages/fr/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/fr/missions.ts | 1 - .../i18n/messages/he/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/he/missions.ts | 1 - .../i18n/messages/ja/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/ja/missions.ts | 1 - .../i18n/messages/ne/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/ne/missions.ts | 1 - .../i18n/messages/ru/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/ru/missions.ts | 1 - .../i18n/messages/tr/mission-scheduling.ts | 9 +- .../ui/src/lib/i18n/messages/tr/missions.ts | 1 - .../messages/zh-Hans/mission-scheduling.ts | 9 +- .../src/lib/i18n/messages/zh-Hans/missions.ts | 1 - .../browser/fixtures/mission-scheduling.tsx | 13 +- .../browser/mission-editor-scheduling.test.ts | 98 +++------ .../mission-scheduling-stability.test.ts | 208 ------------------ .../tests/browser/mission-scheduling.test.ts | 58 ++--- scripts/backend-async-operations.json | 6 +- 48 files changed, 238 insertions(+), 641 deletions(-) delete mode 100644 packages/ui/tests/browser/mission-scheduling-stability.test.ts diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index 00b9855721..37a6b2616d 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -746,12 +746,10 @@ stable prefix with the shared native source reader and launch envelope; unavaila moved, excluded or over-capacity sources block with an explanation. The original first-Play intent retains this text across acknowledgement loss and exact retries. Stored execution roots outside the editor's single directory-only scope stay read-only. -`mission-editor-schedule.ts` owns its passive capability read by view -identity, client and native generation, and fences its response by that owner and -visibility; only a changed owner returns Scheduling to its first-read state. Config, plugin and reconnection events revalidate the visible -editor's capability with one read in flight and at most one trailing read. Task revisions -and transcript releases read nothing. During a successful revalidation the shown fields, -values, focus and open picker stay unchanged, with no indicator. +The form keeps schedules above events (`orderMissionCriteria`, `mission-scheduling-data.ts`): a card that becomes +a schedule joins the schedules, and a card added after an event is an event. The service directory its sources need +is the native Location's, read once an event criterion, an existing coordinator conversation or a followed +conversation needs it. Followed conversations show for a Mission launched once. Create stores a paused Mission, or a paused programmed Mission when its launch criteria repeat or name an event. **Start automatically** defaults off, outside Scheduling. When selected, only the direct positive creation acknowledgement may continue the captured user intention through guarded Play; @@ -828,7 +826,7 @@ Editor reads and the body display cache share only the pure wire-slice validator descriptor-pinned content independently of the display cache. Source choices use explicit project pages on demand, one reader per event kind listed -in the criteria (`mission-editor-sources.ts`). Schedule documents page by eight; +in the criteria (`mission-editor-sources.ts`); conversation choices use native session pages, and local branch choices use the owned directory's bounded local ref listing (`GET /api/workspaces/:id/git-branches`, at most 200 refs under `refs/heads/`, including branches without a worktree). The read uses diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 5bc5a8947c..e30cc152d7 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -90,9 +90,9 @@ Wählen Sie **Repository-Aktivität → Ereignis**, danach optionale Filter in d Forge-Prüfungen verwenden `gh`, `glab` oder `tea` auf dem OpenCode-Host, auch bei geschlossenem CodeNomad; öffentliche Repositorys erlauben anonymen Zugriff. Selbst gehostete Forges erfordern eine dort angemeldete CLI. **github.com** bietet außerdem Kontobenachrichtigungen und Dependabot-Warnungen über angemeldetes `gh` mit [Benachrichtigungszugriff](https://docs.github.com/en/rest/activity/notifications) oder [Lesezugriff auf Warnungen](https://docs.github.com/en/rest/dependabot/alerts). Benachrichtigungen behalten ihren Lesestatus; Warnungen umfassen behobene oder verworfene Einträge. Gespeicherte Benachrichtigungen mit leerem **GitHub-Repository** umfassen das Konto. Der erste Start setzt die Referenz. -Ereignisse beziehen sich auf erfolgreiche andere Missionen/Zeitpläne, lokale Commits, neue Nachrichten oder explizite Dateien des Projekts. Wählen Sie die Quelle im jeweiligen Kriterium. Die Suche ignoriert Groß- und Kleinschreibung, auch bei Buchstaben mit Akzenten. Während einer Suche setzen Sie mit **Weitere Quellen laden** fort, auch wenn die Seite bereits Treffer enthält. Die für neue Nachrichten gewählte Unterhaltung liefert auch Kontext für den Durchlauf. Ein anderer Kriteriumstyp leert die Quelle. Gespeicherter Unterhaltungskontext bleibt beim Bearbeiten erhalten. +Ereignisse beziehen sich auf lokale Commits, neue Nachrichten oder explizite Dateien des Projekts. Wählen Sie die Quelle im jeweiligen Kriterium. Die Suche ignoriert Groß- und Kleinschreibung, auch bei Buchstaben mit Akzenten. Während einer Suche setzen Sie mit **Weitere Quellen laden** fort, auch wenn die Seite bereits Treffer enthält. Die für neue Nachrichten gewählte Unterhaltung liefert auch Kontext für den Durchlauf. Ein anderer Kriteriumstyp leert die Quelle. Gespeicherter Unterhaltungskontext bleibt beim Bearbeiten erhalten. -**oder** verbindet benachbarte Zeitpläne oder Ereignisse. **wenn** macht Ereignisse nach Zeitplänen zu Bedingungen: seit dem letzten erfolgreichen Durchlauf muss eines eingetreten sein. **sonst** macht nachfolgende Zeitpläne zum Rückfall: seit ihrem vorherigen Termin beziehungsweise ihrer Aktivierung darf oben kein Durchlauf gestartet sein. Ereignisse danach bedingen diesen Rückfall. +**oder** verbindet benachbarte Zeitpläne oder Ereignisse. **wenn** macht Ereignisse nach Zeitplänen zu Bedingungen: seit dem letzten erfolgreichen Durchlauf muss eines eingetreten sein. Führende Ereignisse werden alle 15 Minuten geprüft. Der erste Start setzt die Referenz, Erfolg schreibt sie fort, Fehlschlag erhält sie. Durchläufe überlappen nicht. @@ -104,7 +104,7 @@ Sie können einen Agenten bitten, den Zeitplan mit seiner aktuellen Stamm-Unterh Nicht darstellbare gespeicherte Regeln bleiben bis zum ausdrücklichen Ersetzen erhalten; prüfen Sie gespeicherte Enden und Grenzen vor Änderungen. -Wählen Sie unter **Verfolgte Gespräche** mit **Gespräch hinzufügen** ein Gespräch aus, auch für eine sofortige Mission. Ändern Sie die Auswahl vor dem Start oder entfernen Sie sie mit ×. +Wählen Sie unter **Verfolgte Gespräche** mit **Gespräch hinzufügen** ein Gespräch aus, für eine sofortige Mission. Ändern Sie die Auswahl vor dem Start oder entfernen Sie sie mit ×. Wählen Sie **Neue Commits auf einem lokalen Branch**, um eine lokale Git-Referenz zu beobachten, oder **Neue Commits auf einem Remote-Branch** und geben Sie den Branch-Namen ein (z. B. `dev`). Die Prüfung liest das erkannte Repository direkt, ohne lokalen Fetch. Mehrere Commits zwischen Prüfungen ergeben einen Durchlauf. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index a8c9cce82f..e30bb6213d 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -94,11 +94,10 @@ Choose **Repository activity → Event**, then any optional filters in the same Forge checks use `gh`, `glab` or `tea` on the OpenCode execution host, including with CodeNomad closed; public repositories can use anonymous access. Self-hosted forges require a CLI signed in to that host. **github.com** also offers account notifications and Dependabot alerts through signed-in `gh`, with [notification access](https://docs.github.com/en/rest/activity/notifications) or [alert read access](https://docs.github.com/en/rest/dependabot/alerts). Notifications preserve read status; alerts include fixed or dismissed items. Stored notifications with an empty **GitHub repository** cover the account. First Start sets the reference. -An event can follow another schedule's success, a completed one-time Mission, commits on a local branch, new messages in a conversation, or changes to explicit files. Choose the source inside that criterion. Search ignores letter case, including accented letters. During a search, use **Load more sources** inside the picker to continue, whether or not the current page has matches. The new-message criterion's selected conversation also supplies context to the passage. Changing the criterion type clears its source. Editing keeps stored conversation context. +An event can follow commits on a local branch, new messages in a conversation, or changes to explicit files. Choose the source inside that criterion. Search ignores letter case, including accented letters. During a search, use **Load more sources** inside the picker to continue, whether or not the current page has matches. The new-message criterion's selected conversation also supplies context to the passage. Changing the criterion type clears its source. Editing keeps stored conversation context. - **or** combines adjacent schedules, or adjacent events. - **if**: events after schedules are their conditions. At each scheduled time, one of those events must have changed since the last successful passage. -- **else**: schedules after events are a fallback. At their time, they run only if the criteria above launched no passage since that schedule's previous slot, or since it was armed. Events after the fallback condition that fallback. Events at the beginning can launch a passage on each new occurrence; trigger events are checked every 15 minutes. First Start establishes the source reference. A successful passage advances it; failed work keeps it. Passages do not overlap. @@ -110,7 +109,7 @@ You can ask an agent to prepare the schedule using its current root conversation A saved policy that the editor cannot represent stays under **Stored scheduling policy** until you explicitly replace it. Review any retained end or launch limit before editing. -In **Followed conversations**, use **Add conversation** and choose a conversation, including for an immediate Mission. Before Play, change a selection or use its × button to remove it. +In **Followed conversations**, use **Add conversation** and choose a conversation, for an immediate Mission. Before Play, change a selection or use its × button to remove it. Choose **New commits on a local branch** to watch a local Git ref, or **New commits on a remote branch** and enter the branch name (for example `dev`). The remote check reads the detected repository directly, without a local fetch. Several commits between checks produce one passage. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 9f45fb96cc..2a96792ebf 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -88,9 +88,9 @@ Elige **Actividad del repositorio → Evento** y los filtros opcionales en la mi Las comprobaciones usan `gh`, `glab` o `tea` en el host OpenCode, incluso con CodeNomad cerrado; los repositorios públicos permiten acceso anónimo. Las forjas autohospedadas requieren una CLI conectada a ese host. **github.com** ofrece además notificaciones y alertas Dependabot mediante `gh` conectado, con acceso a [notificaciones](https://docs.github.com/en/rest/activity/notifications) o [lectura de alertas](https://docs.github.com/en/rest/dependabot/alerts). Las notificaciones conservan su estado de lectura; las alertas incluyen las corregidas o descartadas. Las notificaciones guardadas con **Repositorio de GitHub** vacío cubren la cuenta. El primer inicio fija la referencia. -Los eventos siguen el éxito de otra programación o Misión, commits locales, mensajes nuevos o archivos explícitos del proyecto. Elige la fuente dentro del criterio. La búsqueda ignora mayúsculas y minúsculas, también en letras acentuadas. Durante una búsqueda, usa **Cargar más fuentes** en el selector para continuar, aunque la página ya tenga coincidencias. La conversación elegida para mensajes nuevos también aporta contexto a la ejecución. Cambiar el tipo de criterio borra su fuente. La edición conserva el contexto de conversación guardado. +Los eventos siguen commits locales, mensajes nuevos o archivos explícitos del proyecto. Elige la fuente dentro del criterio. La búsqueda ignora mayúsculas y minúsculas, también en letras acentuadas. Durante una búsqueda, usa **Cargar más fuentes** en el selector para continuar, aunque la página ya tenga coincidencias. La conversación elegida para mensajes nuevos también aporta contexto a la ejecución. Cambiar el tipo de criterio borra su fuente. La edición conserva el contexto de conversación guardado. -**o** une horarios vecinos o eventos vecinos. **si** convierte eventos después de horarios en condiciones: alguno debe haber cambiado desde la última pasada exitosa. **si no** convierte horarios posteriores a eventos en respaldo: nada de arriba debe haber lanzado una pasada desde su horario anterior o su activación. Los eventos posteriores condicionan ese respaldo. +**o** une horarios vecinos o eventos vecinos. **si** convierte eventos después de horarios en condiciones: alguno debe haber cambiado desde la última pasada exitosa. Los eventos iniciales se comprueban cada 15 minutos. El primer inicio fija la referencia; el éxito la avanza y el fallo la conserva. Las pasadas no se solapan. @@ -102,7 +102,7 @@ Puedes pedir a un agente que prepare la programación con su conversación raíz Una política guardada no representable se conserva hasta sustituirla explícitamente; revisa finales y límites antes de editar. -En **Conversaciones seguidas**, usa **Añadir conversación** y elige una conversación, también para una Misión inmediata. Antes de iniciar, cambia una selección o quítala con ×. +En **Conversaciones seguidas**, usa **Añadir conversación** y elige una conversación, para una Misión inmediata. Antes de iniciar, cambia una selección o quítala con ×. Elige **Nuevos commits en una rama local** para seguir una referencia Git local o **Nuevos commits en una rama remota** e introduce el nombre de la rama (por ejemplo, `dev`). La comprobación consulta directamente el repositorio detectado, sin un fetch local. Varios commits entre comprobaciones generan un solo pase. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index 7995ee00fc..8f5ae171ff 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -94,11 +94,10 @@ Choisissez **Activité du dépôt → Événement**, puis les filtres éventuels Les contrôles de forge utilisent `gh`, `glab` ou `tea` sur l’hôte OpenCode, même avec CodeNomad fermé ; les dépôts publics peuvent être lus anonymement. Une forge auto-hébergée exige une CLI connectée à cet hôte. **github.com** propose aussi les notifications du compte et les alertes Dependabot via `gh` connecté, avec accès aux [notifications](https://docs.github.com/en/rest/activity/notifications) ou aux [alertes en lecture](https://docs.github.com/en/rest/dependabot/alerts). Les notifications conservent leur état de lecture ; les alertes incluent celles corrigées ou ignorées. Les notifications enregistrées avec un **Dépôt GitHub** vide couvrent le compte. Le premier démarrage fixe la référence. -Un événement peut suivre la réussite d’un autre programme, une Mission ponctuelle terminée, des commits sur une branche locale, de nouveaux messages ou des changements de fichiers explicites. Choisissez la source dans ce critère. La recherche ignore les majuscules et minuscules, y compris pour les lettres accentuées. Pendant une recherche, utilisez **Charger d’autres sources** dans le sélecteur pour poursuivre, même si la page contient déjà des résultats. La conversation choisie pour les nouveaux messages fournit aussi du contexte au passage. Changer le type de critère efface sa source. La modification conserve le contexte de conversation déjà enregistré. +Un événement peut suivre des commits sur une branche locale, de nouveaux messages ou des changements de fichiers explicites. Choisissez la source dans ce critère. La recherche ignore les majuscules et minuscules, y compris pour les lettres accentuées. Pendant une recherche, utilisez **Charger d’autres sources** dans le sélecteur pour poursuivre, même si la page contient déjà des résultats. La conversation choisie pour les nouveaux messages fournit aussi du contexte au passage. Changer le type de critère efface sa source. La modification conserve le contexte de conversation déjà enregistré. - **ou** combine des horaires voisins, ou des événements voisins. - **si** : les événements après des horaires sont leurs conditions. À chaque horaire, l’un d’eux doit avoir changé depuis le dernier passage réussi. -- **sinon** : les horaires après des événements sont un repli. Ils lancent seulement si les critères au-dessus n’ont lancé aucun passage depuis leur créneau précédent, ou leur activation. Les événements placés après ce repli le conditionnent. Les événements en tête peuvent lancer un passage à chaque nouvelle occurrence ; ils sont vérifiés toutes les 15 minutes. Le premier démarrage fixe la référence des sources. Un passage réussi la fait avancer ; un échec la conserve. Les passages ne se chevauchent pas. @@ -110,7 +109,7 @@ Vous pouvez demander à un agent de préparer la programmation dans sa conversat Une politique enregistrée que l’éditeur ne sait pas représenter reste sous **Politique de lancement enregistrée** jusqu’à son remplacement explicite. Vérifiez les éventuelles limites de fin ou de nombre de passages avant de modifier. -Dans **Conversations suivies**, utilisez **Ajouter une conversation** puis choisissez une conversation, y compris pour une Mission immédiate. Avant Play, changez une sélection ou utilisez son bouton × pour la retirer. +Dans **Conversations suivies**, utilisez **Ajouter une conversation** puis choisissez une conversation, pour une Mission immédiate. Avant Play, changez une sélection ou utilisez son bouton × pour la retirer. Choisissez **Nouveaux commits sur une branche locale** pour suivre une référence Git locale, ou **Nouveaux commits sur une branche distante** et saisissez le nom de la branche (par exemple `dev`). La vérification interroge directement le dépôt distant détecté, sans `git fetch` local. Plusieurs commits entre deux vérifications déclenchent un seul passage. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index 55a0868c3a..245bf62a16 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -88,9 +88,9 @@ הבדיקות משתמשות ב-`gh`, ב-`glab` או ב-`tea` במארח OpenCode, גם כש-CodeNomad סגור; מאגרים ציבוריים מאפשרים גישה אנונימית. שרת באירוח עצמי דורש CLI המחובר אליו. **github.com** מציע גם התראות חשבון ו-Dependabot דרך `gh` מחובר, עם גישה ל[התראות](https://docs.github.com/en/rest/activity/notifications) או ל[קריאת התראות אבטחה](https://docs.github.com/en/rest/dependabot/alerts). מצב הקריאה נשמר; התראות אבטחה כוללות פריטים שתוקנו או נדחו. התראות שמורות עם **מאגר GitHub** ריק כוללות את החשבון. ההתחלה הראשונה קובעת ייחוס. -אירועים עוקבים אחר הצלחת תזמון/משימה אחרים, commits מקומיים, הודעות חדשות או קבצים מפורשים בפרויקט. בחרו מקור בתוך הקריטריון. החיפוש אינו מבחין בין אותיות גדולות וקטנות, גם באותיות עם סימנים דיאקריטיים. בזמן חיפוש, בחרו **טעינת מקורות נוספים** בבורר כדי להמשיך, גם אם כבר יש התאמות בדף. השיחה שנבחרה להודעות חדשות מספקת גם הקשר להרצה. שינוי סוג הקריטריון מנקה את המקור שלו. עריכה שומרת על הקשר השיחה שכבר נשמר. +אירועים עוקבים אחר commits מקומיים, הודעות חדשות או קבצים מפורשים בפרויקט. בחרו מקור בתוך הקריטריון. החיפוש אינו מבחין בין אותיות גדולות וקטנות, גם באותיות עם סימנים דיאקריטיים. בזמן חיפוש, בחרו **טעינת מקורות נוספים** בבורר כדי להמשיך, גם אם כבר יש התאמות בדף. השיחה שנבחרה להודעות חדשות מספקת גם הקשר להרצה. שינוי סוג הקריטריון מנקה את המקור שלו. עריכה שומרת על הקשר השיחה שכבר נשמר. -**או** מחבר זמנים סמוכים או אירועים סמוכים. **אם** הופך אירועים אחרי זמנים לתנאים: אחד צריך להשתנות מאז ההרצה המוצלחת האחרונה. **אחרת** הופך זמן שאחרי אירועים לגיבוי: הוא רץ רק אם הקריטריונים שמעליו לא הפעילו הרצה מאז המועד הקודם שלו או הפעלתו. אירועים אחריו מתנים את הגיבוי. +**או** מחבר זמנים סמוכים או אירועים סמוכים. **אם** הופך אירועים אחרי זמנים לתנאים: אחד צריך להשתנות מאז ההרצה המוצלחת האחרונה. אירועי פתיחה נבדקים כל 15 דקות. ההתחלה הראשונה קובעת נקודת ייחוס; הצלחה מקדמת אותה וכישלון שומר אותה. הרצות אינן חופפות. @@ -102,7 +102,7 @@ התזמון הנבחר מציג מצב, התעוררות/בדיקה הבאה, הרצות שהחלו/הצליחו והיסטוריה. נשמרות 30 תוצאות והמונים המצטברים. הרצה מיידית שהתקבלה נספרת. כלל שמור שהטופס אינו מייצג נשאר עד החלפה מפורשת; בדקו גבולות וסיום לפני עריכה. -ב־**שיחות במעקב**, בחרו **הוספת שיחה** ואז שיחה, גם למשימה מיידית. לפני ההפעלה, שנו בחירה או הסירו אותה בכפתור ×. +ב־**שיחות במעקב**, בחרו **הוספת שיחה** ואז שיחה, למשימה מיידית. לפני ההפעלה, שנו בחירה או הסירו אותה בכפתור ×. בחרו **קומיטים חדשים בענף מקומי** למעקב אחר הפניית Git מקומית, או **קומיטים חדשים בענף מרוחק** והזינו שם ענף (למשל `dev`). הבדיקה קוראת ישירות מהמאגר שזוהה, בלי fetch מקומי. כמה קומיטים בין בדיקות מפעילים הרצה אחת. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index d3cf87afeb..189933e559 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -88,9 +88,9 @@ 確認には OpenCode ホストの `gh`、`glab`、`tea` を使い、CodeNomad を閉じていても動作します。 公開リポジトリは匿名アクセスも可能です。 セルフホストにはそのホストにログイン済みの CLI が必要です。 **github.com** ではログイン済み `gh` によるアカウント通知と Dependabot アラートも使え、[通知](https://docs.github.com/en/rest/activity/notifications)または[アラート読み取り](https://docs.github.com/en/rest/dependabot/alerts)の権限が必要です。 既読状態を維持し、修正・却下済みアラートも含めます。 **GitHub リポジトリ**が空の保存済み通知条件はアカウント全体が対象です。 -他のスケジュールや単発ミッションの成功、ローカルコミット、新しいメッセージ、明示したプロジェクトファイルをイベントにできます。 対象は各条件の中で選びます。 検索していないときは、スクロールすると続きが読み込まれます。 検索はアクセント付き文字も含めて大文字と小文字を区別しません。 検索中は、すでに一致する項目がある場合も、選択画面の**ソースをさらに読み込む**で続きを読み込みます。 新しいメッセージの対象に選んだ会話は、実行のコンテキストにも使われます。 条件の種類を変えると対象がクリアされます。 保存済みの会話コンテキストは編集時にも保持されます。 +ローカルコミット、新しいメッセージ、明示したプロジェクトファイルをイベントにできます。 対象は各条件の中で選びます。 検索していないときは、スクロールすると続きが読み込まれます。 検索はアクセント付き文字も含めて大文字と小文字を区別しません。 検索中は、すでに一致する項目がある場合も、選択画面の**ソースをさらに読み込む**で続きを読み込みます。 新しいメッセージの対象に選んだ会話は、実行のコンテキストにも使われます。 条件の種類を変えると対象がクリアされます。 保存済みの会話コンテキストは編集時にも保持されます。 -**または** は隣接する時刻またはイベントを結合します。**もし** は時刻の後のイベントを条件にし、前回の成功以降どれかの変化を必要とします。**それ以外** はイベントの後の時刻を代替とし、その前の時刻または有効化以降、上の条件が実行を開始していない場合に動きます。後続イベントはその代替の条件です。 +**または** は隣接する時刻またはイベントを結合します。**もし** は時刻の後のイベントを条件にし、前回の成功以降どれかの変化を必要とします。 先頭のトリガーは15分ごとに確認します。 初回開始で基準を決め、成功で進め、失敗なら保持します。 実行は重複しません。 @@ -102,7 +102,7 @@ 選択したスケジュールは状態、次回起動/確認、開始・成功数と履歴を示します。直近30結果を保持し、累計数は残ります。受理された今すぐ実行も数えます。表現できない保存済みルールは明示的に置換するまで保持します。編集前に終了条件や上限を確認してください。 -**フォロー中の会話**で**会話を追加**を押し、会話を選びます。即時ミッションでも使えます。開始前に選択を変更するか、× ボタンで削除できます。 +**フォロー中の会話**で**会話を追加**を押し、会話を選びます。即時ミッションで使えます。開始前に選択を変更するか、× ボタンで削除できます。 ローカルの Git 参照を監視するには **ローカルブランチの新しいコミット** を選びます。リモートを監視するには **リモートブランチの新しいコミット** を選び、`dev` などのブランチ名を入力します。ローカルで fetch せず、検出したリポジトリを直接確認します。確認の間に複数のコミットがあっても、実行は一回です。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index d5a0014449..fd9ca57fe2 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -88,9 +88,9 @@ जाँचले OpenCode होस्टमा `gh`, `glab` वा `tea` प्रयोग गर्छ, CodeNomad बन्द हुँदा पनि; सार्वजनिक रिपोजिटरी अज्ञात रूपमा पढ्न सकिन्छ। स्व-होस्टेड फोर्जमा त्यही होस्टमा लगइन भएको CLI चाहिन्छ। **github.com** ले लगइन भएको `gh` मार्फत खाताका सूचना र Dependabot चेतावनी पनि दिन्छ; [सूचना](https://docs.github.com/en/rest/activity/notifications) वा [चेतावनी पढ्ने](https://docs.github.com/en/rest/dependabot/alerts) पहुँच चाहिन्छ। पढिएको अवस्था कायम रहन्छ; सच्याइएका वा खारेज चेतावनी पनि समेटिन्छन्। **GitHub रिपोजिटरी** खाली भएका सुरक्षित सूचना मापदण्डले पूरै खाता समेट्छन्। पहिलो सुरुवातले आधार बनाउँछ। -घटनाले अर्को समयतालिका/मिसनको सफलता, स्थानीय commit, नयाँ सन्देश वा स्पष्ट परियोजना फाइल पछ्याउँछ। स्रोत त्यही मापदण्डभित्र छान्नुहोस्। खोजले उच्चारणचिह्न भएका अक्षरसहित ठूला र साना अक्षर छुट्याउँदैन। खोज गर्दा पृष्ठमा मिल्दो स्रोत भए पनि चयनकर्ताभित्र **थप स्रोत लोड गर्नुहोस्** रोजेर खोज जारी राख्नुहोस्। नयाँ सन्देशका लागि छानिएको कुराकानीले पालालाई सन्दर्भ पनि दिन्छ। मापदण्डको प्रकार बदल्दा त्यसको स्रोत खाली हुन्छ। सम्पादन गर्दा सुरक्षित कुराकानी सन्दर्भ कायम रहन्छ। +घटनाले स्थानीय commit, नयाँ सन्देश वा स्पष्ट परियोजना फाइल पछ्याउँछ। स्रोत त्यही मापदण्डभित्र छान्नुहोस्। खोजले उच्चारणचिह्न भएका अक्षरसहित ठूला र साना अक्षर छुट्याउँदैन। खोज गर्दा पृष्ठमा मिल्दो स्रोत भए पनि चयनकर्ताभित्र **थप स्रोत लोड गर्नुहोस्** रोजेर खोज जारी राख्नुहोस्। नयाँ सन्देशका लागि छानिएको कुराकानीले पालालाई सन्दर्भ पनि दिन्छ। मापदण्डको प्रकार बदल्दा त्यसको स्रोत खाली हुन्छ। सम्पादन गर्दा सुरक्षित कुराकानी सन्दर्भ कायम रहन्छ। -**वा** ले छेउका समय वा घटना जोड्छ। **यदि** ले समयपछिका घटनालाई सर्त बनाउँछ: पछिल्लो सफल पालादेखि कुनै एक बदलिएको हुनुपर्छ। **अन्यथा** ले घटनापछिको समयलाई विकल्प बनाउँछ: त्यसको अघिल्लो समय वा सक्रियतादेखि माथिका मापदण्डले पाला सुरु नगरेको हुनुपर्छ। त्यसपछिका घटना त्यही विकल्पका सर्त हुन्। +**वा** ले छेउका समय वा घटना जोड्छ। **यदि** ले समयपछिका घटनालाई सर्त बनाउँछ: पछिल्लो सफल पालादेखि कुनै एक बदलिएको हुनुपर्छ। सुरुका ट्रिगर १५ मिनेटमा जाँचिन्छन्। पहिलो सुरुवातले आधार बनाउँछ, सफलताले अघि बढाउँछ र असफलताले राख्छ। पालाहरू जुध्दैनन्। @@ -102,7 +102,7 @@ चयनित समयतालिकाले अवस्था, अर्को जगाइ/जाँच, सुरु भएका/सफल पाला र इतिहास देखाउँछ। पछिल्ला ३० परिणाम र कुल गणना रहन्छन्। स्वीकारिएको अहिले चलाउने कार्य पनि गनिन्छ। फारमले नदेखाउन सक्ने सुरक्षित नियम स्पष्ट प्रतिस्थापनसम्म रहन्छ; सम्पादनअघि अन्त्य र सीमा जाँच्नुहोस्। -**पछ्याइएका कुराकानीहरू** मा **कुराकानी थप्नुहोस्** रोजेर कुराकानी छान्नुहोस्; तत्काल मिसनमा पनि यो गर्न सकिन्छ। सुरु गर्नुअघि छनोट बदल्नुहोस् वा × बटनले हटाउनुहोस्। +**पछ्याइएका कुराकानीहरू** मा **कुराकानी थप्नुहोस्** रोजेर कुराकानी छान्नुहोस्; तत्काल मिसनमा यो गर्न सकिन्छ। सुरु गर्नुअघि छनोट बदल्नुहोस् वा × बटनले हटाउनुहोस्। स्थानीय Git सन्दर्भ हेर्न **स्थानीय शाखामा नयाँ कमिटहरू** छान्नुहोस्। टाढाको शाखा हेर्न **दूरस्थ शाखामा नयाँ कमिटहरू** छानेर `dev` जस्तो शाखाको नाम लेख्नुहोस्। जाँचले स्थानीय fetch बिना पहिचान गरिएको रिपोजिटरी सीधै पढ्छ। दुई जाँचबीचका धेरै कमिटले एउटै पास सुरु गर्छन्। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index 44b14e82c0..b801a8405e 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -88,9 +88,9 @@ Проверки используют `gh`, `glab` или `tea` на хосте OpenCode, в том числе при закрытом CodeNomad; публичные репозитории допускают анонимный доступ. Собственный сервер требует CLI с авторизацией на этом хосте. **github.com** также предлагает уведомления аккаунта и оповещения Dependabot через авторизованный `gh` с доступом к [уведомлениям](https://docs.github.com/en/rest/activity/notifications) или [чтению оповещений](https://docs.github.com/en/rest/dependabot/alerts). Статус прочтения сохраняется; исправленные и отклонённые оповещения включаются. Сохранённые уведомления с пустым **Репозиторием GitHub** охватывают аккаунт. Первый запуск задаёт отсчёт. -События отслеживают успех другого расписания/миссии, локальные коммиты, новые сообщения или явные файлы проекта. Выбирайте источник внутри критерия. Без поискового запроса продолжение загружается при прокрутке. Поиск не различает регистр, в том числе у букв с диакритикой. Во время поиска нажимайте **Загрузить другие источники** в списке для продолжения, даже если на странице уже есть совпадения. Разговор, выбранный для новых сообщений, также даёт контекст проходу. Изменение типа критерия очищает его источник. При редактировании сохранённый контекст разговоров сохраняется. +События отслеживают локальные коммиты, новые сообщения или явные файлы проекта. Выбирайте источник внутри критерия. Без поискового запроса продолжение загружается при прокрутке. Поиск не различает регистр, в том числе у букв с диакритикой. Во время поиска нажимайте **Загрузить другие источники** в списке для продолжения, даже если на странице уже есть совпадения. Разговор, выбранный для новых сообщений, также даёт контекст проходу. Изменение типа критерия очищает его источник. При редактировании сохранённый контекст разговоров сохраняется. -**или** соединяет соседние расписания или события. **если** делает события после расписаний условиями: одно должно измениться после последнего успешного прохода. **иначе** делает последующее расписание резервным: критерии выше не должны запустить проход после его предыдущего слота или включения. События после резерва задают его условия. +**или** соединяет соседние расписания или события. **если** делает события после расписаний условиями: одно должно измениться после последнего успешного прохода. Начальные события проверяются каждые 15 минут. Первый старт устанавливает точку отсчёта; успех продвигает её, неудача сохраняет. Проходы не пересекаются. @@ -102,7 +102,7 @@ Выбранное расписание показывает состояние, следующее пробуждение/проверку, число запущенных/успешных проходов и историю. Хранятся 30 результатов и общие счётчики. Допущенное «Выполнить сейчас» учитывается. Непредставимая сохранённая политика остаётся до явной замены; перед изменением проверьте завершения и пределы. -В разделе **Отслеживаемые беседы** нажмите **Добавить беседу** и выберите беседу, в том числе для немедленной миссии. Перед запуском измените выбор или уберите его кнопкой ×. +В разделе **Отслеживаемые беседы** нажмите **Добавить беседу** и выберите беседу, для немедленной миссии. Перед запуском измените выбор или уберите его кнопкой ×. Выберите **Новые коммиты в локальной ветке**, чтобы следить за локальной ссылкой Git, или **Новые коммиты в удалённой ветке** и укажите имя ветки, например `dev`. Проверка обращается прямо к обнаруженному репозиторию, без локального fetch. Несколько коммитов между проверками дают один проход. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index a5adc2f58f..891c7a33e8 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -88,9 +88,9 @@ Başlatma veya sürdürme sırasında zamanlama projenin OpenCode yapılandırma Kontroller OpenCode makinesindeki `gh`, `glab` veya `tea` kullanır, CodeNomad kapalıyken de çalışır; herkese açık depolar anonim okunabilir. Kendi sunucunuz için o sunucuya bağlı CLI gerekir. **github.com**, oturum açmış `gh` ile hesap bildirimleri ve Dependabot uyarıları da sunar; [bildirim](https://docs.github.com/en/rest/activity/notifications) veya [uyarı okuma](https://docs.github.com/en/rest/dependabot/alerts) erişimi gerekir. Okunma durumu korunur; düzeltilen veya kapatılan uyarılar da kapsanır. **GitHub deposu** boş kayıtlı bildirimler hesabı kapsar. İlk başlatma referansı belirler. -Olaylar; başka programın/Görevin başarısını, yerel commitleri, yeni mesajları veya açık proje dosyalarını izler. Kaynağı ilgili ölçütün içinde seçin. Arama, aksanlı harfler dâhil büyük ve küçük harfleri ayırt etmez. Arama sırasında sayfada eşleşme olsa bile seçicide **Daha fazla kaynak yükle** ile devam edin. Yeni mesajlar için seçilen konuşma geçişe bağlam da sağlar. Ölçüt türünü değiştirmek kaynağını temizler. Düzenleme, kayıtlı konuşma bağlamını korur. +Olaylar; yerel commitleri, yeni mesajları veya açık proje dosyalarını izler. Kaynağı ilgili ölçütün içinde seçin. Arama, aksanlı harfler dâhil büyük ve küçük harfleri ayırt etmez. Arama sırasında sayfada eşleşme olsa bile seçicide **Daha fazla kaynak yükle** ile devam edin. Yeni mesajlar için seçilen konuşma geçişe bağlam da sağlar. Ölçüt türünü değiştirmek kaynağını temizler. Düzenleme, kayıtlı konuşma bağlamını korur. -**veya**, bitişik zamanları veya olayları birleştirir. **eğer**, zamanlardan sonraki olayları koşul yapar: son başarılı geçişten beri biri değişmiş olmalıdır. **aksi halde**, olaylardan sonraki zamanı yedek yapar: önceki yuvasından veya etkinleştirilmesinden beri üstteki ölçütler geçiş başlatmamışsa çalışır. Sonraki olaylar bu yedeği koşullandırır. +**veya**, bitişik zamanları veya olayları birleştirir. **eğer**, zamanlardan sonraki olayları koşul yapar: son başarılı geçişten beri biri değişmiş olmalıdır. Baştaki tetikleyiciler 15 dakikada bir kontrol edilir. İlk Başlat referansı kurar; başarı ilerletir, başarısızlık korur. Geçişler çakışmaz. @@ -102,7 +102,7 @@ Bir ajandan zamanlamayı kendi geçerli kök konuşmasıyla hazırlamasını ist Gösterilemeyen kayıtlı kural, açıkça değiştirilene kadar korunur; düzenlemeden önce bitiş ve sınırları inceleyin. -**Takip edilen konuşmalar** altında **Konuşma ekle** ile bir konuşma seçin; anında Görev için de kullanılabilir. Başlatmadan önce seçimi değiştirin veya × düğmesiyle kaldırın. +**Takip edilen konuşmalar** altında **Konuşma ekle** ile bir konuşma seçin; anında Görev için kullanılabilir. Başlatmadan önce seçimi değiştirin veya × düğmesiyle kaldırın. Yerel Git başvurusunu izlemek için **Yerel dalda yeni commit'ler** seçeneğini kullanın. Uzak dal için **Uzak dalda yeni commit'ler** seçeneğini ve `dev` gibi bir dal adı girin. Kontrol, yerel fetch olmadan algılanan depoyu doğrudan okur. İki kontrol arasındaki birden fazla commit tek geçiş başlatır. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index 5d366dff29..df8dfa8ad5 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -88,9 +88,9 @@ 检查使用 OpenCode 主机上的 `gh`、`glab` 或 `tea`,CodeNomad 关闭后也能运行;公共仓库可以匿名读取。 自托管服务需要已登录该主机的 CLI。 **github.com** 还通过已登录的 `gh` 提供账号通知与 Dependabot 告警,需要[通知访问权](https://docs.github.com/en/rest/activity/notifications)或[告警读取权](https://docs.github.com/en/rest/dependabot/alerts)。 通知保留已读状态;告警包括已修复或忽略的项目。 已保存通知的 **GitHub 仓库**留空时覆盖整个账号。 首次启动建立基准。 -事件可跟随其他计划或一次性任务成功、本地提交、新消息或明确列出的项目文件。 请在相应条件内选择来源。 搜索不区分大小写,包括带变音符号的字母。 搜索期间,无论当前页是否已有匹配项,都需在选择器中点击**加载更多来源**继续。 为新消息选定的对话也会为运行提供上下文。 更改条件类型会清空其来源。 编辑时保留已保存的对话上下文。 +事件可跟随本地提交、新消息或明确列出的项目文件。 请在相应条件内选择来源。 搜索不区分大小写,包括带变音符号的字母。 搜索期间,无论当前页是否已有匹配项,都需在选择器中点击**加载更多来源**继续。 为新消息选定的对话也会为运行提供上下文。 更改条件类型会清空其来源。 编辑时保留已保存的对话上下文。 -**或**连接相邻时间或相邻事件。**如果**使时间后的事件成为条件:自上次成功运行后至少一个发生变化。**否则**使事件后的时间成为后备:从其上一个时段或启用以来,上方条件未启动过运行才执行。后续事件约束该后备。 +**或**连接相邻时间或相邻事件。**如果**使时间后的事件成为条件:自上次成功运行后至少一个发生变化。 开头的触发事件每 15 分钟检查一次。 首次启动建立基准,成功推进基准,失败保留基准。 运行不会重叠。 @@ -102,7 +102,7 @@ 选中的计划显示状态、下次唤醒/检查、已启动/成功次数及历史。保留最近 30 个结果,累计计数仍在。已获准的立即运行也计数。表单无法表示的保存规则保留到显式替换;编辑前检查结束条件和次数限制。 -在**关注的对话**中点击**添加对话**并选择对话,即时任务也可使用。启动前可更改选择,或点击 × 移除。 +在**关注的对话**中点击**添加对话**并选择对话,即时任务可使用。启动前可更改选择,或点击 × 移除。 选择**本地分支有新提交**可监视本地 Git 引用;选择**远程分支有新提交**后,输入分支名(例如 `dev`)。检查直接读取检测到的远程仓库,无需在本地执行 fetch。两次检查之间的多个提交只触发一次执行。 diff --git a/packages/ui/src/components/mission-backend-consumers.test.ts b/packages/ui/src/components/mission-backend-consumers.test.ts index ecf01c1dfd..9ab3acc3f1 100644 --- a/packages/ui/src/components/mission-backend-consumers.test.ts +++ b/packages/ui/src/components/mission-backend-consumers.test.ts @@ -8,7 +8,6 @@ import { isMissionPickerSource } from "./mission-scheduling-data" import { isReservedMissionScheduleSessionID } from "../../../server/src/missions/mission-schedule-carrier-identity" import { buildProjectSessionListOptions, normalizeSessionDirectory } from "../stores/session-list-options" import { backgroundReads } from "../lib/background-read-queue" -import { recurrenceStartText } from "../../../server/src/missions/lifecycle-input" import { createEffect, createMemo, createRoot, createSignal, mapArray, on, onCleanup, untrack } from "solid-js" // Run production consumer bodies/effects, with transport and view owners injected. @@ -105,9 +104,9 @@ test("editor creation dispatch is remote; stale completion preserves the current env.replace(); read.resolve({ mission: {} }); await pending }) -for (const kind of ["schedule-success", "mission-completed", "branch-commits"] as const) { +for (const kind of ["branch-commits"] as const) { test(`editor source ${kind} uses remote API and rejects late source rows`, async () => { - const read = deferred(), env = fixture({ fetchMissionSchedules: () => read.promise, fetchLocalGitBranches: () => read.promise }) + const read = deferred(), env = fixture({ fetchLocalGitBranches: () => read.promise }) let dispose!: () => void const timers = new Map void>() let timerId = 0 @@ -119,7 +118,7 @@ for (const kind of ["schedule-success", "mission-completed", "branch-commits"] a kinds: () => [kind], selected: () => [], active: () => true, captureView: () => () => true }) }) for (const [key, timer] of timers) { timers.delete(key); timer() } reader.loading(); assert.equal(env.owners.length, 1) - env.revoke(); read.resolve({ projectID: "p", schedules: [{ id: "source", kind: "schedule", configuration: { title: "source" } }], branches: ["refs/heads/dev"] }) + env.revoke(); read.resolve({ branches: ["refs/heads/dev"] }) await flush(); assert.deepEqual(reader.sources(), {}); dispose() }) } @@ -171,9 +170,9 @@ test("editor GitHub and coordinator payload reaches only its owning programmed M props: { instanceId: owner, directory: "/repo", action, onSaved: () => {} }, locked: () => false, isActive: () => true, setFieldError: () => {}, structuralLocked: () => false, compareError: () => undefined, immediateCreationFollowed: () => false, mode: () => "recurring", coordinatorSessionID, coordinatorReady: production("./mission-editor.tsx", "coordinatorReady", { coordinatorSessionID, mode: () => "recurring", - watchedIDs, schedule: { scheduling: () => ({ criteria: [{ kind: "github-issue" }] }) }, + schedule: { scheduling: () => ({ criteria: [{ kind: "github-issue" }] }) }, sourceChoices: { sources: () => ({ "coordinator-session": [{ id: "ses_same" }] }) } }), - textLocked: () => false, policy, policyReady: () => true, recurrenceStartText, calendarID: "cal", startOnCreation: () => false, removeReplaced: async () => {}, + textLocked: () => false, policy, policyReady: () => true, calendarID: "cal", startOnCreation: () => false, removeReplaced: async () => {}, objective: () => "objective", notes: () => "notes", template: () => "custom", taskMode: () => "native", uncertainRecurrence: () => undefined, missionCreationHold: () => undefined, identity: () => owner, copyMissionProfiles: (value: any) => structuredClone(value), effectiveProfiles: () => ({ coordinator: { agent: "worker", model: { providerID: "p", id: "m" } }, roles: {} }), @@ -368,17 +367,3 @@ test("lifecycle reconcile authorizes only its exact request after its own read", const pending = reconcile(read.promise); env.revoke(); read.resolve(undefined); assert.equal(await pending, false) env.replace(); assert.equal(await reconcile(Promise.resolve()), true) }) - -test("schedule editor passive readCapability reaches its distinct remote read", async () => { - const calls: string[] = [], capability: string[] = [] - const scope = scheduleScope({ - fetchMissionScheduleCapability: async () => { calls.push("capability"); return { api: { available: true }, enabled: true } }, - }) - Object.assign(scope, { capabilityRead: undefined, captureOwner: () => () => true, - owner: () => ({ signal: new AbortController().signal }), setCapabilityReading: () => {}, - setDirectory: () => {}, setCapability: (value: string) => capability.push(value), - }) - production("./mission-editor-schedule.ts", "readCapability", scope)(); await flush() - assert.deepEqual(calls, ["capability"]) - assert.deepEqual(capability, ["available"]) -}) diff --git a/packages/ui/src/components/mission-editor-schedule.ts b/packages/ui/src/components/mission-editor-schedule.ts index 864628c678..e5a736b943 100644 --- a/packages/ui/src/components/mission-editor-schedule.ts +++ b/packages/ui/src/components/mission-editor-schedule.ts @@ -1,10 +1,9 @@ -import { createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js" +import { createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js" import type { MissionPanelMap } from "../../../server/src/api-types" import type { MissionProfiles } from "../../../server/src/missions/playbook-profiles" import { backendOf } from "../lib/backend-client" import { captureBackendOperation } from "../lib/backend-operation" import { MissionMutationError } from "../lib/mission-mutation" -import { backendEvents as serverEvents } from "../lib/server-events" import { getOpenCodeInstanceGeneration } from "../stores/opencode-data" import { instances } from "../stores/instances" import type { MissionEditorAction, MissionEditorDraft } from "../stores/mission-editor-state" @@ -17,9 +16,9 @@ import { rereadMissionHoldWhileActive } from "../lib/mission-held-reread" /** What an edit loads again from its Mission. */ export type MissionEditorLoaded = { title: string; objective: string; notes?: string; template: MissionPanelMap["template"]; profiles?: MissionProfiles taskMode: "native" | "independent"; coordinatorGoal?: boolean } -/** The form's launch criteria and whether this service can program them, and the edit of a started Mission's objective and notes. */ +/** The form's launch criteria, and the edit of a started Mission's objective and notes. */ export function createMissionEditorScheduling(props: { - instanceId: string; directory?: string; action: MissionEditorAction; draft?: Readonly + instanceId: string; action: MissionEditorAction; draft?: Readonly /** Scalar view identity; with the client and native generation, it owns the shown reads. */ scope: () => string; owner: () => string; active: () => boolean; captureView: () => (() => boolean) onLoad: (loaded: MissionEditorLoaded) => void @@ -31,9 +30,6 @@ export function createMissionEditorScheduling(props: { const [previousDraft, setPreviousDraft] = createSignal(props.draft?.previousDraft) const [ready, setReady] = createSignal(true), [failed, setFailed] = createSignal(false) const [conflict, setConflict] = createSignal(false), [reading, setReading] = createSignal(false) - const [refresh, setRefresh] = createSignal(0) - const [capability, setCapability] = createSignal<"loading" | "missing" | "activatable" | "available">("loading") - const [directory, setDirectory] = createSignal() // Only a changed view, client or native generation is another owner: other // publications (task revisions, transcript releases) never reread or reset. const owner = createMemo(() => ({ key: props.owner(), client: instances().get(props.instanceId)?.client, @@ -46,28 +42,6 @@ export function createMissionEditorScheduling(props: { const origin = owner() return () => !origin.signal.aborted && !controller.signal.aborted && owner() === origin && props.active() } - // One capability read at a time, with at most one trailing read; the same - // owner keeps its last display while it revalidates. - let capabilityRead: { controller: AbortController; trailing: boolean } | undefined - const [capabilityReading, setCapabilityReading] = createSignal(false) - const readCapability = () => untrack(() => { - if (!props.active()) return - if (capabilityRead) { capabilityRead.trailing = true; return } - const controller = new AbortController(), read = capabilityRead = { controller, trailing: false } - const owned = captureOwner(controller), current = () => capabilityRead === read && owned() - setCapabilityReading(true) - void backendOf(props.instanceId).api.fetchMissionScheduleCapability(props.instanceId, props.directory, - AbortSignal.any([owner().signal, controller.signal, AbortSignal.timeout(10_000)])).then(value => { - if (!current()) return - if (value.location?.directory) setDirectory(value.location.directory) - setCapability(value.api?.available ? value.enabled ? "available" : value.activation?.available ? "activatable" : "missing" : "missing") - }).catch(() => { if (current()) setCapability("missing") }).finally(() => { - if (capabilityRead !== read) return - capabilityRead = undefined; setCapabilityReading(false) - if (read.trailing && owned()) readCapability() - }) - }) - const stopCapability = () => { capabilityRead?.controller.abort(); capabilityRead = undefined; setCapabilityReading(false) } let reconcileRead: AbortController | undefined const stopReconcile = () => { reconcileRead?.abort(); reconcileRead = undefined } let previousOwner: ReturnType | undefined @@ -76,26 +50,12 @@ export function createMissionEditorScheduling(props: { const value = owner(), active = visible() untrack(() => { const changed = Boolean(previousOwner && value !== previousOwner) - if (changed) setCapability("loading") previousOwner = value - stopCapability(); stopReconcile(); if (active) readCapability() + stopReconcile() if (active && changed && held()?.state === "uncertain") void reconcile() }) }) - createEffect(on(refresh, readCapability, { defer: true })) - // A config event does not say which layer changed: every visible editor of the - // instance revalidates its capability, as do native and backend reconnections. - const stopEvents = [ - serverEvents.on("instance.event", event => { - if (event.type === "instance.event" && event.instanceId === props.instanceId - && (event.event.type === "config.updated" || event.event.type === "plugin.updated")) readCapability() - }), - serverEvents.on("instance.eventStatus", event => { - if (event.type === "instance.eventStatus" && event.instanceId === props.instanceId && event.status === "connected") readCapability() - }), - serverEvents.forInstance(() => props.instanceId).onOpen(readCapability), - ] - onCleanup(() => { stopEvents.forEach(stop => stop()); stopCapability(); stopReconcile() }) + onCleanup(stopReconcile) const held = () => missionScheduleEditorHold(props.scope()) const comparison = () => { const { titleOverride, objective, notes, template, profiles, taskMode, watched, scheduling } = props.captureDraft() @@ -185,6 +145,5 @@ export function createMissionEditorScheduling(props: { finally { if (reconcileRead === controller) reconcileRead = undefined } } rereadMissionHoldWhileActive(() => held()?.state === "uncertain", props.active, reconcile) - return { journal, scheduling, setScheduling, previousDraft, ready, failed, conflict, reading, capability, directory, revalidating: capabilityReading, - held, saveJournalEdit, reconcile, reload, retryRead: () => setRefresh(value => value + 1) } + return { journal, scheduling, setScheduling, previousDraft, ready, failed, conflict, reading, held, saveJournalEdit, reconcile, reload } } diff --git a/packages/ui/src/components/mission-editor-sources.ts b/packages/ui/src/components/mission-editor-sources.ts index dbb17b36f5..ff80a68ae7 100644 --- a/packages/ui/src/components/mission-editor-sources.ts +++ b/packages/ui/src/components/mission-editor-sources.ts @@ -4,7 +4,7 @@ import { captureBackendOperation } from "../lib/backend-operation" import { getRootClient } from "../stores/opencode-client" import { getOpenCodeInstanceGeneration } from "../stores/opencode-data" import { buildProjectSessionListOptions, normalizeSessionDirectory } from "../stores/session-list-options" -import { isMissionPickerSource, type MissionConditionKind } from "./mission-scheduling-data" +import { isMissionPickerSource, type MissionCriterionKind } from "./mission-scheduling-data" import type { MissionSchedulingSourceLists } from "./mission-scheduling-sources" import { isReservedMissionScheduleSessionID } from "../../../server/src/missions/mission-schedule-carrier-identity" import { backgroundReads } from "../lib/background-read-queue" @@ -26,8 +26,8 @@ function conversationTitleQuery(query: string): string { } /** Bounded source pages per selected event kind. Open source pickers own continuation. */ -export function createMissionEditorSources(props: { instanceId: string; projectID?: string; target?: string - directory: () => string | undefined; kinds: () => readonly (MissionConditionKind | "coordinator-session")[]; active: () => boolean +export function createMissionEditorSources(props: { instanceId: string; projectID?: string + directory: () => string | undefined; kinds: () => readonly (MissionCriterionKind | Kind)[]; active: () => boolean selected: () => readonly { kind: Kind; id: string }[] captureView: () => (() => boolean) }) { const [sources, setSources] = createSignal({}) @@ -58,19 +58,11 @@ export function createMissionEditorSources(props: { instanceId: string; projectI setPinLoading(new Set(ids)); setPinFailed(new Set()) void Promise.allSettled(ids.map(id => backgroundReads.run(signal, async () => { if (!/^[A-Za-z0-9_.:-]{1,240}$/.test(id)) throw new Error("Invalid source") - if (id === props.target) throw new Error("Source cycle") - if (kind === "conversation-message" || kind === "coordinator-session") { - const source = await getRootClient(props.instanceId).session.get({ sessionID: id }, { signal }) - if (source.id !== id || props.projectID && source.projectID !== props.projectID - || normalizeSessionDirectory(source.location.directory) !== normalizeSessionDirectory(directory) - || isReservedMissionScheduleSessionID(id) || kind === "coordinator-session" && source.parentID) throw new Error("Foreign source") - return { id, label: source.title || id } - } - const read = await backendOf(props.instanceId).api.fetchMissionSchedule(props.instanceId, id, { directory }, signal), { document } = read - if (!document || document.id !== id - || !document.configuration.roots.some(root => normalizeSessionDirectory(root.directory) === normalizeSessionDirectory(directory)) - || document.kind !== (kind === "schedule-success" ? "schedule" : "one-time")) throw new Error("Source unavailable") - return { id, label: document.configuration.title } + const source = await getRootClient(props.instanceId).session.get({ sessionID: id }, { signal }) + if (source.id !== id || props.projectID && source.projectID !== props.projectID + || normalizeSessionDirectory(source.location.directory) !== normalizeSessionDirectory(directory) + || isReservedMissionScheduleSessionID(id) || kind === "coordinator-session" && source.parentID) throw new Error("Foreign source") + return { id, label: source.title || id } }))).then(results => { if (!current()) return const rows = results.flatMap(result => !signal.aborted && result.status === "fulfilled" ? [result.value] : []) @@ -113,16 +105,10 @@ export function createMissionEditorSources(props: { instanceId: string; projectI && normalizeSessionDirectory(row.location.directory) === normalizeSessionDirectory(directory))) .map(row => ({ id: row.id, label: row.title || row.id })), next: page.cursor?.next } } - if (kind === "branch-commits") { - const page = await backendOf(props.instanceId).api.fetchLocalGitBranches(props.instanceId, directory, signal) - if (!Array.isArray(page.branches) || page.branches.length > 200 - || page.branches.some(ref => typeof ref !== "string" || !ref.startsWith("refs/heads/") || ref.length > 1024)) throw new Error("Invalid local branch page") - return { rows: page.branches.map(ref => ({ id: ref, label: ref.slice("refs/heads/".length) })), next: undefined } - } - const page = await backendOf(props.instanceId).api.fetchMissionSchedules(props.instanceId, { directory, after, limit: 8 }, signal) - if (props.projectID && page.projectID !== props.projectID || page.schedules.length > 8) throw new Error("Foreign source page") - return { rows: page.schedules.filter(row => row.id !== props.target && row.kind === (kind === "schedule-success" ? "schedule" : "one-time")) - .map(row => ({ id: row.id, label: row.configuration.title })), next: page.next } + const page = await backendOf(props.instanceId).api.fetchLocalGitBranches(props.instanceId, directory, signal) + if (!Array.isArray(page.branches) || page.branches.length > 200 + || page.branches.some(ref => typeof ref !== "string" || !ref.startsWith("refs/heads/") || ref.length > 1024)) throw new Error("Invalid local branch page") + return { rows: page.branches.map(ref => ({ id: ref, label: ref.slice("refs/heads/".length) })), next: undefined } } const timer = setTimeout(() => { void read().then(page => { if (!current()) return diff --git a/packages/ui/src/components/mission-editor.tsx b/packages/ui/src/components/mission-editor.tsx index 3a917c4cdc..0761396740 100644 --- a/packages/ui/src/components/mission-editor.tsx +++ b/packages/ui/src/components/mission-editor.tsx @@ -23,7 +23,7 @@ import { MissionBriefPicker, MissionBriefSave } from "./mission-model-library" import { MissionTaskModeControls } from "./mission-task-mode-controls" import { MissionSubagentDepth } from "./mission-subagent-depth" import { missionPanelScroll } from "./mission-panel-scroll" -import { MISSION_LIFECYCLE_TEXT_LIMIT, recurrenceStartText } from "../../../server/src/missions/lifecycle-input" +import { MISSION_LIFECYCLE_TEXT_LIMIT } from "../../../server/src/missions/lifecycle-input" import { recurrenceInputBudget } from "../../../server/src/missions/recurrence-read-budget" import { MISSION_TITLE_MAX, deriveMissionTitle } from "../../../server/src/missions/mission-title" import { getRootClient } from "../stores/opencode-client" @@ -210,7 +210,7 @@ export function MissionEditor(props: { setFieldError({ field, message }) } const errorFor = (field: FieldError["field"]) => fieldError()?.field === field ? fieldError()!.message : undefined - const schedule = createMissionEditorScheduling({ instanceId: props.instanceId, directory: props.directory, action, draft, + const schedule = createMissionEditorScheduling({ instanceId: props.instanceId, action, draft, scope: scheduleScope, owner: identity, active: isActive, captureView: () => { const view = captureView(), operation = props.captureOperation?.() ?? (() => true) const generation = getOpenCodeInstanceGeneration(props.instanceId) @@ -222,8 +222,36 @@ export function MissionEditor(props: { setCoordinatorGoal(Boolean(config.coordinatorGoal)) setCustomProfiles(true); setCustomTaskMode(true) }, captureDraft: () => captureDraft(), onSaved: mission => props.onSaved(mission) }) - const policy = createMemo(() => { try { return missionSchedulingPolicy(schedule.scheduling(), schedule.directory()) } catch { return undefined } }) + // The service's own directory for this view, read once a source needs it: sources are listed there, and a local branch is named with it. + const sourceIdentity = createMemo(() => JSON.stringify([identity(), props.directory, getOpenCodeInstanceGeneration(props.instanceId)])) + const [sourceLocation, setSourceLocation] = createSignal<{ key: string; directory: string }>() + const [sourceLocationFailed, setSourceLocationFailed] = createSignal(false) + const [sourceLocationRevision, setSourceLocationRevision] = createSignal(0) + const sourceLocationActive = createMemo(() => kind === "create" && creationReady() && isActive() && (watched().length > 0 + || coordinatorSessionID() !== undefined || schedule.scheduling().criteria.some(row => isMissionEventKind(row.kind)))) + createEffect(on([sourceIdentity, sourceLocationRevision, sourceLocationActive], () => { + if (!sourceLocationActive()) return + const key = sourceIdentity(), viewCurrent = captureView(), controller = new AbortController() + const operation = captureBackendOperation(props.instanceId, controller.signal) + let alive = true + setSourceLocation(undefined); setSourceLocationFailed(false) + const location = createRequestLocation(props.directory) + const current = () => operation.current() && alive && viewCurrent() && sourceIdentity() === key + void getRootClient(props.instanceId).location.get({ location: toRequestLocation(location) }, { + ...requestLocationOptions(location), signal: AbortSignal.any([operation.signal, AbortSignal.timeout(10_000)]), + }).then(value => { + if (!current()) return + if (!value.directory || value.directory.length > 4096 || value.directory.includes("\0") + || props.projectID && value.project.id !== props.projectID) throw new Error("Native source Location differs") + setSourceLocation({ key, directory: value.directory }) + }).catch(() => { if (current()) setSourceLocationFailed(true) }) + onCleanup(() => { alive = false; controller.abort() }) + })) + const directory = () => sourceLocation()?.key === sourceIdentity() ? sourceLocation()!.directory : undefined + const policy = createMemo(() => { try { return missionSchedulingPolicy(schedule.scheduling(), directory()) } catch { return undefined } }) const mode = () => policy() && !requiresMissionCalendar(policy()!) ? "once" : "recurring" + // Followed conversations belong to a Mission launched once. + const watchedIDs = createMemo(() => mode() === "once" ? watched() : []) const captureStart = createMissionCreationStart({ instanceId: props.instanceId, get projectID() { return props.projectID }, get directory() { return props.viewDirectory ?? props.directory ?? props.instanceId }, active: isActive, captureView: () => { @@ -238,50 +266,24 @@ export function MissionEditor(props: { || kind === "edit" && !!original && (original.status !== "active" || original.runState === "stopped") const [policyReady, setPolicyReady] = createSignal(false) const sourceChoices = createMissionEditorSources({ instanceId: props.instanceId, projectID: props.projectID, - target: original?.id, directory: schedule.directory, + directory, kinds: () => [...schedule.scheduling().criteria.flatMap(row => isMissionEventKind(row.kind) ? [row.kind] : []), - ...(watched().length ? ["conversation-message" as const] : []), + ...(watchedIDs().length ? ["conversation-message" as const] : []), ...(coordinatorSessionID() !== undefined && mode() === "recurring" ? ["coordinator-session" as const] : [])], selected: () => [...schedule.scheduling().criteria.flatMap(row => isMissionPickerSource(row.kind) && row.source - ? [{ kind: row.kind, id: row.source }] : []), ...watched().filter(Boolean).map(id => ({ kind: "conversation-message" as const, id })), + ? [{ kind: row.kind, id: row.source }] : []), ...watchedIDs().filter(Boolean).map(id => ({ kind: "conversation-message" as const, id })), ...(coordinatorSessionID() ? [{ kind: "coordinator-session" as const, id: coordinatorSessionID()! }] : [])], active: isActive, captureView }) - const repository = createMissionEditorRepository({ instanceId: props.instanceId, directory: schedule.directory, captureView, + const repository = createMissionEditorRepository({ instanceId: props.instanceId, directory, captureView, active: () => isActive() && schedule.scheduling().criteria.some(row => isRepositoryCriterion(row.kind)) }) - const watchedIDs = watched - const needsSourceLocation = createMemo(() => watchedIDs().length > 0) const watchedValid = () => watchedIDs().length <= 32 && new Set(watchedIDs()).size === watchedIDs().length && watchedIDs().every(id => /^[A-Za-z0-9_.:-]{1,240}$/.test(id)) - const sourceIdentity = createMemo(() => JSON.stringify([identity(), props.directory, getOpenCodeInstanceGeneration(props.instanceId)])) - const [sourceLocation, setSourceLocation] = createSignal<{ key: string; directory: string }>() - const [sourceLocationFailed, setSourceLocationFailed] = createSignal(false) - const [sourceLocationRevision, setSourceLocationRevision] = createSignal(0) - const sourceLocationActive = createMemo(() => needsSourceLocation() && creationReady() && isActive()) - createEffect(on([sourceIdentity, sourceLocationRevision, sourceLocationActive], () => { - if (!sourceLocationActive()) return - const key = sourceIdentity(), viewCurrent = captureView(), controller = new AbortController() - const operation = captureBackendOperation(props.instanceId, controller.signal) - let alive = true - setSourceLocation(undefined); setSourceLocationFailed(false) - const location = createRequestLocation(props.directory) - const current = () => operation.current() && alive && viewCurrent() && sourceIdentity() === key - void getRootClient(props.instanceId).location.get({ location: toRequestLocation(location) }, { - ...requestLocationOptions(location), signal: AbortSignal.any([operation.signal, AbortSignal.timeout(10_000)]), - }).then(value => { - if (!current()) return - if (!value.directory || value.directory.length > 4096 || value.directory.includes("\0") - || props.projectID && value.project.id !== props.projectID) throw new Error("Native source Location differs") - setSourceLocation({ key, directory: value.directory }) - }).catch(() => { if (current()) setSourceLocationFailed(true) }) - onCleanup(() => { alive = false; controller.abort() }) - })) - const sourceLocationReady = () => !needsSourceLocation() || sourceLocation()?.key === sourceIdentity() + const sourceLocationReady = () => !watchedIDs().length || directory() !== undefined const coordinatorReady = () => coordinatorSessionID() === undefined || mode() === "recurring" - && !watchedIDs().includes(coordinatorSessionID()!) && !schedule.scheduling().criteria.some(row => row.kind === "conversation-message" && row.source === coordinatorSessionID()) && !!sourceChoices.sources()["coordinator-session"]?.some(row => row.id === coordinatorSessionID()) const sourceInputBudget = () => recurrenceInputBudget({ consigne: objective().trim(), watchedConversationIDs: watchedIDs(), - roots: sourceLocation()?.key === sourceIdentity() ? [{ directory: sourceLocation()!.directory }] : [] }) + roots: directory() ? [{ directory: directory()! }] : [] }) let requestId = held?.requestId ?? draft?.requestId ?? generateUUID(), lastPayload = draft?.lastPayload ?? "" // The prepared Mission this form replaces is removed once; its conversation is offered once to what replaces it. let conversation = replaces?.coordinatorSessionId, removed = false @@ -329,17 +331,13 @@ export function MissionEditor(props: { if (!structuralLocked()) { if (!watchedValid()) { fail("followed", t("missions.recurrence.watchedInvalid")); return } if (!sourceLocationReady()) { fail("followed", t("missions.recurrence.sourceLocationUnavailable")); return } - if ((mode() === "recurring" || watchedIDs().length) && !sourceInputBudget().sufficient) { + if (watchedIDs().length && !sourceInputBudget().sufficient) { fail("objective", t("missions.recurrence.sourceInputTooLong", { limit: MISSION_LIFECYCLE_TEXT_LIMIT })); return } } if (!coordinatorReady()) { fail("coordinator", t("missions.scheduling.coordinatorUnavailable")); return } if (kind === "create" && mode() === "recurring") { if (textLocked() || !structuralLocked() && (!policy() || !policyReady())) return - if (!structuralLocked()) { - try { recurrenceStartText({ consigne: objective().trim() }) } - catch { fail("objective", t("missions.recurrence.instructionsTooLong", { limit: MISSION_LIFECYCLE_TEXT_LIMIT })); return } - } if (missionCreationHold(identity())) { setAdopted(true); return } const selected = copyMissionProfiles(effectiveProfiles()) if (mode() === "recurring" && !structuralLocked() && (!selected?.coordinator?.agent || !selected.coordinator.model?.providerID || !selected.coordinator.model.id @@ -511,13 +509,13 @@ export function MissionEditor(props: { }} />