You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "xxhZs (via GitHub)" <gi...@apache.org> on 2026/10/15 13:57:21 UTC

[PR] feat(assistant): coordinate work through a durable inbox bot [maka]

xxhZs opened a new pull request, #6124:
URL: https://github.com/apache/maka/pull/6124

   ## Summary
   
   The personal assistant now coordinates user messages and background work through a persistent Inbox Bot. Only `SendUser` publishes chat messages; the Bot can delegate work, manage indexes, handle task questions and results, and sleep until more input arrives. Ordinary model text does not become a user-facing reply.
   
   - Persist and batch Inbox delivery, make `SendUser.messages` idempotent, and finish `Sleep` only after successful tool persistence and the Host's finish guards.
   - Route discovery reports, task clarification/results, and index completion/failure feedback to the Bot. Give it direct index-management tools and owner-bound task controls.
   - Deliver current task Inbox contents before every model request, including amendments and Bot answers received while the task is running. Refresh the task files without advancing acknowledgement or settlement boundaries; this no longer depends on Recall finding a correction.
   - Add compact, differentiated assistant chat bubbles, avatars (emoji or image), and assistant-managed avatar updates.
   
   Builds on #6004. The proactive exploration prompt itself is retained; discovery output is handed to the Bot for user communication.
   
   ## Verification
   
   - Type checks passed for `@maka/runtime`, `@maka/runtime-host`, `@maka/ui`, and `@maka/desktop`.
   - Runtime Host build and desktop main build passed; `git diff --check` passed.
   - Assistant suites passed: memory network **76**, initiative **23**, proactive matters **78**.
   - Selected runtime, Host/Bot, and UI regression suites: **387 tests**. One Host integration fixture still used the retired `SendUser.text` shape; changed it to `messages`, then reran its entire **54-test** composition suite successfully. The other **333 tests** had passed in the initial run.
   - Desktop session-local suite: **79 passed**.
   - Real `gpt-6.1-sol` / medium scenario tests used synthetic source records and simulated business time, with all user requests manually entered through the assistant. The scenario harness and data remain outside this repository. The main scenario included 24 historical sessions, 27 external records, two grouped indexes, three delegated tasks, a discovery heartbeat, scope corrections, clarification, selective pauses, next-day task execution, and scheduled incremental indexing.
   - A separate real-model delivery check captured two amendments and one Bot answer in subsequent model requests of the same task activation (approximately 4.57s, 3.25s, and 3.68s after their forwarding calls). These observations are not latency guarantees.
   
   User-visible examples from the synthetic scenario:
   
   | Input or source change | Observed result |
   | --- | --- |
   | Pause reimbursement, keep the handoff running, create two indexes, and answer a simple time conversion | Paused only reimbursement, created one grouped index worker, and answered the conversion directly |
   | User clarifies that their sister accompanies their mother | Passed the correction to the existing exploration task; did not continue reporting a two-place scheduling conflict |
   | School entry deadline changes; a previously recommended exhibition is cancelled | Discovery read updated originals despite stale indexes; the Bot communicated both changes |
   | Next-day handoff evidence and warehouse receipt arrive | Existing tasks resumed, verified the evidence, completed, and notified the user |
   | Pause discovery and the life index, retain work-index maintenance | Discovery/life maintenance stayed paused; the work index completed its incremental checkpoint |
   
   Not run for this PR: full repository tests, full desktop packaging, and an additional visual browser/Electron smoke run.
   
   ## Known behavioral limitations
   
   - Forwarding an unchanged “keep the existing tasks running” instruction woke two waiting tasks unnecessarily in the scenario. They were not duplicate tasks, but performed extra rounds.
   - The Bot can still over-confirm constraints or combine several findings into one long chat bubble. No key scenario finding was lost.
   - Live input is incorporated at the next model request; it cannot undo a tool that has already started or completed. Cancellation remains a separate control operation.
   
   ## AI use
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: OpenAI Codex contributed implementation, tests, debugging, and this PR description. The commit includes a `Generated-by: Codex` trailer.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [ ] Lint, format, typecheck and the affected suites pass locally
     - Type checks and affected tests passed as listed above; whole-change lint/format checks were not run. The latest task-delivery edits were formatted.
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "me2seeks (via GitHub)" <gi...@apache.org>.
me2seeks commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4294711554


##########
packages/runtime-host/src/server/execution-composition.ts:
##########
@@ -466,6 +468,39 @@ export async function createExecutionRuntimeHostComposition(
           if (failures.length)
             throw new AggregateError(failures, 'Failed to stop assistant sessions');
         },
+        readAvatarImage: async (sessionId, source, signal) => {
+          const path = localImagePath(source);
+          return path === undefined
+            ? downloadImage(source, signal)
+            : readLocalImage(sessionId, path, signal);
+        },
+        appendConversation: async (sessionId, message) => {
+          await sessionAdmission.run(sessionId, async (lease) => {
+            if (!personalAssistant.isConversation(sessionId) || !personalAssistant.enabled)

Review Comment:
   **[P2] Keep durable Inbox admission consistent with the visible receipt**
   
   `BotController.receive()` persists the Inbox/outbox row before `flush()` calls `appendConversation`. That callback waits for `sessionAdmission`, then checks `personalAssistant.enabled` here. `assistant.set-enabled(false)` clears `this.runtime` without taking that admission gate. If an append is queued behind an existing admission and reaches this check after disablement, it throws even though the Inbox row is already durable; `turn.message.submit` returns `internal_failure`.
   
   While disabled, `hasInboxMessage()` returns false and the transcript row was never appended, so the execution query can report the message as not admitted. Re-enabling starts a Bot that can flush and process the original row after the client has treated it as failed; retrying with a new message ID can process it twice. Serialize disablement with pending append/admission, or make the durable Inbox receipt authoritative and queryable across disablement.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs merged PR #6124:
URL: https://github.com/apache/maka/pull/6124


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs commented on PR #6124:
URL: https://github.com/apache/maka/pull/6124#issuecomment-6247967573

   @Astro-Han P3 follow-up is pushed in **f471bce2c30882ceb2a4dfdce1a1d6f2d6bc5b64**. Thanks for the detailed review; please re-review the changes and qualifications below.
   
   ### Changes
   - **Protocol/docs:** moved the epoch to **224** after checking current main (222), #6115 (223), #6091 (223), and #6090 (currently 222). The comment now lists Inbox admission/query state, summaries, avatar operations, the binding `bot` block, and connector provenance. The merge-time epoch guard remains authoritative. Updated `browser/session.ts` comments and blocked-action guidance to describe selection/Host authorization rather than an on-screen/open-panel requirement. Hidden/minimized/collapsed-panel operation remains supported.
   - **Provenance:** added a strictly decoded `externalSource` admission field carrying connector/sender identity; when supplied, it survives the Bot bridge, durable Inbox and copied conversation, is marked `external_connector`, and is not recorded as human-authored ledger text. Conflicting dedupe retries cannot erase/change the origin. Task amendments now use `coordinator`, with explicit executor context that they are not new human authorization.
   - **Initiative:** startup resolves the existing assistant conversation instead of letting an arbitrary first tool caller become the config owner; configuration retains the bound cwd. `DiscoveryReport` now checks actual mailbox acceptance and propagates failures.
   - **Avatar:** local images must resolve inside the invoking Session's persisted workspace, retain normal Session filesystem authority, and pass file-type/size/replacement checks. Capture has a 30-second deadline and validates returned image bytes. URL loading retains the existing public-target DNS pinning, per-redirect checks, proxy/outbound policy and streamed 2 MiB limit; added executable tests for these boundaries as well as local traversal/symlink/oversize/cancellation cases.
   - **Renderer/store:** catalog-backed English/zh-CN/zh-TW placeholder and ARIA labels; stable state for identical disconnected-avatar polls; Escape/outside-pointer dismissal for compact composer settings; typing gated on unanswered human/optimistic input rather than Bot working state alone; removed unreachable `queueVisibleBatch` string-array branches. New renderer tests are in the normal desktop test entrypoint.
   
   ### Validation
   - Passed: full build, workspace typecheck, lint, format, locale hygiene, ASF headers, Astryx surface inventory, **desktop-scoped Knip**, strict-base renderer architecture against `d14cec57`, and committed-tree epoch guard (**222 → 224**).
   - Passed: **106/106** focused core/Host tests (including assistant, avatar, initiative, conversation and execution composition); assistant suites **80/80 + 24/24 + 78/78**; focused desktop/browser tests **8/8**. The earlier full desktop and UI suites also passed.
   - **Not claiming an all-green full workspace run:** that invocation did not finish cleanly (CLI remained running until the invocation timeout). Managed-activation and eval shim failures reproduced on an isolated, rebuilt original `db11126c` baseline too. Node 25 TLS transport failures passed on cached Node 24; the missing reused PTY dependency patch was restored and its test passed. A full Node 24 runtime run had one process-cleanup failure, whose unchanged targeted suite passed on retry (12/12). An unrestricted root Knip scan reports fixture/script/generated-artifact findings, including the same 50 unused-file findings on the original baseline; the CI desktop scope passes. No tests, budgets, or check configuration were weakened. Local Electron E2E was not rerun; new-head CI is pending.
   
   ### Explicit limits
   - No in-repository production connector currently supplies the new provenance field. This provides the native admission/persistence boundary; it does **not** establish that every upstream connector is integrated or authenticate a sender from their text.
   - Typing uses transcript pending-human state, not a new Host-certified causal reply-turn identity.
   - Local avatar containment/replacement checks are not descriptor-relative OS isolation against concurrent hostile filesystem mutation; configured proxies retain their existing trusted-egress role.
   
   No merge or force-push was performed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4294982662


##########
apps/desktop/src/renderer/chat-message-surface.tsx:
##########
@@ -27,6 +27,8 @@ import {
   useUiLocale,
   type LiveTurnProjection,
 } from '@maka/ui';
+import { PersonalAssistantTyping } from './features/personal-assistant/typing.js';

Review Comment:
   P2: `check:architecture` rejects this direct feature import (`feature imports must use index`). Re-export `PersonalAssistantTyping` from `./features/personal-assistant/index.js` and import it from there.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4301841745


##########
packages/ui/src/chat-view.tsx:
##########
@@ -847,6 +851,7 @@ export function ChatView(props: {
               {tail}
             </>
           ) : null}
+          {props.activityContent}

Review Comment:
   P1: This adds a second child after the deliberately single `null` child (see the comment above). When `activityContent` is `undefined`, the children become `[null, undefined]`, `ChatMessageList` treats the list as non-empty, and `emptyState` (the hero and the only load-earlier control) never renders. This happens in every session. Repro: `chat-view-load-earlier.test.js` and desktop `chat-view-optimistic-render.test.js` both fail on this head and pass with these two lines removed.



##########
packages/ui/src/chat-view.tsx:
##########
@@ -1053,6 +1059,7 @@ export function ChatView(props: {
               )}
             </>
           )}
+          {props.activityContent}

Review Comment:
   P1: Same issue in the transcript branch. When `showEmptyState` is true, this extra sibling suppresses `emptyState`, which holds `loadEarlierHistoryControl`.



##########
packages/runtime-host/src/protocol/index.ts:
##########
@@ -107,7 +107,8 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
 export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
 // Increment when the same protocol version no longer guarantees safe Client-Host
 // interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 222 as const;
+// 223: Assistant conversation message admission can return an Inbox receipt without a model Turn.
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 223 as const;

Review Comment:
   P3: 223 is also claimed by open PRs #6115, #6091 and #6090. The comment should also list assistant.avatar, assistant.avatar-image, the `bot` block on assistant.binding, the `inbox` execution-query state and the optional text `summary`.



##########
apps/desktop/src/renderer/chat-message-surface.tsx:
##########
@@ -27,6 +27,8 @@ import {
   useUiLocale,
   type LiveTurnProjection,
 } from '@maka/ui';
+import { PersonalAssistantTyping } from './features/personal-assistant/typing.js';

Review Comment:
   P2 (check:architecture): Import this through `features/personal-assistant/index.js`. Even after that change and `--write`, the strict-base ratchet still rejects the new `useAssistantAvatar` hook call here (hookCalls 4 -> 5) and the app-shell.tsx token growth (7285 -> 7337). Move that logic behind a feature-owned component.



##########
packages/runtime-host/src/server/execution-composition.ts:
##########
@@ -466,6 +468,39 @@ export async function createExecutionRuntimeHostComposition(
           if (failures.length)
             throw new AggregateError(failures, 'Failed to stop assistant sessions');
         },
+        readAvatarImage: async (sessionId, source, signal) => {
+          const path = localImagePath(source);
+          return path === undefined
+            ? downloadImage(source, signal)
+            : readLocalImage(sessionId, path, signal);
+        },
+        appendConversation: async (sessionId, message) => {
+          await sessionAdmission.run(sessionId, async (lease) => {
+            if (!personalAssistant.isConversation(sessionId) || !personalAssistant.enabled)
+              throw Error('Assistant conversation is unavailable');
+            const header = await stores.sessionStore.readHeaderSnapshot(sessionId);

Review Comment:
   P2 (me2seeks's finding, corroborated by code reading): The `enabled` guard is read once, before the awaits, and never re-checked, and the caller (`BotController.flush()`, controller.ts:108-125) awaits `appendConversation` before marking the outbox row delivered. So the interleaving the code permits is: flush enters `appendConversation` with one pending row; `assistant.set-enabled(false)` lands inside `await publishBotConversationMessage(...)`; the guard is not re-read, so both durable writes complete and the row is marked delivered; the `user_message` is then consumed by `seq` on the bot's next run, i.e. after re-enable. Bounded to at most one message, because the next loop iteration's `this.ready()` throws post-abort. I did not build or run a test for this.



##########
apps/desktop/src/renderer/app-shell.tsx:
##########
@@ -1364,6 +1365,9 @@ function AppShellContent({
                   contextPickEnabled={canStageComposerContext}
                   executorComposer={{ selection: executor, taskSubmissionHardBlocked, connectionCount: connections.length, onSetup: () => openSettingsSection('external-agents'), onNewTask: openNewTaskSurface }}
                   activeSession={activeSessionForView}
+                  compactControls={activeSessionForView?.labels?.includes('personal-assistant')}
+                  placeholder={activeSessionForView?.labels?.includes('personal-assistant')
+                    ? (uiLocale === 'zh-CN' ? '聊点什么…' : 'Send a message…') : undefined}

Review Comment:
   P3: The inline locale ternary sends zh-TW to English and grows app-shell.tsx tokens, which the architecture ratchet rejects. Use a catalog entry owned by the feature.



##########
apps/desktop/src/renderer/features/personal-assistant/avatar.tsx:
##########
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { useEffect, useState } from 'react';
+import { DEFAULT_ASSISTANT_AVATAR, assistantAvatarSchema, type AssistantAvatar } from '@maka/runtime-host/protocol';
+import { usePersonalAssistantServices } from './services.js';
+import { originalHost } from './navigation.js';
+
+type AvatarView = AssistantAvatar & { imageUrl?: string };
+
+export function useAssistantAvatar(enabled: boolean, sessionId?: string) {
+  const services = usePersonalAssistantServices();
+  const [state, setState] = useState<{ scope?: string; avatar: AvatarView }>({ avatar: DEFAULT_ASSISTANT_AVATAR });
+  useEffect(() => {
+    if (!enabled) return;
+    let live = true;
+    let cachedImage: { id: string; url: string } | undefined;
+    let timer: ReturnType<typeof setTimeout>;
+    const refresh = async () => {
+      try {
+        const host = sessionId
+          ? originalHost(sessionId, (await services.hostSnapshot()).entries).host
+          : await services.defaultHost();
+        const result = await services.call('assistant.avatar', {}, host);
+        const avatar: AvatarView = assistantAvatarSchema.parse(result.avatar);
+        if (avatar.image) {
+          if (cachedImage?.id !== avatar.image.id) {
+            let data = '';
+            while (live && data.length < avatar.image.length) {
+              const chunk = await services.call('assistant.avatar-image', { id: avatar.image.id, offset: data.length }, host);
+              if (chunk.id !== avatar.image.id || chunk.offset !== data.length || typeof chunk.data !== 'string'
+                || !chunk.data.length || data.length + chunk.data.length > avatar.image.length) throw Error('Invalid avatar image');
+              data += chunk.data;
+            }
+            if (!live) return;
+            cachedImage = { id: avatar.image.id, url: `data:${avatar.image.mimeType};base64,${data}` };
+          }
+          avatar.imageUrl = cachedImage.url;
+        } else cachedImage = undefined;
+        if (live) setState((old) => old.scope === sessionId && old.avatar.emoji === avatar.emoji && old.avatar.background === avatar.background && old.avatar.imageUrl === avatar.imageUrl
+          ? old : { scope: sessionId, avatar });
+      } catch {
+        // A disconnected Host must not display another Host's identity.
+        if (live) setState({ scope: sessionId, avatar: DEFAULT_ASSISTANT_AVATAR });

Review Comment:
   P3: On Host failure this sets a fresh object every 3 s. That changes the `assistantAvatar` element and re-renders every memoized TurnView. Dedupe like the success path does.



##########
apps/desktop/src/main/browser-ipc-main.ts:
##########
@@ -99,7 +99,7 @@ export function registerBrowserIpc(deps: BrowserIpcDeps): BrowserIpcController {
     const owner = ownerForSession(sessionId);
     if (!owner || !browserParentForRenderer(owner)) return false;
     const ref = parseDesktopSessionResourceKey(sessionId);
-    return isWorkHubCoordinationSessionId(ref.sessionId) && deps.isHostActive(ref);
+    return deps.isHostActive(ref);

Review Comment:
   P2: With hidden ordinary Sessions now allowed to act, the previous Session keeps this access until the renderer's next `browser:active-session` arrives. `browser-selection.ts:63-84` sends that only after the new Session's Host identity resolves, and sends nothing to revoke the old selection first. Reproduced: while B's resolution was pending, a hidden and collapsed A still executed `browser_click`. Revoke the old selection immediately on change, then show the new one when it resolves.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4306547565


##########
packages/runtime-host/src/assistant/index-initiative/controller.ts:
##########
@@ -45,12 +47,27 @@ export class InitiativeController {
       this.owned = owned;
     };
     acquire();
+    this.bindingReady = this.resolveBinding();

Review Comment:
   P3: this promise is computed once and never retried. If `sessionQuery.list()` rejects at startup, `assistant.bind`, `enable` and `configure` keep throwing until the Host restarts, even when the failure was transient. Consider memoizing only success, or re-running `resolveBinding()` after a rejection.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on PR #6124:
URL: https://github.com/apache/maka/pull/6124#issuecomment-6227612510

   @xxhZs Thanks for pushing this forward! The Inbox and `SendUser` changes feel much closer to the Bot discussed in #6076.
   
   One thought as I was reading: could this and WorkHub gradually become the same thing? They both receive requests, delegate work and bring results back. I’d love to end up with one Bot I can talk to from the desktop or IM, and let it manage the Sessions underneath.
   
   I also feel there are quite a few concepts and special flows now, across both implementations. I’d be happy to drop more of them—for example, I don’t need every task to go through a separate model review or a draft/checkpoint/settlement process. If the existing Host, Session and scheduling capabilities can do the job, I’d prefer to build on those and remove the extra machinery.
   
   No need to fit all of this into this PR. I mainly wanted to compare notes on the direction and see what could disappear as the two come together. What do you think?
   
   <details>
   <summary>中文版</summary>
   
   @xxhZs 感谢推进!Inbox 和 `SendUser` 这部分,感觉已经更接近 #6076 里讨论的 Bot 了。
   
   我看下来有个想法:这套是不是可以逐渐和 WorkHub 合成一个?两边都在接收要求、委派工作、拿回结果。我希望最后就是一个 Bot,桌面和 IM 都能找它,底下的 Session 由它管理。
   
   另外,两边现在的概念和专用流程都有点多,我觉得可以再大胆删一些。比如我不需要每个任务都经过独立模型审核,也不一定需要草稿、checkpoint、结算这一整套流程。现有 Host、Session 和调度能力能解决的,就尽量复用,把多出来的机制去掉。
   
   不用都放进这个 PR,我主要想先聊聊这个方向,看看两边合到一起时,哪些东西可以顺便删掉。你觉得呢?
   
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs commented on PR #6124:
URL: https://github.com/apache/maka/pull/6124#issuecomment-6228714695

   @Astro-Han Yes, the long-term plan is to bring the assistant/Bot and WorkHub together as one. There are quite a few design decisions and changes involved at the moment, so we are keeping them separate for now and will gradually merge them over time.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4302808270


##########
apps/desktop/src/renderer/features/personal-assistant/index.tsx:
##########
@@ -24,7 +24,8 @@ import {
   useShowAssistantBackgroundSessions,
 } from '../../application/contracts/session-catalog/assistant-session-visibility.js';
 import { SideNavItem } from '@astryxdesign/core/SideNav';
-import { Sparkles } from '@maka/ui/icons';
+import { PersonalAssistantAvatar, useAssistantAvatar } from './avatar.js';
+export { PersonalAssistantAvatar, useAssistantAvatar } from './avatar.js';

Review Comment:
   P2 (CI): Knip (apps/desktop) fails on this head because `PersonalAssistantAvatar` and `useAssistantAvatar` are no longer imported through the barrel. `chat-presentation.tsx` imports `./avatar.js` directly, and this file uses them through line 27. Deleting this re-export, together with the `PersonalAssistantTyping` re-export at line 467, makes `npx knip --workspace apps/desktop` pass locally, and the strict-base architecture check still passes.



##########
apps/desktop/src/renderer/features/personal-assistant/index.tsx:
##########
@@ -459,3 +462,6 @@ function PersonalAssistantStatusSettings({
 }
 
 export { createInternalUriDispatcher } from './internal-uri.js';
+
+export { PersonalAssistantChatPresentation, PersonalAssistantChatLayout, PersonalAssistantComposer } from './chat-presentation.js';
+export { PersonalAssistantTyping } from './typing.js';

Review Comment:
   P2 (CI): This re-export is unused, because `chat-presentation.tsx` imports `./typing.js` directly. Knip reports it as an unused export, and that is the current CI `test` failure.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4292926721


##########
apps/desktop/src/main/browser-ipc-main.ts:
##########
@@ -99,7 +99,7 @@ export function registerBrowserIpc(deps: BrowserIpcDeps): BrowserIpcController {
     const owner = ownerForSession(sessionId);
     if (!owner || !browserParentForRenderer(owner)) return false;
     const ref = parseDesktopSessionResourceKey(sessionId);
-    return isWorkHubCoordinationSessionId(ref.sessionId) && deps.isHostActive(ref);
+    return deps.isHostActive(ref);

Review Comment:
   [P1] Preserve the ordinary-Session browser visibility gate
   
   Removing the coordination-Session predicate grants every selected ordinary Session a background action lease. A renderer can remain selected while its parent view or native window is hidden/minimized. `createBrowserViewHost.canDrive` then returns true before checking visibility/viewport, and `revokeHiddenActions` no longer severs its running action. An agent can therefore read or mutate an authenticated page that the user cannot see, contrary to the explicit security policy in browser/logic.ts:99–107.
   
   Using the registered IPC and actual `withBrowserPage` path with the existing native/CDP fixture, I observed all three action callbacks execute with the ordinary owner hidden, its window hidden, and its window minimized. Loading only the actual d6ff9119 IPC module blocks all nine with BrowserActionBlockedError. Collapsing the panel also newly admits mutation without a viewport. The changed test now expects these hidden actions to succeed and removes the revocation assertion.
   
   Keep background access restricted to WorkHub coordination as before, or explicitly revoke ordinary-Session access when the view/window is hidden, minimized or the panel is collapsed. Retain negative tests for hidden reads, mutations and in-flight revocation; selection/Host identity alone is not an equivalent security boundary.



##########
packages/ui/src/message-summary.tsx:
##########
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { useId, useState, type ReactNode } from 'react';
+import { Markdown } from './markdown.js';
+import { ChevronDown } from './icons.js';
+import { assistantChatCopy } from './assistant-chat-copy.js';
+import { useUiLocale } from './locale-context.js';
+
+/** Short and legacy messages stay plain; only authored summaries are collapsible. */
+export function MessageSummary({ summary, children }: { summary?: string; children: ReactNode }) {
+  const [expanded, setExpanded] = useState(false);
+  const bodyId = useId();
+  const locale = useUiLocale();
+  if (!summary) return <>{children}</>;
+  const labels = assistantChatCopy(locale);
+  return (
+    <div className="maka-message-summary">
+      <div className="maka-message-summary-preview"><Markdown text={summary} density="compact" /></div>
+      <div id={bodyId} className="maka-message-summary-body" hidden={!expanded}>{children}</div>
+      <button

Review Comment:
   [P2] Restore the mandatory checks for the new summary component and SendUser shape
   
   `npm run astryx:surface-inventory` fails on this new raw `<button>`: Astryx owns this primitive, so the checker requires Astryx Button (and its documented variants) rather than a hand-written control/custom-control styling. This is a mandatory CI step, independent of the now-fixed locale/format checks.
   
   The normal assistant test chain also still uses legacy string arrays at proactive-matters/test/assistant-loop.test.ts:44,190 and source-assistant-loop.test.ts:149, while SendUser now validates `{text, summary?}` objects. The unchanged tests fail (179/182 pass); adapting only their fixture arguments to objects makes the four affected integration cases pass. Please migrate those callers as well as replacing this control, then rerun both mandatory checks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4296605231


##########
apps/desktop/src/main/browser-ipc-main.ts:
##########
@@ -99,7 +99,7 @@ export function registerBrowserIpc(deps: BrowserIpcDeps): BrowserIpcController {
     const owner = ownerForSession(sessionId);
     if (!owner || !browserParentForRenderer(owner)) return false;
     const ref = parseDesktopSessionResourceKey(sessionId);
-    return isWorkHubCoordinationSessionId(ref.sessionId) && deps.isHostActive(ref);
+    return deps.isHostActive(ref);

Review Comment:
   @Astro-Han Browser operation while the Maka window is hidden or minimized, or the browser panel is collapsed, is intended product behavior. Please re-review the browser finding on that basis, including whether the remaining selected-session ownership, renderer lifetime, active Host and epoch checks are sufficient for this intended capability. This clarification does not claim that the separate Inbox admission race or architecture-check failures have been fixed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4287228148


##########
packages/ui/src/composer.tsx:
##########
@@ -2510,6 +2513,7 @@ export const Composer = forwardRef<
                   </DropdownMenu>
                 </span>
               ) : null}
+              <ComposerConfiguration compact={props.compactControls} label={locale === 'zh-CN' ? '聊天选项' : 'Chat options'}>

Review Comment:
   P2: This new `locale === 'zh-CN'` branch fails the required locale-hygiene check (`locale-literal-compare 0 -> 1`), so the `test` job is red. Please move the label into the UiCatalog.



##########
packages/runtime-host/src/assistant/bot/controller.ts:
##########
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
+import { ASSISTANT_BACKGROUND_SESSION_LABEL } from '@maka/core/session';
+import type { MessageContent } from '@maka/core/events';
+import type { AssistantModuleServices } from '../service.js';
+import type { InitiativeStore } from '../index-initiative/store.js';
+import { BotStore, type InboxInput } from './store.js';
+
+const UNREAD_SLEEP_FEEDBACK =
+  '本次未能休眠:你读取 Inbox 后又收到新消息,或上一批还有未投递消息。请调用 InboxCheck 接收正文,再自行决定如何处理;不要求回复或完成每件事,之后可再次调用 Sleep。';
+
+export class BotController {
+  readonly abort = new AbortController();
+  private timer?: ReturnType<typeof setInterval>;
+  private running?: Promise<void>;
+  private flushing?: Promise<void>;
+  private activeAgent?: any;
+  private deliveredThrough = 0;
+  private deliveries = new Map<string, ReturnType<BotStore['batch']>>();
+  checkInbox(callId: string, limit: number) {
+    this.ready();
+    const previous = this.deliveries.get(callId);
+    if (previous) return previous;
+    const batch = this.store.batch(this.deliveredThrough, limit);
+    this.deliveredThrough = batch.through;
+    this.deliveries.set(callId, batch);
+    return batch;
+  }
+  isSleeping() {
+    return (
+      !this.running &&
+      !this.store.get('error') &&
+      this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)
+    );
+  }
+  constructor(
+    readonly ctx: AssistantModuleServices,
+    readonly binding: InitiativeStore,
+    readonly store: BotStore,
+  ) {}
+  owner() {
+    return this.binding.get()?.sessionId as string | undefined;
+  }
+  worker() {
+    return this.store.get<string>('worker');
+  }
+  invocation(sessionId = this.owner()!) {
+    return {
+      sessionId,
+      cwd: this.binding.get().cwd,
+      emitOutput: () => {},
+      turnId: 'assistant-bot',
+      toolCallId: randomUUID(),
+      abortSignal: this.abort.signal,
+    };
+  }
+  start() {
+    this.timer = setInterval(() => this.tick(), 1000);
+    this.timer.unref?.();
+    this.tick();
+  }
+  ready() {
+    this.abort.signal.throwIfAborted();
+    this.binding.fence();
+  }
+  post(input: InboxInput) {
+    this.ready();
+    this.store.post(input);
+    this.tick();
+  }
+  async receive(id: string, content: MessageContent) {
+    this.ready();
+    this.store.post(
+      { id, type: 'user_message', source: 'user', content },
+      {
+        ...content,
+        type: 'user',
+        id,
+        turnId: `assistant-input:${id}`,
+        ts: Date.now(),
+      },
+    );
+    await this.flush();
+    this.tick();
+  }
+  async flush(): Promise<void> {
+    if (this.flushing) {
+      await this.flushing;
+      if (this.store.pendingVisible().length) await this.flush();
+      return;
+    }
+    this.flushing = (async () => {
+      for (const message of this.store.pendingVisible()) {
+        this.ready();
+        if (!this.ctx.appendConversation)
+          throw Error('Assistant conversation transport unavailable');
+        await this.ctx.appendConversation(this.owner()!, message);
+        this.store.delivered(message.id);
+      }
+    })().finally(() => {
+      this.flushing = undefined;
+    });
+    return this.flushing;
+  }
+  async agent() {
+    return this.ctx.agents.withInvocation(this.invocation(), async () => {
+      let id = this.worker();
+      if (!id) {
+        const label = `assistant-bot:${this.owner()}`;
+        const matches = (await this.ctx.sessionQuery.list()).filter((s: any) =>
+          s.labels?.includes(label),
+        );
+        if (matches.length > 1)
+          throw Error('Multiple Bot workers found; cannot choose a conversation');
+        id = matches[0]?.id;
+        if (!id)
+          id = (
+            await this.ctx.agents.create({
+              background: true,
+              name: '个人助手 · Bot',
+              labels: [label, ASSISTANT_BACKGROUND_SESSION_LABEL],
+            })
+          ).sessionId;
+        this.store.set('worker', id);
+      }
+      return this.ctx.agents.resume({ sessionId: id! });
+    });
+  }
+  tick() {
+    if (this.running || this.abort.signal.aborted || !this.owner()) return;
+    try {
+      this.ready();
+    } catch {
+      return;
+    }
+    this.running = this.run()
+      .catch((error) => {
+        if (!this.abort.signal.aborted) this.store.set('error', String(error));
+      })
+      .finally(() => {
+        this.running = undefined;
+      });
+  }
+  private async run() {
+    await this.flush();
+    if (this.store.get('error')) return;
+    if (this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)) {
+      this.store.set('wake', null);
+      this.store.set('wakeError', null);
+      return;
+    }
+    // Commit delivery only at a normal Sleep boundary. An interrupted loop may
+    // replay mail, but cannot lose it between a tool return and durable history.
+    this.deliveredThrough = this.store.get<number>('deliveredThrough') ?? 0;
+    this.deliveries.clear();
+    const agent = await this.agent();
+    this.activeAgent = agent;
+    try {
+      const status = ((await agent.snapshot()) as any)?.agent?.status;
+      if (['blocked', 'waiting_for_user'].includes(status))
+        throw Error('Bot requires attention in its worker Session');
+      let wake = this.store.get<{ messageId: string; text: string }>('wake');
+      if (wake || status !== 'running') {
+        if (!wake) {
+          this.store.set('sleepTurn', null);
+          wake = {
+            messageId: randomUUID(),
+            text: `Inbox 有新消息。当前 UTC 时间:${new Date().toISOString()}。用 InboxCheck 批量接收新消息正文,自主决定如何处理;不需要轮询。`,
+          };
+          // Persist before submission: an ambiguous response must not create another wake.
+          this.store.set('wake', wake);
+        }
+        for (;;) {
+          this.ready();
+          let resolution: any;
+          try {
+            resolution = await agent.messageExecution(wake.messageId);
+            if (resolution?.state === 'not_admitted') {
+              const admitted: any = await agent.followup(wake.text, { messageId: wake.messageId });
+              if (!['turn_started', 'followup'].includes(admitted?.disposition))
+                throw Error('Bot wake was not admitted');
+              if (admitted.disposition === 'turn_started') {
+                this.store.set('wakeError', null);
+                break;
+              }
+            }
+          } catch (error) {
+            // Retry reconciliation on the next scheduler tick, keeping the submission identity.
+            this.store.set('wakeError', String(error));
+            return;
+          }
+          this.store.set('wakeError', null);
+          if (resolution?.state === 'owned') break;
+          if (resolution?.state === 'cancelled') {
+            this.store.set('wake', null);
+            throw Error('Bot wake was cancelled; Inbox is preserved');
+          }
+          if (!['pending', 'not_admitted'].includes(resolution?.state))

Review Comment:
   P3: `queryMessageExecutions` leaves out ids that are still in `#pendingSubmits` ("cannot say yet"). That makes `resolution` `undefined`, which ends up here as a sticky `error`. It should be retried like `pending`.



##########
packages/runtime-host/src/assistant/bot/controller.ts:
##########
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
+import { ASSISTANT_BACKGROUND_SESSION_LABEL } from '@maka/core/session';
+import type { MessageContent } from '@maka/core/events';
+import type { AssistantModuleServices } from '../service.js';
+import type { InitiativeStore } from '../index-initiative/store.js';
+import { BotStore, type InboxInput } from './store.js';
+
+const UNREAD_SLEEP_FEEDBACK =
+  '本次未能休眠:你读取 Inbox 后又收到新消息,或上一批还有未投递消息。请调用 InboxCheck 接收正文,再自行决定如何处理;不要求回复或完成每件事,之后可再次调用 Sleep。';
+
+export class BotController {
+  readonly abort = new AbortController();
+  private timer?: ReturnType<typeof setInterval>;
+  private running?: Promise<void>;
+  private flushing?: Promise<void>;
+  private activeAgent?: any;
+  private deliveredThrough = 0;
+  private deliveries = new Map<string, ReturnType<BotStore['batch']>>();
+  checkInbox(callId: string, limit: number) {
+    this.ready();
+    const previous = this.deliveries.get(callId);
+    if (previous) return previous;
+    const batch = this.store.batch(this.deliveredThrough, limit);
+    this.deliveredThrough = batch.through;
+    this.deliveries.set(callId, batch);
+    return batch;
+  }
+  isSleeping() {
+    return (
+      !this.running &&
+      !this.store.get('error') &&
+      this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)
+    );
+  }
+  constructor(
+    readonly ctx: AssistantModuleServices,
+    readonly binding: InitiativeStore,
+    readonly store: BotStore,
+  ) {}
+  owner() {
+    return this.binding.get()?.sessionId as string | undefined;
+  }
+  worker() {
+    return this.store.get<string>('worker');
+  }
+  invocation(sessionId = this.owner()!) {
+    return {
+      sessionId,
+      cwd: this.binding.get().cwd,
+      emitOutput: () => {},
+      turnId: 'assistant-bot',
+      toolCallId: randomUUID(),
+      abortSignal: this.abort.signal,
+    };
+  }
+  start() {
+    this.timer = setInterval(() => this.tick(), 1000);
+    this.timer.unref?.();
+    this.tick();
+  }
+  ready() {
+    this.abort.signal.throwIfAborted();
+    this.binding.fence();
+  }
+  post(input: InboxInput) {
+    this.ready();
+    this.store.post(input);
+    this.tick();
+  }
+  async receive(id: string, content: MessageContent) {
+    this.ready();
+    this.store.post(
+      { id, type: 'user_message', source: 'user', content },
+      {
+        ...content,
+        type: 'user',
+        id,
+        turnId: `assistant-input:${id}`,
+        ts: Date.now(),
+      },
+    );
+    await this.flush();
+    this.tick();
+  }
+  async flush(): Promise<void> {
+    if (this.flushing) {
+      await this.flushing;
+      if (this.store.pendingVisible().length) await this.flush();
+      return;
+    }
+    this.flushing = (async () => {
+      for (const message of this.store.pendingVisible()) {
+        this.ready();
+        if (!this.ctx.appendConversation)
+          throw Error('Assistant conversation transport unavailable');
+        await this.ctx.appendConversation(this.owner()!, message);
+        this.store.delivered(message.id);
+      }
+    })().finally(() => {
+      this.flushing = undefined;
+    });
+    return this.flushing;
+  }
+  async agent() {
+    return this.ctx.agents.withInvocation(this.invocation(), async () => {
+      let id = this.worker();
+      if (!id) {
+        const label = `assistant-bot:${this.owner()}`;
+        const matches = (await this.ctx.sessionQuery.list()).filter((s: any) =>
+          s.labels?.includes(label),
+        );
+        if (matches.length > 1)
+          throw Error('Multiple Bot workers found; cannot choose a conversation');
+        id = matches[0]?.id;
+        if (!id)
+          id = (
+            await this.ctx.agents.create({
+              background: true,
+              name: '个人助手 · Bot',
+              labels: [label, ASSISTANT_BACKGROUND_SESSION_LABEL],
+            })
+          ).sessionId;
+        this.store.set('worker', id);
+      }
+      return this.ctx.agents.resume({ sessionId: id! });
+    });
+  }
+  tick() {
+    if (this.running || this.abort.signal.aborted || !this.owner()) return;
+    try {
+      this.ready();
+    } catch {
+      return;
+    }
+    this.running = this.run()
+      .catch((error) => {
+        if (!this.abort.signal.aborted) this.store.set('error', String(error));
+      })
+      .finally(() => {
+        this.running = undefined;
+      });
+  }
+  private async run() {
+    await this.flush();
+    if (this.store.get('error')) return;
+    if (this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)) {
+      this.store.set('wake', null);
+      this.store.set('wakeError', null);
+      return;
+    }
+    // Commit delivery only at a normal Sleep boundary. An interrupted loop may
+    // replay mail, but cannot lose it between a tool return and durable history.
+    this.deliveredThrough = this.store.get<number>('deliveredThrough') ?? 0;
+    this.deliveries.clear();
+    const agent = await this.agent();
+    this.activeAgent = agent;
+    try {
+      const status = ((await agent.snapshot()) as any)?.agent?.status;
+      if (['blocked', 'waiting_for_user'].includes(status))
+        throw Error('Bot requires attention in its worker Session');
+      let wake = this.store.get<{ messageId: string; text: string }>('wake');
+      if (wake || status !== 'running') {

Review Comment:
   P3: After a Host crash in the middle of a Bot turn, the persisted `wake` reports `owned`. This branch then skips submitting a new wake, `whenIdle()` returns at once, and `run()` throws "Bot ended without Sleep", so the pending mail waits for the next Inbox post. I reproduced this with BotController/BotStore and a stub agent (`owned` + `idle`): 0 submissions, `error` set. At aae6420c a fresh wake was submitted in this case. Consider treating an `owned` wake as consumed when the worker isn't running and `sleepTurn` is unset.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4294642155


##########
apps/desktop/src/main/browser-ipc-main.ts:
##########
@@ -99,7 +99,7 @@ export function registerBrowserIpc(deps: BrowserIpcDeps): BrowserIpcController {
     const owner = ownerForSession(sessionId);
     if (!owner || !browserParentForRenderer(owner)) return false;
     const ref = parseDesktopSessionResourceKey(sessionId);
-    return isWorkHubCoordinationSessionId(ref.sessionId) && deps.isHostActive(ref);
+    return deps.isHostActive(ref);

Review Comment:
   The feature owner has explicitly confirmed that background browser operation includes a hidden or minimized Maka window, as well as a collapsed browser panel. This does not exceed the requested product scope; the changed admission expectations are intentional. We will retain this capability rather than restore visibility-based denial. This does not authorize arbitrary unselected sessions: selected-session ownership, renderer lifetime, active Host and epoch checks still apply. The old visibility-only policy comment needs to be reconciled with this intentional policy change; it should not be treated as evidence that the requested behavior itself is accidental.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #6124:
URL: https://github.com/apache/maka/pull/6124#discussion_r4285006753


##########
packages/runtime-host/src/server/execution-composition.ts:
##########
@@ -466,6 +466,32 @@ export async function createExecutionRuntimeHostComposition(
           if (failures.length)
             throw new AggregateError(failures, 'Failed to stop assistant sessions');
         },
+        readAvatarImage: async (sessionId, source, signal) => {
+          const path = localImagePath(source);
+          return path === undefined ? downloadImage(source, signal) : readLocalImage(sessionId, path, signal);
+        },
+        appendConversation: async (sessionId, message) => {
+          await sessionAdmission.run(sessionId, async (lease) => {
+            if (!personalAssistant.isConversation(sessionId) || !personalAssistant.enabled)
+              throw Error('Assistant conversation is unavailable');
+            const header = await stores.sessionStore.readHeaderSnapshot(sessionId);
+            const existing = (await stores.sessionStore.readMessagesSnapshot(sessionId)).find(
+              (row) => row.id === message.id,
+            );
+            if (existing) {
+              if (JSON.stringify(existing) !== JSON.stringify(message))

Review Comment:
   P2: `existing` is re-canonicalized by the session store (content fields such as `inlineReferences`/`displayText` move after `type/id/turnId/ts`), but `message` keeps outbox key order. The desktop always sends `inlineReferences`. So after a crash or `refreshCanonical` failure between `appendMessages` and `store.delivered()`, this check throws on every retry. Because `flush()` stops at the first pending row, the assistant outbox and Bot are blocked permanently. I reproduced it in the real composition test using `inlineReferences: []` plus a reset `delivered` flag: the retry and a later new message both returned `Assistant message identity conflict`. Please compare canonical forms on both sides.



##########
packages/runtime-host/src/assistant/bot/controller.ts:
##########
@@ -0,0 +1,242 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
+import { ASSISTANT_BACKGROUND_SESSION_LABEL } from '@maka/core/session';
+import type { MessageContent } from '@maka/core/events';
+import type { AssistantModuleServices } from '../service.js';
+import type { InitiativeStore } from '../index-initiative/store.js';
+import { BotStore, type InboxInput } from './store.js';
+
+const UNREAD_SLEEP_FEEDBACK =
+  '本次未能休眠:你读取 Inbox 后又收到新消息,或上一批还有未投递消息。请调用 InboxCheck 接收正文,再自行决定如何处理;不要求回复或完成每件事,之后可再次调用 Sleep。';
+
+export class BotController {
+  readonly abort = new AbortController();
+  private timer?: ReturnType<typeof setInterval>;
+  private running?: Promise<void>;
+  private flushing?: Promise<void>;
+  private activeAgent?: any;
+  private deliveredThrough = 0;
+  private deliveries = new Map<string, ReturnType<BotStore['batch']>>();
+  checkInbox(callId: string, limit: number) {
+    this.ready();
+    const previous = this.deliveries.get(callId);
+    if (previous) return previous;
+    const batch = this.store.batch(this.deliveredThrough, limit);
+    this.deliveredThrough = batch.through;
+    this.deliveries.set(callId, batch);
+    return batch;
+  }
+  isSleeping() {
+    return (
+      !this.running &&
+      !this.store.get('error') &&
+      this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)
+    );
+  }
+  constructor(
+    readonly ctx: AssistantModuleServices,
+    readonly binding: InitiativeStore,
+    readonly store: BotStore,
+  ) {}
+  owner() {
+    return this.binding.get()?.sessionId as string | undefined;
+  }
+  worker() {
+    return this.store.get<string>('worker');
+  }
+  invocation(sessionId = this.owner()!) {
+    return {
+      sessionId,
+      cwd: this.binding.get().cwd,
+      emitOutput: () => {},
+      turnId: 'assistant-bot',
+      toolCallId: randomUUID(),
+      abortSignal: this.abort.signal,
+    };
+  }
+  start() {
+    this.timer = setInterval(() => this.tick(), 1000);
+    this.timer.unref?.();
+    this.tick();
+  }
+  ready() {
+    this.abort.signal.throwIfAborted();
+    this.binding.fence();
+  }
+  post(input: InboxInput) {
+    this.ready();
+    this.store.post(input);
+    this.tick();
+  }
+  async receive(id: string, content: MessageContent) {
+    this.ready();
+    this.store.post(
+      { id, type: 'user_message', source: 'user', content },
+      {
+        ...content,
+        type: 'user',
+        id,
+        turnId: `assistant-input:${id}`,
+        ts: Date.now(),
+      },
+    );
+    await this.flush();
+    this.tick();
+  }
+  async flush(): Promise<void> {
+    if (this.flushing) {
+      await this.flushing;
+      if (this.store.pendingVisible().length) await this.flush();
+      return;
+    }
+    this.flushing = (async () => {
+      for (const message of this.store.pendingVisible()) {
+        this.ready();
+        if (!this.ctx.appendConversation)
+          throw Error('Assistant conversation transport unavailable');
+        await this.ctx.appendConversation(this.owner()!, message);
+        this.store.delivered(message.id);
+      }
+    })().finally(() => {
+      this.flushing = undefined;
+    });
+    return this.flushing;
+  }
+  async agent() {
+    return this.ctx.agents.withInvocation(this.invocation(), async () => {
+      let id = this.worker();
+      if (!id) {
+        const label = `assistant-bot:${this.owner()}`;
+        const matches = (await this.ctx.sessionQuery.list()).filter((s: any) =>
+          s.labels?.includes(label),
+        );
+        if (matches.length > 1)
+          throw Error('Multiple Bot workers found; cannot choose a conversation');
+        id = matches[0]?.id;
+        if (!id)
+          id = (
+            await this.ctx.agents.create({
+              background: true,
+              name: '个人助手 · Bot',
+              labels: [label, ASSISTANT_BACKGROUND_SESSION_LABEL],
+            })
+          ).sessionId;
+        this.store.set('worker', id);
+      }
+      return this.ctx.agents.resume({ sessionId: id! });
+    });
+  }
+  tick() {
+    if (this.running || this.abort.signal.aborted || !this.owner()) return;
+    try {
+      this.ready();
+    } catch {
+      return;
+    }
+    this.running = this.run()
+      .catch((error) => {
+        if (!this.abort.signal.aborted) this.store.set('error', String(error));
+      })
+      .finally(() => {
+        this.running = undefined;
+      });
+  }
+  private async run() {
+    await this.flush();
+    if (
+      this.store.get('error') ||
+      this.store.head() <= (this.store.get<number>('deliveredThrough') ?? 0)
+    )
+      return;
+    // Commit delivery only at a normal Sleep boundary. An interrupted loop may
+    // replay mail, but cannot lose it between a tool return and durable history.
+    this.deliveredThrough = this.store.get<number>('deliveredThrough') ?? 0;
+    this.deliveries.clear();
+    const agent = await this.agent();
+    this.activeAgent = agent;
+    try {
+      const status = ((await agent.snapshot()) as any)?.agent?.status;
+      if (['blocked', 'waiting_for_user'].includes(status))
+        throw Error('Bot requires attention in its worker Session');
+      if (status !== 'running') {
+        this.store.set('sleepTurn', null);
+        const wakeId = randomUUID();
+        const admitted: any = await agent.followup(
+          `Inbox 有新消息。唤醒 ID:${wakeId}。当前 UTC 时间:${new Date().toISOString()}。用 InboxCheck 批量接收新消息正文,自主决定如何处理;不需要轮询。`,
+        );
+        if (!['turn_started', 'followup'].includes(admitted?.disposition))
+          throw Error('Bot wake was not admitted');
+        // A queued wake is not complete until its message entered the worker history.
+        while (

Review Comment:
   P3: this transcript poll has no deadline and serializes the whole worker transcript every 25 ms. If the queued follow-up never appears (for example, it is cancelled), `running` stays set and the Bot stalls until restart. Consider a bounded wait that records an error, or an admission-acknowledgement signal.



##########
packages/runtime-host/src/assistant/proactive-matters/controller.ts:
##########
@@ -101,7 +101,7 @@ export class MatterController {
     }
     this.store.enqueueDue();
     for (const m of this.store.list()) {
-      if (!this.active || this.runs.size >= 2) break;
+      if (!this.active || this.runs.size >= 15) break;

Review Comment:
   P3: concurrent task runs go from 2 to 15, which the PR description doesn't mention. Is this intended? It significantly changes resource and provider-rate load.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(assistant): coordinate work through a durable inbox bot [maka]

Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs commented on PR #6124:
URL: https://github.com/apache/maka/pull/6124#issuecomment-6248129409

   @Astro-Han Follow-up **c59ff5a0902ba19f2d939610ec05f3928339b15b** is now pushed, completing the minimal provenance wiring for the **existing desktop Bot-channel production path**. This supersedes the API-only qualification in my previous comment for that path.
   
   The existing flow remains `createBotIncomingMainService → BotSessionAdapter → RuntimeHostBotSessionAdapter → turn.start`: it now carries `external_connector`, the connector platform, and `BotMessageEvent.userId` as sender identity when available. Missing sender identity remains missing. These are **untrusted source metadata, not owner authentication or new user authorization**. Bot Session creation/routing, `explore` preparation, connector authentication and permissions are unchanged; no Bot Session was migrated into the personal-assistant Inbox. The separate native assistant `externalSource` support remains in place.
   
   `turn.start` and durable root-descriptor decoding now strictly admit only the existing `cloud_activation` and new `external_connector` origin shapes. Empty/extra-field origins and goal/scheduled-task/agent-graph origin forgery remain rejected. Existing generic runtime message creation marks an origin-bearing message as host-authored rather than human-authored. Root admission retains the origin; same-origin replay does not restart inference, while removing/changing connector identity on replay is rejected.
   
   **On committed tree `c59ff5a09`, using cached Node 24.20.0:** full build, workspace typecheck, lint, format, desktop-scoped Knip, strict-base renderer architecture against `d14cec57`, and epoch guard `222 → 224` all exited 0. Tests passed: **184/184** protocol + root-coordinator tests (including old cloud compatibility, missing sender, durable origin and replay checks), **11/11** real Bot producer/adapter tests, and **38/38** avatar/native-provenance/initiative boundary tests. The producer→wire decoder and decoder→real durable Host/ledger boundaries are tested separately; this is not a claim of a live vendor connector E2E run.
   
   The broader local-run failures/timeout and remaining typing-causality/filesystem-race limits reported above are unchanged; I am not claiming all local workspace tests or E2E are green. The epoch remains 224 for this unreleased PR, with its comment updated. Both pushes preserve the original `db11126c` history (`db11126c → f471bce2c → c59ff5a09`), with no force-push or merge. Please re-review the two commits together.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org