diff --git a/README.md b/README.md index 86551113..e37876cc 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [An-bot-team](plugins/antianqi/an-bot-team/) | Today's bot is one person wearing several masks, taking turns with you. An-bot-team gives you a team instead: members with different skills and temperaments, each guarding one field, and they can argue about the same question from different angles | [antianqi](https://github.com/antianqi) | | [Agent Flow](plugins/huixin615/agent-flow/) | Import this plugin's Hook event file to inspect native task calls and sub-agent lifecycles, with exact task-to-child links when IDs are available. Choose a recorded chat or the latest imported record; no Host session files are opened. Requires MiniMax Code 3.1.4 or later | [Huixin615](https://github.com/Huixin615) | | [蹬王之王 · Expiry Guardian](plugins/hylouis233/expiry-guardian/) | Track credit and reset-card expiry from a local ledger you maintain, and get a "spend the card or let the credits burn first" recommendation with the reasoning spelled out | [Hylouis](https://github.com/Hylouis233) | -| [MiniMax Pet](plugins/minimax-ai/minimax-pet/) | A lightweight companion with appearance, task and settings tabs, visible-session activity, answer-needed reminders, Markdown-rendered replies, a one-click jump to a task's conversation (3.1.11 or later) and a transparent desktop pet. Requires MiniMax Code 3.1.6 or later | [MiniMax](https://github.com/MiniMax-AI) | +| [MiniMax Pet](plugins/minimax-ai/minimax-pet/) | Desktop chats, stacked task reminders, MiniMax subscription quota and Windows delivery previews. Requires MiniMax Code 3.1.6 or later; conversation navigation requires 3.1.11 or later. | [MiniMax](https://github.com/MiniMax-AI) | | [MCP OAuth Console](plugins/microbiosis/mcp-oauth-console/) | Sign in to MCP servers that require OAuth: device-code or authorization-code + PKCE flow, the `Authorization` header written into the MCP configuration, and an opt-in refresh before expiry | [Microbiosis](https://github.com/Microbiosis) | | [本机大盘 · Local Market Board](plugins/jzlikewei/kurumi-monitor/) | Watch your own machine as a stock terminal: CPU, GPU, temperature, memory, disk, network and every running process become listed stocks with live candlesticks, moving averages, a watchlist, a leaderboard and a trade tape, on macOS and Windows. Requires minimax Code 3.1.2 or later | [jzlikewei](https://github.com/jzlikewei) | | [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 3178b68a..71390327 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -89,7 +89,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [An-bot-team 团队](plugins/antianqi/an-bot-team/) | 现在的 bot 像一个人轮流带着几个面具跟你聊天;An-bot-team 给你一支真正各有能力、各有性格的团队,还能围坐一起从不同角度讨论同一个问题 | [antianqi](https://github.com/antianqi) | | [Agent 协作透视](plugins/huixin615/agent-flow/README.zh-CN.md) | 手动导入插件 Hook 记录,查看原生 task 调用与子 Agent 运行区间;有明确 ID 时关联父子任务。可选择记录会话或一键查看最近导入的记录,不读取宿主会话文件。需要 MiniMax Code 3.1.4 或更高版本 | [Huixin615](https://github.com/Huixin615) | | [蹬王之王](plugins/hylouis233/expiry-guardian/README.md) | 看你自己维护的本地账本,算出「该用卡还是该留积分」,并把理由说清楚 | [Hylouis](https://github.com/Hylouis233) | -| [MiniMax Pet](plugins/minimax-ai/minimax-pet/README.zh-CN.md) | 提供外观/任务/设置、可见会话状态、需要回答提醒、按 Markdown 渲染的回复、一键打开任务对话(3.1.11 起)和透明桌宠;需要 MiniMax Code 3.1.6 或更高版本 | [MiniMax](https://github.com/MiniMax-AI) | +| [MiniMax Pet](plugins/minimax-ai/minimax-pet/README.zh-CN.md) | 桌面会话、叠放任务提醒、MiniMax 订阅额度和 Windows 交付物预览。需要 MiniMax Code 3.1.6 或更高版本,打开会话需要 3.1.11 或更高版本。 | [MiniMax](https://github.com/MiniMax-AI) | | [MCP OAuth 令牌台](plugins/microbiosis/mcp-oauth-console/README.zh-CN.md) | 给需要 OAuth 的 MCP 服务器完成登录:设备码或授权码 + PKCE 流程,把 `Authorization` 头写入 MCP 配置,并可选择在到期前自动续期 | [Microbiosis](https://github.com/Microbiosis) | | [本机大盘](plugins/jzlikewei/kurumi-monitor/README.zh-CN.md) | 把本机当成行情终端来看:CPU、GPU、温度、内存、磁盘、网络与每个运行中的进程都是一只个股,实时 K 线、均线、自选行情、主力动向与逐笔成交,支持 macOS 与 Windows。需要 minimax Code 3.1.2 或更高版本 | [jzlikewei](https://github.com/jzlikewei) | | [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) | diff --git a/plugins/minimax-ai/minimax-pet/.minimax-plugin/plugin.json b/plugins/minimax-ai/minimax-pet/.minimax-plugin/plugin.json index 49536175..21454997 100644 --- a/plugins/minimax-ai/minimax-pet/.minimax-plugin/plugin.json +++ b/plugins/minimax-ai/minimax-pet/.minimax-plugin/plugin.json @@ -2,8 +2,8 @@ "schemaVersion": 1, "name": "minimax-pet", "displayName": "MiniMax Pet", - "version": "0.9.5", - "description": "轻量桌宠,聚合主窗口可见会话的任务状态、需要回答的提醒和最新结果,支持外观切换及图集导入。", + "version": "0.10.0", + "description": "桌宠读取 MiniMax Code 内置会话,显示实时回复、任务进度和 MiniMax 订阅额度,支持外观切换及图集导入。", "author": "MiniMax", "icon": "icon.png", "category": "Other", diff --git a/plugins/minimax-ai/minimax-pet/PROVENANCE.md b/plugins/minimax-ai/minimax-pet/PROVENANCE.md index f6fb038c..2fcc46b4 100644 --- a/plugins/minimax-ai/minimax-pet/PROVENANCE.md +++ b/plugins/minimax-ai/minimax-pet/PROVENANCE.md @@ -1,6 +1,6 @@ # Source and distribution -Author: MiniMax ([MiniMax-AI](https://github.com/MiniMax-AI)). This is the 0.7.0 open-source edition of the MiniMax Pet MiniApp. It uses public MiniApp page APIs and contains no Host implementation. Public documentation, dependency URLs, and license notices have been prepared for this repository; private development references and acceptance records are not part of the package. +Author: MiniMax ([MiniMax-AI](https://github.com/MiniMax-AI)). This is the 0.10.0 open-source edition of the MiniMax Pet MiniApp. It uses public MiniApp page APIs and contains no Host implementation. Public documentation, dependency URLs, and license notices have been prepared for this repository; private development references and acceptance records are not part of the package. ## Layout diff --git a/plugins/minimax-ai/minimax-pet/README.md b/plugins/minimax-ai/minimax-pet/README.md index fde7f2a4..4e4a737a 100644 --- a/plugins/minimax-ai/minimax-pet/README.md +++ b/plugins/minimax-ai/minimax-pet/README.md @@ -2,93 +2,33 @@ English | [简体中文](README.zh-CN.md) -A lightweight desktop companion for MiniMax Code, by **MiniMax**. It shows visible conversation activity, answer-needed reminders and recent results without creating another chat. The interface is available in Simplified Chinese and English. +MiniMax Pet **0.10.0** is a desktop companion for MiniMax Code. Hover over the pet or focus its shortcuts to open chats, check MiniMax subscription limits, or review task activity. -## Features - -- **Appearance:** preview and select pets, import compatible pet JSON and spritesheets, and remove imported pets. -- **Tasks:** recent reminders, visible user conversations, and a scrollable latest reply rendered as Markdown. Desktop cards preview up to five lines. Clicking a card keeps the pet visible; observed `ask_user` calls show “需要你回答” (needs your answer). -- **Open the conversation:** on MiniMax Code 3.1.11 or later, a task's detail, in the panel and on the desktop, has a **打开对话** (open conversation) button, labelled **去回答** (go answer) while the task needs an answer. It brings the MiniMax Code main window forward on that conversation. Older clients do not show the button. -- **Language:** the panel and desktop copy follow the MiniMax Code interface language on 3.1.11 or later, or the system language when the client does not report one, and can be pinned in **Settings**. Older clients fall back to the system language. -- **Settings:** pet size, interface language, how long desktop cards stay, page-local reminder dismissal and mute, connection status, and reconnect. -- **Desktop window:** a draggable transparent pet with compact notification cards. Return it to the main panel to use the three tabs. -- **Theme:** on MiniMax Code 3.1.11 or later the panel and desktop cards follow the client's light or dark theme; older clients follow the system setting. - -The pet does not run Agent turns, create independent chats, write to chat inputs, comment on every session, stop tasks, or answer questionnaires. Selecting a task only reads its details; the main window switches only when you click **打开对话** or **去回答**. - -Version **0.9.0** adds two settings. **Task notifications** sets how many seconds a desktop card stays after a task finishes or fails, entered as a number and saved on the device; the default is 10 and **0** keeps the card until you close it. A card hiding never marks the task read, cards that need your answer never hide, and pointing at or focusing the cards pauses the countdown. **Language** follows the MiniMax Code interface language by default and can be pinned to 简体中文 or English; the whole panel and desktop copy switch, while conversation titles and replies stay as the Agent wrote them. - -Version **0.9.0** also gives the desktop window one fixed size, tall enough for the open card. Earlier versions grew the window when a card opened, which moved it on screen and made the pet jump for a frame; now opening or closing a card only shows or hides it. The area above the pet is transparent and passes clicks through to whatever is behind it. - -Version **0.9.2** keeps the desktop window at its intended size while dragging by sending the configured size with each move, rather than carrying forward unexpected native bounds. The desktop task card is centered and capped at 264 CSS pixels; it can still fit narrower windows with the existing 8-pixel side gutters. Permissions and dependencies are unchanged. - -Version **0.9.3** moves the desktop pet using the Host-confirmed window position and the pointer's offset from the grab point. The page waits for each move to finish before using another pointer sample. If you release while a move is pending, the window stays at the last position accepted by the Host. - -Version **0.9.5** adds “潮音 · MiniMax 老师” (Chao Yin) as an optional community pet with nine animations and 16 look directions. - -Version **0.9.4** keeps the pet reachable when you choose **放到桌面**. It tries the saved position, then fits the window to the usable area of the screen it actually lands on. A valid position on another display stays put; when the window is taller than the available area, the pet stays at the bottom rather than being hidden below the screen. - -Version **0.8.1** fixes the desktop card: the title truncates to one line, only the reply scrolls, and the actions stay pinned, so a long title or reply no longer pushes 返回任务 / 打开对话 out of the card. Expanding the card also grows the window instead of squeezing the reply into one line. - -Version **0.8.0** aligns the panel with the MiniMax Code design language: 24px page margins and section gaps, 14px/22px body copy with 12px/18px supporting text, 32px minimum control height, 12px cards and 8px controls, 0.5px borders on desktop overlays, and press/focus states. The desktop pet keeps its 280px layout with the same tokens. - -Version **0.7.0** renders each task's latest reply as Markdown: headings, emphasis, lists, task lists, fenced code, tables, quotes and links, with raw HTML shown as inert text and images as a label instead of a remote request. Notification cards and reminder previews stay plain text. Parsing uses a vendored bundle of unified, remark-parse and remark-gfm (MIT) built by `npm run build:markdown`; the page never builds an HTML string from model output. The bundle makes no network request and runs entirely in the page. - -Version **0.6.0** removes the **打招呼** (wave) and **跳一下** (jump) actions from the menu and the appearance page, and removes the original-chat draft with its voice input; the package no longer requests the microphone. It adds **打开对话** / **去回答** and the client theme. The supported baseline stays MiniMax Code 3.1.6: both additions are feature-detected and need no new access. +- **Chats:** choose a project to see its unarchived desktop chats, then read the latest reply and live activity. Continue a chat in the main window with its original tools, or send a draft to the pet's bound chat after Host confirmation. Choose **+** to compose a new draft and hand it to MiniMax Code via the clipboard. Paste and send it in the main window to create the desktop chat. +- **Tasks:** the bell opens a stack above the pet. Click the stack to expand the cards, or use the arrow on a card to open its chat. Active cards show progress such as tool activity. The stop shortcut takes you to the running chat, where you can stop it. Completed cards animate in and out and dismiss individually after five seconds. An unread completion stays in the bell count across restarts until you view its reply. +- **Deliveries:** view image thumbnails in chat and open images, Markdown, and text files in a larger preview on Windows with Microsoft Edge. Closing the preview returns you to the same chat. Other formats can be viewed in the main window. +- **Quota:** the ring shows the five-hour remaining percentage for the signed-in MiniMax account. The details show the five-hour and weekly limits. +- **Appearance:** choose a bundled pet or import an atlas. The mint robot remains the default. The five included appearances are the mint robot, MiniMax Code 章鱼娘, 麦芽糖, MMX 章鱼娘, and 潮音 · MiniMax 老师 (Chao Yin). The pet can blink and briefly follow the nearby pointer when its atlas supports these poses. Language, theme, pet size, and error-card timing are available in the panel. See [artwork and attribution](ARTWORK.md). ## Install and open -1. Copy the entire `plugins/minimax-ai/minimax-pet/` directory, including `.minimax-plugin`, into `/plugins/minimax-pet/`. The default data directory is `~/.minimax`; use your configured directory if different. The `minimax-ai` author directory is not part of the installed path. -2. Restart MiniMax Code and confirm the plugin is enabled. -3. Open “MiniMax Pet” from the MiniApp list, or ask the Agent “打开 MiniMax Pet”. -4. Choose **放到桌面** to show the desktop pet. - -To update, close the app and exit the client before replacing the complete package. Keep backups outside the client's plugins directory. Imported pets and preferences are stored separately in the Host-assigned plugin data directory. - -Earlier local prototypes use a different plugin ID. The Host gives `minimax-pet` its own data directory; importing the new package does not automatically move an older plugin's pets or preferences. Keep any existing installation/data until you have exported what you need. +1. Copy the entire `plugins/minimax-ai/minimax-pet/` folder, including `.minimax-plugin`, to `/plugins/minimax-pet/`. The default data directory is `~/.minimax`. +2. Open MiniMax Pet from MiniMax Code and choose **Put on desktop** from the pet panel. Use the appearance, task, and settings tabs in the panel to configure it. ## Tested environment -- MiniMax Code **3.1.6 or later** is the supported baseline. On 2026-10-26, the official [mainland China](https://filecdn.minimax.chat/public/minimax-agent-prod/release/latest-mac.yml) and [Global](https://file.cdn.minimax.io/public/minimax-agent-prod/release/latest-mac.yml) production update feeds both listed 3.1.6. The corresponding release implementation was checked for the required APIs. This establishes a released API baseline, not GUI acceptance of this plugin on that release. -- Task monitoring uses `agent.sessions`, `agent.session`, `agent.observe`, and `agent.cancel` with the `session.read` grant. Runtime capability and permission checks remain in place; missing APIs or disabled access are reported as unavailable. -- **打开对话** / **去回答** uses `host.navigation.open` and the theme uses `host.ui.subscribe`, both added in MiniMax Code **3.1.11**; on 2026-11-10 the macOS and Windows installers of 3.1.11 answered on both production CDNs. Both calls were checked against the MiniMax Code source: opening a conversation the Mini App already holds needs no `hostAccess` and no extra grant, must start inside a click, and brings the main window forward. -- An earlier UI version was exercised on macOS in a MiniMax Code development build: three tabs, wide/narrow layouts, task reading, real session/ask activity, import/delete, and desktop round trips. Version 0.6.0 has Node/DOM tests (including the open and theme paths against a simulated Host), an isolated HTTP smoke test, and a browser check of the panel layout outside the Host. -- The default atlas is checked by actual PNG decoding, frame coverage and deterministic rebuild tests. The separate octopus icon is checked by PNG decoding and visual review. On 2026-10-26, the packaged Skill was exercised with a real Agent in the macOS development build to create, validate, preview and import a custom v2 pet; all nine animation previews and the four cardinal mouse-look directions were checked. This does not replace released-client acceptance. -- Version 0.9.0 has Node/DOM tests for the card timer, the preference round trip and the copy of both languages (every key the page uses must exist in both), plus a browser check of the panel and desktop window in both languages against a simulated Host. Not verified for 0.9.0: the language the real client reports on any given install, and both languages inside a real MiniMax Code window. -- Version 0.9.2 was checked in MiniMax Code **3.1.19.232** on Windows 11 x64 (build 26200, 150% display scaling). With the task card open, four automated pointer drags moved the real window without cumulative width or height growth. A physical mouse and other display configurations were not tested for this fix. -- The drag behavior was exercised with a physical mouse in a local comparison build on MiniMax Inside Code **3.1.19.169**, Windows 11 (build 26300), and a 4K display. Version 0.9.3 has regression tests for input before and after the Host applies a pending move. Desktop testing of the final 0.9.3 package remains open. -- A pre-rebase build of the pop-out fix was checked in MiniMax Code **3.1.19.232** on Windows 11 x64 (build 26200, 150% display scaling). The old saved position clipped the pet at the top of the screen; the patched app brought it fully inside the work area and saved the corrected position. Secondary and disconnected displays were exercised in automated tests, not on physical displays. -- Not verified for 0.6.0: opening a conversation or following the theme inside a real MiniMax Code 3.1.11+ window (panel or desktop pet), any Windows GUI, and released-client installation or GUI acceptance on 3.1.6. Automated tests use synthetic data and do not prove those paths. +- The manifest's API baseline is MiniMax Code **3.1.6**. Chat navigation and Host theme/language detection use APIs available from **3.1.11**. Desktop selection and deliveries also depend on the current local desktop database and a Host Node runtime with `node:sqlite`. +- The 0.10.0 package was checked on Windows with Node.js 26 using synthetic session, quota, and preview data. A local precursor was exercised in the Windows desktop client. This exact version has not been reinstalled for live account or GUI acceptance. macOS and Linux floating windows were not re-tested. +- The earlier Windows drag fix and Chao Yin atlas were checked with MiniMax Code **3.1.19.232** on Windows 11 x64. Independent preview windows are available on Windows with Edge. ## Data & access -- **Conversation data:** requests only `session.read`. Reads visible user-conversation metadata, status and a selected conversation's latest reply through the public Host API. It does not read the Host database, logs, configuration, credentials or private files. Conversation state and reminders stay in page memory. -- **Observations:** one global observer aggregates visible task lifecycle events. Up to three detailed observers follow active tasks and detect new ask tool events. A completed/removed task releases its detailed slot; another task enters only after the previous subscription settles. The initial snapshot contains up to 50 recent visible conversations; observed tasks remain while the Host confirms visibility. -- **Coverage limits:** observers are tail-only. They cannot reconstruct questionnaires opened before subscribing or during a disconnect. More than three active tasks means only three receive detailed ask coverage. No observed ask does not prove no pending question. Historical idle tasks are not presented as newly completed. -- **Local files:** the Node service serves packaged assets and stores preferences and user-imported JSON/WebP/PNG spritesheets under opaque `context.dataDir`. Imports, replacement recovery and deletion are limited to that plugin data. Browser storage is used only to migrate old view preferences. -- **Rendered replies:** the latest reply is parsed as Markdown by the vendored parser and rebuilt as DOM nodes under the page's own stylesheet. Raw HTML in a reply is displayed as literal text, never executed or inserted as markup; links show their target on hover and are not opened; images are not fetched and appear as a text label. -- **Host navigation:** only when you click **打开对话** or **去回答**, the page calls `host.navigation.open({ id: 'session', sessionId, source: 'local' })` for a conversation it already lists through `session.read`. It does not declare `hostAccess` and never reads which page of MiniMax Code you are on. It writes nothing to chat inputs and sends no message. -- **Display preferences:** `host.ui.subscribe` reports the client theme and interface language; the page applies the theme and, while the language setting is **Follow MiniMax Code**, the language. Choosing 简体中文 or English overrides it. The preference is stored with the other settings in the plugin data directory. No grant is involved. -- **Network:** the plugin has no hard-coded external runtime endpoint; its own HTTP requests use its assigned loopback origin. -- **Microphone, camera and notifications:** not used and not declared. -- **Processes and Agent turns:** the Host starts one Node process. The plugin spawns no additional runtime process, launches no shell command, offers no MCP server, and never calls `agent.run`. - -## Agent Skill - -The `minimax-pet` Skill opens the app and guides the current Agent through creating custom pet artwork. It includes exact v1/v2 dimensions, animation and look layouts, alpha and metadata requirements, and a self-contained Node PNG validation tool. Files stay in the user workspace until import is confirmed; this does not add automatic Agent runs to the MiniApp. - -## Bundled artwork - -Four pets are bundled. The default is the MiniMax Pet mint robot, whose atlas can be regenerated with Node.js from the source directory. The second is “MiniMax Code 章鱼娘” (`minimax-tako`), a pink-haired octopus girl generated with MiniMax image generation and assembled into the v2 atlas, and the third is 麦芽糖 (`octopus-girl-v2`). The fourth is “MMX 章鱼娘” (`mmx-octopus`), a contributed character that ships the v1 atlas: all nine animation rows and no look directions. The purple octopus plugin icon is a separate imagegen asset and is preserved when regenerating the atlas. See [ARTWORK.md](ARTWORK.md). - -Version **0.5.10** also includes **Maiyatang (麦芽糖)**, an optional coral-pink chibi octopus girl. Select her in **外观 → 选择宠物**; the mint robot remains the default. She has all nine animation states and sixteen look poses in the existing v2 format. Her Chinese self-introduction appears under the preview. She uses the existing player timing, including the slow six-frame idle cycle, without new permissions or runtime behavior. The atlas was validated and imported through the local plugin UI on Linux; this does not establish bundled-install or desktop-window acceptance on released clients. See [ARTWORK.md](ARTWORK.md) for the AI-generation workflow and contributor license. - -## Development - -The complete editable source is at `sources/minimax-ai/minimax-pet/`. The installable package is self-contained at `plugins/minimax-ai/minimax-pet/`. See [PROVENANCE.md](PROVENANCE.md) for build and byte-comparison steps; developer notes and tests stay outside the distributed runtime payload. - -## License +- **Conversations:** `session.read` lists visible chats, reads selected replies, and observes task and tool activity. One aggregate observer watches recent chats, with up to three detailed live observers. The plugin does not run Agent turns or call tools. `message.append` hands a draft to the pet's own chat after the Host asks for confirmation. New drafts are written to the clipboard only on submission. `host.navigation.open` jumps to a known chat or project, and `host.ui.subscribe` follows theme and language. The plugin does not read the current Host page. +- **Desktop metadata and deliveries:** the Node service opens `v2/sqlite/runtime-state.sqlite` read-only under `MINIMAX_DATA_DIR`, `MINIS_MAX_DATA_DIR`, `MAVIS_DATA_DIR`, or `~/.minimax`. It uses project visibility, archive status and delivery metadata. The file layout and schema are not public Host APIs. A delivery must be indexed for a visible desktop chat, have a supported type, and resolve inside that chat's workspace. The preview serves the file locally. Markdown is rendered as DOM nodes, and reply HTML is displayed as text. +- **Quota:** the Node service looks for `auth/**/auth.json` under the configured MiniMax data root (`MINIS_MAX_DATA_DIR`, `MAVIS_DATA_DIR`, `MINIMAX_DATA_DIR`, `DATA_DIR`, or `~/.minimax`). It sends the account bearer token only to the MiniMax services at `agent.minimax.cn` and `www.minimaxi.com` to query the subscription. The page receives status, plan tier, remaining quota, and reset times. +- **Storage and processes:** preferences, imported atlases, unread session IDs, titles and short previews, read markers, and the Edge preview profile stay under `context.dataDir`. The page talks to the Node service over the Host-assigned loopback origin. Windows uses `powershell.exe -NoProfile -NonInteractive -EncodedCommand` for the bundled native drag helper, which stops with the plugin. It opens `msedge.exe` in app mode using a separate profile when you request a preview. Close the preview to close that window. +- **Devices:** the plugin uses no microphone, camera, or system notifications. -Original code, documentation, the robot, minimax-tako pet and icon: [MIT](LICENSE), Copyright 2026 MiniMax. Maiyatang artwork: MIT, Copyright 2026 Fectivnfy112357. The minimax-tako atlas was generated with MiniMax image generation. The default atlas is generated from editable geometric drawing code; the octopus icon and Maiyatang were generated with imagegen from supplied visual references. See [ARTWORK.md](ARTWORK.md). No externally sourced pet spritesheet is bundled. User-imported artwork keeps its own license. +## Development and license -`miniapp/client/vendor/markdown.mjs` bundles 59 MIT-licensed packages from the unified, remark-parse and remark-gfm dependency trees. Each package keeps its own copyright notice in `miniapp/client/vendor/markdown.LICENSE.txt`, which `npm run build:markdown` regenerates from the packages esbuild actually includes. +The `minimax-pet` Skill includes the v1/v2 atlas format and a Node.js validation tool. See [PROVENANCE.md](PROVENANCE.md) for package and development checks, [ARTWORK.md](ARTWORK.md) for artwork credits, and [LICENSE](LICENSE) for the MIT terms. diff --git a/plugins/minimax-ai/minimax-pet/README.zh-CN.md b/plugins/minimax-ai/minimax-pet/README.zh-CN.md index fcb087cb..39ca3a7a 100644 --- a/plugins/minimax-ai/minimax-pet/README.zh-CN.md +++ b/plugins/minimax-ai/minimax-pet/README.zh-CN.md @@ -2,80 +2,33 @@ [English](README.md) | 简体中文 -作者:**MiniMax**。围绕主窗口可见会话提供轻量陪伴、任务状态与通知,界面提供“外观/任务/设置”三个页签。 +MiniMax Pet **0.10.0** 是 MiniMax Code 的桌宠。鼠标移到桌宠附近或用键盘聚焦快捷栏,即可打开会话、查看 MiniMax 订阅额度或浏览任务动态。 -## 使用 +- **会话** 先选项目,再从桌面端未归档的会话中查看最新回复和实时进度。可回到主窗口继续使用原会话的工具。给与桌宠绑定的会话写草稿时,由宿主确认交接。点 **+** 可以在桌宠写新会话草稿并交给主窗口,粘贴并发送后创建桌面会话。 +- **任务** 点铃铛查看桌宠头顶的卡片叠层,再点叠层展开。运行中的卡片会显示调用工具等进度。点箭头可打开对应会话,停止快捷键会定位到主窗口的运行中会话。每条完成提醒有弹出和收起动画,显示五秒后独立收起。未查看记录会在重开桌宠后保留,查看对应回复后再消除。 +- **交付物** 会话内显示图片缩略图。Windows 安装了 Microsoft Edge 时可在独立窗口查看大图、Markdown 和文本。关掉预览即可回到刚才的会话。其他格式可以回主窗口查看。 +- **额度** 圆环展示 MiniMax 订阅五小时剩余额度,展开后同时显示五小时和每周的用量周期。 +- **外观** 支持选择内置桌宠或导入图集。内置薄荷机器人、MiniMax Code 章鱼娘、麦芽糖、MMX 章鱼娘和「潮音 · MiniMax 老师」,默认是薄荷机器人。支持相应姿势的图集可眨眼和短暂看向附近指针。面板可调整尺寸、语言、主题跟随和异常提醒时长。详见[素材及署名](ARTWORK.md)。 -将仓库 `plugins/minimax-ai/minimax-pet/` 完整复制到 `/plugins/minimax-pet/`,包括隐藏的 `.minimax-plugin`;默认 `` 为 `~/.minimax`,自定义数据目录时采用实际配置。不要复制外层作者目录。重启 MiniMax Code、确认插件启用后,从 MiniApp 列表打开“MiniMax Pet”,或对 Agent 说“打开 MiniMax Pet”。点击“放到桌面”显示透明桌宠窗口。 +## 安装和打开 -外观页支持选择、导入预览和删除已导入宠物;任务页显示提醒、全部可见任务和按 Markdown 渲染的最近回复;设置页提供大小、语言、通知时长、提醒管理和重连。 +1. 将整个 `plugins/minimax-ai/minimax-pet/` 目录(含 `.minimax-plugin`)复制到 `/plugins/minimax-pet/`。默认数据目录为 `~/.minimax`。 +2. 在 MiniMax Code 打开 MiniMax Pet,从面板选择「放到桌面」。在面板的「外观」「任务」和「设置」中配置桌宠。 -面板和桌面文案在 MiniMax Code 3.1.11 及以上跟随客户端界面语言;客户端不报告语言时跟随系统语言,也可以在设置页固定为简体中文或 English。旧版本客户端跟随系统语言。桌面通知最多预览五行,点击后可滚动读完整内容,桌宠保持可见。观察到 ask 时显示“需要你回答”。 +## 测试环境 -在 MiniMax Code 3.1.11 及以上版本,面板和桌面上的任务详情都有“打开对话”按钮,任务需要回答时显示为“去回答”;点一下会把 MiniMax Code 主窗口切到这个对话。面板和桌面卡片的明暗也跟随 MiniMax Code 的主题。旧版本客户端不显示该按钮,明暗跟随系统设置。 +- 插件清单的接口基线为 MiniMax Code **3.1.6**。会话跳转及主题、语言跟随使用 **3.1.11** 起提供的接口。桌面会话筛选和交付物依赖当前桌面数据库结构,以及带 `node:sqlite` 的宿主运行时。 +- 0.10.0 在 Windows 与 Node.js 26 上使用模拟会话、额度和预览数据验证。此版本的本地前身在 Windows 桌面端试用过。本次打包版尚未重新安装验收真实账户和桌面交互,也未重新测试 macOS 或 Linux 悬浮窗。 +- 较早的拖动修复和「潮音」图集已在 Windows 11 x64 与 MiniMax Code **3.1.19.232** 上验证。独立预览窗需要 Windows 和 Edge。 -**0.5.10** 新增可选内置宠物 **麦芽糖**,是一位珊瑚粉触手长发的 Q 版全身章鱼娘。在“外观 → 选择宠物”中选择她,预览下方会显示她的自述;薄荷色机器人仍为默认宠物。麦芽糖采用现有 v2 图集,包含九种动作和十六个视线方向,沿用六帧、6.6 秒一轮的慢速待机,不新增权限或改变播放器。图集已通过校验,并在 Linux 的本地插件界面完成导入和选择;这不代表正式客户端的 bundled 安装或透明桌面窗口已验收。AI 创作流程和贡献者许可见[素材说明](ARTWORK.md)。 +## 数据与访问 -**0.5.11** 新增可选内置宠物 **MMX 章鱼娘**,是一位橙发、白背心、棕格纹短裙的 Q 版全身章鱼娘。在“外观 → 选择宠物”中选择她即可;薄荷色机器人仍为默认宠物。她采用 v1 图集,包含九种动作,不含十六个视线方向,因此鼠标跟随对她不生效;沿用六帧、6.6 秒一轮的慢速待机,不新增权限或改变播放器。图集已通过校验。创作流程和贡献者许可见[素材说明](ARTWORK.md)。 - -**0.9.0** 新增两项设置。“任务通知”用数字框设置桌面卡片在任务完成或异常后显示多少秒,默认 10 秒,填 0 表示一直显示到手动关闭;设置保存在本机。卡片自动收起不会把任务标记为已读,需要你回答的卡片不会自动收起,鼠标悬停或焦点停留时会暂停计时。“语言”默认跟随 MiniMax Code 的界面语言,也可以固定为简体中文或 English;面板和桌面文案整体切换,对话标题和回复保持 Agent 原文。 - -**0.9.0** 把桌面窗口固定成一个尺寸,本来就放得下展开的卡片。之前点开卡片会把窗口撑高,窗口在屏幕上跟着移动,桌宠会跳一下;现在开合卡片只显示或隐藏,不动窗口。桌宠上方是透明区域,点击会穿透到底下的窗口。 - -**0.9.2** 拖拽时同时发送坐标与当前缩放对应的窗口尺寸,不再沿用宿主异常放大的尺寸。桌面任务卡居中,宽度上限为 264 CSS 像素;窗口较窄时仍会缩小并保留两侧各 8 像素的留白。权限和依赖不变。 - -**0.9.3** 根据宿主确认的窗口位置和指针相对抓取点的偏移移动桌宠。每次移动结束后,才使用新的指针事件。如果在宿主应答前松手,窗口停在宿主最后接受的位置。 - -**0.9.5** 新增社区桌宠外观「潮音 · MiniMax 老师」,可在外观设置中选用,包含 9 种动作和 16 个注视方向。 - -**0.9.4** 修复点击“放到桌面”后宠物可能落到屏幕外的问题。先尝试恢复上次的位置,再按窗口实际落在哪块屏幕校正;副屏上的合法位置不会被移回主屏。如果窗口比可用区域更高,优先让窗口底部的宠物留在屏幕上。 - -**0.8.1** 修复桌面卡片:标题单行截断,只有回复区滚动,底部操作固定在卡片内;长标题或长回复不再把「返回任务 / 打开对话」顶出卡片。展开卡片时窗口同步变高,回复不会被压成一行。 - -**0.8.0** 按 MiniMax Code 的设计语言对齐面板:24px 页边距与区块间距、14px/22px 正文与 12px/18px 辅助文字、控件最小高度 32px、卡片 12px 与控件 8px 圆角、桌面浮层 0.5px 描边,并补齐按下与焦点状态。桌面宠物保持 280px 布局,沿用同一套 token。 - -**0.7.0** 把任务最近回复按 Markdown 渲染:标题、强调、列表、任务清单、代码块、表格、引用和链接;回复里的原始 HTML 只作为文本显示,图片显示为文字标签而不发起网络请求。通知卡片和提醒预览仍为纯文本。解析使用 `npm run build:markdown` 打包的 unified + remark-parse + remark-gfm(MIT);页面不会把模型输出拼成 HTML 字符串。 - -**0.6.0** 删除了菜单和外观页里的“打招呼”“跳一下”,删除了原属聊天草稿及其语音输入,不再申请麦克风权限;新增“打开对话/去回答”和主题跟随。支持基线仍为 MiniMax Code 3.1.6:两项新功能都先检测客户端能力,不需要新增权限。 - -旧的本地原型使用不同插件 ID。`minimax-pet` 会有独立的 Host 数据目录,安装本包不会自动搬迁旧插件的宠物和偏好;需要的素材先导出,保留旧安装和数据。 - -## 环境与兼容 - -本包支持 MiniMax Code **3.1.6 及以上版本**。2026-10-26 核对的[中国大陆](https://filecdn.minimax.chat/public/minimax-agent-prod/release/latest-mac.yml)与 [Global](https://file.cdn.minimax.io/public/minimax-agent-prod/release/latest-mac.yml) 正式更新清单均为 3.1.6,并已核对同版本发行实现包含所需接口。这确认了正式发布的 API 基线,不代表本插件已在该正式客户端完成 GUI 验收。 - -任务监控使用 `agent.sessions/session/observe/cancel`,需要 `session.read` 授权。保留运行时能力和权限检查,缺少接口或关闭授权时显示不可用。“打开对话/去回答”使用 `host.navigation.open`,主题跟随使用 `host.ui.subscribe`,两者都从 MiniMax Code **3.1.11** 起提供;2026-11-10 已确认 3.1.11 的 macOS 与 Windows 安装包在两个正式 CDN 上均可下载。两项调用已对照 MiniMax Code 源码核对:打开插件已持有的会话不需要 `hostAccess` 或其他授权,必须在点击中发起,并会把主窗口带到前台。 - -更早的 UI 版本已在 macOS 开发版验收三页签、窄宽布局、真实任务与 ask、导入删除和桌面切换;0.6.0 运行 Node/DOM 测试(含模拟 Host 下的打开对话与主题路径)、隔离 HTTP smoke,并在 Host 之外用浏览器检查了面板布局。默认图集通过 PNG 解码、动画帧覆盖与确定性重建检查;独立的章鱼图标通过 PNG 解码和视觉检查。2026-10-26,已用 macOS 开发版中的真实 Agent 调用随包 Skill,完成自定义 v2 宠物的生成、校验、预览和导入,并检查九种动作预览与鼠标上/右/下/左四向注视。0.6.0 尚未在真实的 MiniMax Code 3.1.11+ 窗口(面板或桌面宠物)中验收打开对话和主题跟随,也未验收 Windows GUI、正式客户端安装或 3.1.6 正式版 GUI;合成数据测试不能证明这些路径。 - -0.9.2 已在 Windows 11 x64(构建 26200,屏幕缩放 150%)的 MiniMax Code **3.1.19.232** 中测试。任务卡展开时通过自动化指针连续拖拽四次,真实窗口发生位移,宽高未逐次累加。此修复未测试物理鼠标及其他显示配置。 - -本地对照构建已在 Windows 11(构建 26300)、4K 显示器和 MiniMax Inside Code **3.1.19.169** 下用物理鼠标测试。0.9.3 的回归测试覆盖宿主应用窗口移动前后到达的指针事件。0.9.3 正式打包版本仍待桌面验收。 - -弹出修复在本次 rebase 前已用 Windows 11 x64(构建 26200,屏幕缩放 150%)和 MiniMax Code **3.1.19.232** 测试。旧保存位置会让宠物在屏幕上沿被裁切,修复版把宠物完整移进工作区并保存校正位置。副屏及屏幕断开场景只做了自动化测试,未连接实际副屏测试。 - -## 数据与能力边界 - -只申请 `session.read`,读取 Host 对本插件可见的用户会话状态和所选会话最新回复,不直接读取 Host 数据库、日志、配置或凭据。状态和提醒只在页面内存中,关闭或静音不修改 Host 的任务或未读事实。 - -全局观察聚合可见任务,初始快照至多 50 条;本连接已观察到、Host 仍确认可见的任务会继续保留。另三个详细观察名额监听活跃会话的 ask,任务结束或移除后取消,等待旧订阅真正结束再补位。详细观察是 tail-only,不能补回订阅前或断线期间的问卷;超过三个活跃任务时,只覆盖其中三个的详细事件。没有观察到 ask 不等于没有待答问卷。 - -偏好和用户导入素材写入独立的 `context.dataDir`;导入替换有中断恢复,删除限于本插件数据。不创建独立聊天、不写入聊天输入框、不逐会话点评、不自动调用模型、不发送或停止用户会话、不代答问卷。 - -回复由随包 vendor 的解析器转为 Markdown 结构,再在页面里用 DOM 节点重建:原始 HTML 只按文本显示,不会插入页面或执行;链接只显示地址不打开;图片不请求,只显示文字标签。 - -只有在你点击“打开对话”或“去回答”时,页面才调用 `host.navigation.open({ id: 'session', sessionId, source: 'local' })`,目标是已通过 `session.read` 列出的会话。未声明 `hostAccess`,不读取你在 MiniMax Code 里停留的页面。`host.ui.subscribe` 只用来读取并应用主题,返回的语言不使用,无需授权。不使用也不声明麦克风、摄像头或系统通知。插件本身没有硬编码的外部服务地址,只使用分配的 loopback 源,不启动额外子进程或 shell。 - -## Agent Skill - -随包的 `minimax-pet` Skill 既能打开插件,也能指导当前 Agent 制作、校验和导入自定义宠物。格式文档列出 v1/v2 的精确尺寸、逐帧布局、透明背景、视线方向和 `pet.json`,并附带无外部依赖的 PNG 校验脚本。生成文件先放在用户工作区,再通过界面确认导入;MiniApp 不自行启动模型。 +- **会话** 用 `session.read` 列出可见会话,读取所选回复并监听任务及工具进度。全局监听聚合近期会话,最多同时详细监听三个任务。插件不会发起 Agent 回合或调用工具。`message.append` 经宿主确认后把草稿交给绑定的会话,新会话草稿仅在提交时写入剪贴板。`host.navigation.open` 跳转到已知会话或项目,`host.ui.subscribe` 获取主题和语言,桌宠不读取宿主当前页面。 +- **桌面数据和交付物** 在 `MINIMAX_DATA_DIR`、`MINIS_MAX_DATA_DIR`、`MAVIS_DATA_DIR` 或 `~/.minimax` 下只读打开 `v2/sqlite/runtime-state.sqlite`,检查项目是否在侧栏、会话是否归档以及交付物的索引。这个目录结构和数据表依赖客户端实现。只有可见会话中已记录、格式受支持且真实路径在会话工作区内的文件可在本地预览。回复中的 HTML 按文字显示。 +- **额度** Node 在配置的 MiniMax 数据目录(`MINIS_MAX_DATA_DIR`、`MAVIS_DATA_DIR`、`MINIMAX_DATA_DIR`、`DATA_DIR` 或 `~/.minimax`)查找 `auth/**/auth.json`,只向 MiniMax 自己的 `agent.minimax.cn` 和 `www.minimaxi.com` 发送账号令牌查询订阅。页面仅收到状态、套餐级别、剩余额度和重置时间。 +- **存储和进程** 偏好、导入图集、未读会话标识、标题和短预览、已读标记及 Edge 预览配置放在 `context.dataDir`。页面通过宿主分配的回环地址连接 Node。Windows 用 `powershell.exe -NoProfile -NonInteractive -EncodedCommand` 执行内置的拖动辅助代码,插件停止时关闭辅助进程。主动打开预览时以独立配置在 `msedge.exe` 的应用窗口中显示。 +- **设备** 不使用麦克风、摄像头和系统通知。 ## 开发与许可 -保留源码/分发双目录,构建与完整字节对比步骤见 [PROVENANCE.md](PROVENANCE.md)。原创代码、文档、两只内置宠物和图标均按 [MIT](LICENSE) 开源,作者为 MiniMax。默认的薄荷色机器人图集由可编辑的几何绘图代码生成;第二只内置宠物“MiniMax Code 章鱼娘”(`minimax-tako`)粉发、戴眼镜、酒红触手,由 MiniMax 图像生成根据用户提供的参考图绘制后拼成 v2 图集,无法用命令重新生成;紫色章鱼图标由 imagegen 根据用户提供的视觉参考生成,重新生成图集不会覆盖图标。详见[素材说明](ARTWORK.md);参考图和外部宠物图集不随包分发,用户自行导入的素材保留其各自许可。 - -`miniapp/client/vendor/markdown.mjs` 打包了 unified、remark-parse、remark-gfm 依赖树里 59 个 MIT 许可的包,各自的版权声明保留在 `miniapp/client/vendor/markdown.LICENSE.txt`,该文件由 `npm run build:markdown` 按 esbuild 实际打包的包清单生成。 - -麦芽糖素材由 Fectivnfy112357 贡献,同样采用 MIT 许可。麦芽糖通过 MiniMax 章鱼娘工坊工作流创作,使用 OpenAI imagegen 生成,再裁切、等比缩放和组装为透明图集;重新生成默认图集不会覆盖她。 - -MMX 章鱼娘素材由 antianqi 贡献,同样采用 MIT 许可。她通过本机部署的开源扩散模型出图与出视频,再由本地脚本抽帧、抠透明、落格拼成 v1 图集,无法用命令重新生成;重新生成默认图集不会覆盖她。 +随包的 `minimax-pet` Skill 包含 v1/v2 图集格式和 Node.js 校验工具。打包与检查见 [PROVENANCE.md](PROVENANCE.md),素材署名见 [ARTWORK.md](ARTWORK.md),许可见 [LICENSE](LICENSE)。 diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/activity.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/activity.mjs index c9a617dc..fc682f4d 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/activity.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/activity.mjs @@ -15,11 +15,13 @@ export function normalizeSession(raw, { detail = false } = {}) { if (detail) { if (typeof raw.error?.message === 'string') session.error = raw.error.message; if (typeof raw.lastAssistantText === 'string') session.lastAssistantText = raw.lastAssistantText; + } else if (typeof raw.workspaceDir === 'string') { + session.projectPath = raw.isDefaultWorkspace ? '' : raw.workspaceDir; } return session; } -export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, now = Date.now, makeRequestId = () => `pet-observe-${globalThis.crypto.randomUUID()}` }) { +export function createActivitySource({ agent, onChange, onSettled, refreshCatalog, allowSession = () => true, pollIntervalMs = 5000, pollingEnabled = true, now = Date.now, makeRequestId = () => `pet-observe-${globalThis.crypto.randomUUID()}` }) { let generation = 0; let sequence = 0; let detailSequence = 0; @@ -103,7 +105,7 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n async function readDetail(epoch = generation) { const id = state.selectedSessionId; const ticket = ++detailSequence; - if (!id || !current(epoch)) return; + if (!id || !current(epoch) || !allowSession(id)) return; // A background refresh of the same visible task must not replace its long // reply with a short loading placeholder, which collapses native scrollTop. // Selection changes and visibility/error paths still clear the old detail. @@ -153,7 +155,8 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n removedAt.delete(event.sessionId); const previous = rows.get(event.sessionId); const status = outcome === 'finished' ? 'idle' : outcome; - rows.set(event.sessionId, { sessionId: event.sessionId, title: typeof event.title === 'string' && event.title ? event.title.slice(0, 1000) : previous?.title || t('desk.untitled'), status, updatedAtMs: now(), liveCompleted: outcome === 'finished' }); + rows.set(event.sessionId, { ...previous, sessionId: event.sessionId, title: typeof event.title === 'string' && event.title ? event.title.slice(0, 1000) : previous?.title || t('desk.untitled'), status, updatedAtMs: now(), liveCompleted: outcome === 'finished' }); + if (event.type === 'turn.finished') onSettled?.(event); emit({}); if (state.selectedSessionId === event.sessionId) void readDetail(epoch); } @@ -205,7 +208,7 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n const [result, originRaw] = await Promise.all([agent.sessions(), agent.session().catch((error) => { if (codeOf(error) === 'session_not_found') return null; throw error; - })]); + }), refreshCatalog?.()]); if (!current(epoch)) return; if (!result || !Array.isArray(result.sessions)) throw invalid(); const incoming = result.sessions.map((raw) => normalizeSession(raw)); @@ -213,14 +216,14 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n const origin = originRaw ? normalizeSession(originRaw) : null; if (origin && !incoming.some((s) => s.sessionId === origin.sessionId)) incoming.push(origin); const incomingIds = new Set(incoming.map((row) => row.sessionId)); - const outsideIds = [...rows.keys()].filter((id) => !incomingIds.has(id) && activity.get(id)?.retainOutsideList); + const outsideIds = [...rows.keys()].filter((id) => !incomingIds.has(id) && allowSession(id) && activity.get(id)?.retainOutsideList); const outside = await readOutsideList(outsideIds, epoch); if (!current(epoch)) return; const next = new Map(); for (const row of incoming) { if ((removedAt.get(row.sessionId) ?? 0) > before) continue; const previous = rows.get(row.sessionId); - next.set(row.sessionId, eventSequence(row.sessionId) > before && previous ? previous : mergeSnapshot(row)); + next.set(row.sessionId, eventSequence(row.sessionId) > before && previous ? { ...row, ...previous } : mergeSnapshot(row)); } for (const [id, checked] of outside) { if (!rows.has(id)) continue; @@ -273,8 +276,20 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n inFlight = operation; return operation.promise; } + function syncTimer() { + clearInterval(timer); + timer = started && !disposed && pollingEnabled && pollIntervalMs > 0 + ? setInterval(() => { void refresh(); }, pollIntervalMs) : null; + } + return { - start() { if (started || disposed) return inFlight?.promise ?? Promise.resolve(); started = true; emit({}); if (pollIntervalMs > 0) timer = setInterval(() => { void refresh(); }, pollIntervalMs); return refresh(); }, + start() { if (started || disposed) return inFlight?.promise ?? Promise.resolve(); started = true; emit({}); syncTimer(); return refresh(); }, + setPollingEnabled(enabled) { + if (disposed || pollingEnabled === enabled) return; + pollingEnabled = enabled; + syncTimer(); + if (started && enabled) void refresh(); + }, refresh, selectSession(id) { if (state.availability !== 'ready' || !rows.has(id)) throw Object.assign(new Error('session_not_found'), { code: 'session_not_found' }); diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs index a4e77470..a7fa778f 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs @@ -4,13 +4,14 @@ let requestSequence = 0; const idOf = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null; const turnOf = (row) => idOf(row?.observedTurnId); -export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDelayMs = 120 }) { +export function createAskObserver({ agent, onChange, onProgress, maxSubscriptions = 3, askDelayMs = 120 }) { // The fourth Host observer slot belongs to the global lifecycle subscription. const limit = Number.isSafeInteger(maxSubscriptions) ? Math.min(3, Math.max(0, maxSubscriptions)) : 3; const delay = Number.isFinite(askDelayMs) ? Math.max(0, askDelayMs) : 120; const watches = new Map(), retiring = new Set(), failed = new Map(); - let disposed = false, ready = false, running = new Map(), selectedId = null; + let disposed = false, ready = false, running = new Map(), selectedId = null, pinned = null; let queued = false, emitted = null; + const tracked = (id) => running.get(id) || (pinned?.sessionId === id ? pinned : null); function getState() { return { @@ -60,7 +61,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (disposed || !ready) return; const desired = []; const add = (id) => { - const row = running.get(id); + const row = tracked(id); if (row && desired.length < limit && !desired.includes(id) && !failedFor(row)) desired.push(id); }; // Never evict a question just because another session became selected. @@ -72,7 +73,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe for (const watch of [...watches.values()]) if (!desired.includes(watch.id)) retire(watch); for (const id of desired) { if (watches.has(id) || watches.size + retiring.size >= limit) continue; - start(running.get(id)); + start(tracked(id)); } notify(); } @@ -89,11 +90,12 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (!turnId || watch.retiredTurns.has(turnId)) return; if (event.type === 'turn.started') { if (watch.turnId === turnId && watch.terminal) return; - enterTurn(watch, turnId); notify(); return; + enterTurn(watch, turnId); onProgress?.(event); notify(); return; } - if (!['tool.started', 'tool.finished', 'turn.finished'].includes(event.type)) return; + if (!['tool.started', 'tool.finished', 'turn.finished', 'text.delta', 'message.committed'].includes(event.type)) return; if (!watch.turnId) enterTurn(watch, turnId); if (watch.turnId !== turnId || watch.terminal) return; + onProgress?.(event); if (event.type === 'turn.finished') { watch.terminal = true; clearAsk(watch); notify(); return; } @@ -124,7 +126,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (wasCurrent) { watches.delete(watch.id); clearAsk(watch); // Do not retry a failing stream on every 5s snapshot of the same turn. - const turnIds = new Set([watch.turnId, turnOf(running.get(watch.id))].filter(Boolean)); + const turnIds = new Set([watch.turnId, turnOf(tracked(watch.id))].filter(Boolean)); failed.set(watch.id, { turnIds }); } if (!disposed) reconcile(); @@ -137,8 +139,10 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe && typeof agent?.observe === 'function' && typeof agent?.cancel === 'function'; selectedId = idOf(snapshot.selectedSessionId); running = new Map(); + pinned = null; if (nextReady) for (const row of Array.isArray(snapshot.sessions) ? snapshot.sessions : []) { if (idOf(row?.sessionId) && row.status === 'running') running.set(row.sessionId, row); + if (snapshot.trackSelected && selectedId && row?.sessionId === selectedId) pinned = row; } if (!nextReady) { ready = false; failed.clear(); @@ -147,11 +151,11 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe } ready = true; for (const [id, entry] of failed) { - const row = running.get(id), turnId = turnOf(row); + const row = tracked(id), turnId = turnOf(row); if (!row || (turnId && !entry.turnIds.has(turnId))) failed.delete(id); } for (const watch of [...watches.values()]) { - const row = running.get(watch.id); + const row = tracked(watch.id); if (!row) { retire(watch); continue; } const turnId = turnOf(row); if (turnId && !watch.retiredTurns.has(turnId)) enterTurn(watch, turnId); @@ -161,7 +165,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe getState, dispose() { if (disposed) return; - disposed = true; ready = false; running.clear(); failed.clear(); + disposed = true; ready = false; pinned = null; running.clear(); failed.clear(); for (const watch of [...watches.values()]) retire(watch); }, }; diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs new file mode 100644 index 00000000..2bf19c4a --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs @@ -0,0 +1,304 @@ +import { t } from './i18n.mjs'; +import { renderMarkdown } from './markdown.mjs'; + +export function createCompactChat({ document: doc, onSelect, onOpen, onAppend, onOpenProject, onOpenDelivery }) { + const element = (tag, className, parent) => { + const node = doc.createElement(tag); + node.className = className; + parent?.append(node); + return node; + }; + const root = element('section', 'compact-chat'); + const projectRow = element('div', 'chat-inline-project', root); + const projectLabel = element('label', '', projectRow); + projectLabel.htmlFor = 'pet-chat-project'; + const projectPicker = element('select', '', projectRow); + projectPicker.id = 'pet-chat-project'; + const selector = element('div', 'chat-sessions', root); + const picker = element('button', 'chat-picker', selector); + picker.type = 'button'; + picker.setAttribute('aria-expanded', 'false'); + picker.setAttribute('aria-controls', 'pet-chat-projects'); + const pickerLabel = element('span', 'chat-picker-label', picker); + const chevron = element('span', 'chat-picker-chevron', picker); + chevron.setAttribute('aria-hidden', 'true'); + const create = element('button', 'compact-button chat-new', selector); + create.type = 'button'; create.textContent = '+'; + const newForm = element('form', 'chat-inline-compose'); + const newInput = element('textarea', 'chat-input', newForm); + newInput.rows = 1; + newInput.maxLength = 100_000; + const handoff = element('button', 'compact-button chat-inline-send', newForm); + handoff.type = 'submit'; + handoff.textContent = '↗'; + selector.insertBefore(newForm, create); + const newHint = element('p', 'compact-hint chat-status', root); + newHint.setAttribute('role', 'status'); + const projectList = element('div', 'chat-project-list', root); + projectList.id = 'pet-chat-projects'; + projectList.hidden = true; + const content = element('div', 'chat-content', root); + const preview = element('div', 'chat-preview md', content); + const actions = element('div', 'chat-actions', content); + const open = element('button', 'compact-button chat-open', actions); + open.type = 'button'; + const form = element('form', 'chat-composer', content); + const draft = element('textarea', 'chat-input', form); + draft.rows = 1; + draft.maxLength = 100_000; + const submit = element('button', 'compact-button chat-draft-submit', form); + submit.type = 'submit'; + const status = element('p', 'compact-hint chat-status', content); + status.setAttribute('role', 'status'); + content.hidden = true; + let current = {}, busy = false, notice, optionsKey = '', replyId = '', visible = false, disposed = false; + let pickerOpen = false, rowButtons = [], rowRequest = 0, composing = false; + let projectKey, chosenProject, newNotice; + let callbacks = { select: onSelect, open: onOpen, append: onAppend }; + + function projectId() { + return chosenProject || current.projects?.find((project) => !project.path)?.id; + } + + function paintProjectPicker(projects) { + const options = projects.map((project) => ({ id: project.id, name: project.name || + project.path.replace(/[/\\]+$/u, '').split(/[/\\]/u).at(-1) || t('chat.noProject') })); + const key = JSON.stringify(options); + if (key !== projectKey) { + projectKey = key; + projectPicker.replaceChildren(...options.map(({ id, name }) => { + const option = doc.createElement('option'); option.value = id; option.textContent = name; return option; + })); + } + if (!projects.some((project) => project.id === chosenProject)) chosenProject = undefined; + projectPicker.value = projectId() || ''; + projectRow.hidden = !projects.length; + projectPicker.disabled = busy; + } + + function paintSessions(sessions, id) { + const key = JSON.stringify([t('chat.untitled'), t('chat.empty'), t('status.running'), id, sessions.map((row) => + [row.sessionId, row.title, row.status])]); + if (optionsKey === key) return; + optionsKey = key; + const focused = doc.activeElement?.dataset.sessionId; + const scroll = projectList.scrollTop; + const fragment = doc.createDocumentFragment(); + rowButtons = []; + for (const row of sessions) { + const button = element('button', 'chat-session-row', fragment); + button.type = 'button'; + button.dataset.sessionId = row.sessionId; + const title = element('span', 'chat-session-label', button); + title.textContent = row.title || t('chat.untitled'); + title.title = title.textContent; + if (row.status === 'running') { + const state = element('span', 'chat-session-running', button); + state.setAttribute('aria-label', t('status.running')); + } + if (row.sessionId === id) { + button.setAttribute('aria-current', 'true'); + const check = element('span', 'chat-session-check', button); + check.textContent = '✓'; + check.setAttribute('aria-hidden', 'true'); + } + rowButtons.push(button); + } + if (!rowButtons.length) element('p', 'chat-empty', fragment).textContent = t('chat.empty'); + projectList.replaceChildren(fragment); + projectList.scrollTop = scroll; + if (focused) rowButtons.find((button) => button.dataset.sessionId === focused)?.focus({ preventScroll: true }); + } + + function paint() { + if (!visible || disposed) return; + const { sessions = [], projects = [], availability, loading, error, originId } = current; + const ready = availability === 'ready'; + paintProjectPicker(projects); + const project = projectId(); + const matches = project ? sessions.filter((row) => row.projectId === project) : []; + const session = matches.find((row) => row.sessionId === current.id); + const id = session?.sessionId; + const detail = id ? current.detail : null; + if (!ready || composing) pickerOpen = false; + const label = session?.title || t('chat.choose'); + pickerLabel.textContent = label; + pickerLabel.title = label; + picker.dataset.selected = id || ''; + picker.setAttribute('aria-expanded', String(pickerOpen)); + projectList.hidden = !pickerOpen; + if (pickerOpen) paintSessions(matches, id); + picker.hidden = composing; + picker.disabled = !ready || busy; + selector.classList.toggle('is-composing', composing); + create.disabled = busy || !composing && (!onOpenProject || !project); + create.textContent = composing ? '‹' : '+'; + create.title = t(composing ? 'chat.inline.back' : 'chat.inline.new'); + create.setAttribute('aria-label', create.title); + newForm.hidden = !composing; + newInput.disabled = busy; + handoff.disabled = busy || !project || !newInput.value.trim(); + newHint.hidden = !composing || !newNotice?.text; + newHint.textContent = newNotice?.text || ''; + newHint.dataset.kind = newNotice?.kind || 'info'; + open.hidden = !ready || !id || !callbacks.open; + open.disabled = busy; + open.textContent = session?.needsAnswer ? t('tasks.goAnswer') : t('chat.openNative'); + const canAppend = ready && id && id === originId && callbacks.append; + form.hidden = !canAppend; + draft.disabled = busy; + submit.disabled = busy || !draft.value.trim(); + const text = id && detail?.sessionId === id ? detail.lastAssistantText : ''; + preview.hidden = !text; + if (replyId !== id) { replyId = id; preview.scrollTop = 0; } + renderMarkdown(preview, text || '', { sessionId: ready ? id : undefined, onOpenDelivery }); + const hint = notice?.text || (!ready ? t(availability === 'connecting' ? 'availability.connectingShort' : 'chat.hostUnavailable') + : error ? t('desk.replyFailed', { code: error }) + : loading && !text ? t('desk.loading') + : id && !text ? t('desk.replyEmpty') : ''); + status.textContent = hint; + status.dataset.kind = notice?.kind || (error ? 'error' : 'info'); + status.hidden = !hint; + content.hidden = composing || pickerOpen || (preview.hidden && open.hidden && form.hidden && status.hidden); + } + + function setPickerOpen(opened, focus = false) { + if (pickerOpen === opened) return; + pickerOpen = opened; + paint(); + if (pickerOpen && !doc.defaultView.matchMedia('(prefers-reduced-motion: reduce)').matches) { + projectList.animate?.([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], + { duration: 145, easing: 'ease-out' }); + } + if (focus) picker.focus({ preventScroll: true }); + } + + function selectRow(id) { + setPickerOpen(false, true); + if (id === current.id) return; + const request = ++rowRequest; + notice = null; + Promise.resolve().then(() => callbacks.select?.(id)).catch((error) => { + if (disposed || request !== rowRequest) return; + notice = { kind: 'error', text: t('chat.actionError', { code: error?.code || 'result_unknown' }) }; + paint(); + }); + } + + // Calling the bridge directly in the gesture preserves short-lived user activation. + function perform(action, value) { + if (!action || busy || disposed) return; + busy = true; notice = null; + let pending; + try { pending = action(value); } catch (error) { pending = Promise.reject(error); } + paint(); + Promise.resolve(pending).then((result) => { + notice = result; + if (action === callbacks.append && result?.kind === 'ok' && draft.value === value) draft.value = ''; + }, (error) => { + notice = { kind: 'error', text: t('chat.actionError', { code: error?.code || error?.message || 'result_unknown' }) }; + }).finally(() => { busy = false; paint(); }); + } + picker.addEventListener('click', () => setPickerOpen(!pickerOpen)); + picker.addEventListener('keydown', (event) => { + if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return; + event.preventDefault(); + setPickerOpen(true); + const target = rowButtons.find((button) => button.dataset.sessionId === current.id) || + (event.key === 'ArrowUp' ? rowButtons.at(-1) : rowButtons[0]); + target?.focus(); + }); + projectList.addEventListener('click', (event) => { + const id = event.target.closest('.chat-session-row')?.dataset.sessionId; + if (id) selectRow(id); + }); + projectList.addEventListener('keydown', (event) => { + const index = rowButtons.indexOf(doc.activeElement); + if (index < 0) return; + const target = event.key === 'Home' ? 0 : event.key === 'End' ? rowButtons.length - 1 : + event.key === 'ArrowDown' ? Math.min(rowButtons.length - 1, index + 1) : event.key === 'ArrowUp' ? Math.max(0, index - 1) : null; + if (target === null) return; + event.preventDefault(); + rowButtons[target].focus(); + }); + root.addEventListener('keydown', (event) => { + if (event.key !== 'Escape' || !pickerOpen) return; + event.preventDefault(); + event.stopPropagation(); + setPickerOpen(false, true); + }); + const outside = (event) => { + if (pickerOpen && !picker.contains(event.target) && !projectList.contains(event.target) && !projectRow.contains(event.target)) setPickerOpen(false); + }; + doc.addEventListener('pointerdown', outside); + create.addEventListener('click', () => { + setPickerOpen(false); + composing = !composing; + newNotice = null; + paint(); + (composing ? newInput : picker).focus({ preventScroll: true }); + }); + projectPicker.addEventListener('change', () => { chosenProject = projectPicker.value; newNotice = null; paint(); }); + newInput.addEventListener('input', () => { handoff.disabled = busy || !projectId() || !newInput.value.trim(); }); + newForm.addEventListener('submit', (event) => { + event.preventDefault(); + if (handoff.disabled || !composing) return; + const value = newInput.value.trim(), project = projectId(); + if (!value || !project || !onOpenProject) return; + busy = true; + let copy, navigation; + try { copy = doc.defaultView.navigator.clipboard.writeText(value); } + catch (error) { copy = Promise.reject(error); } + try { navigation = onOpenProject(project); } + catch (error) { navigation = Promise.reject(error); } + paint(); + void Promise.allSettled([copy, navigation]).then(([copied, opened]) => { + if (disposed) return; + if (opened.status === 'rejected' || opened.value?.kind !== 'ok') { + newNotice = { kind: 'error', text: opened.value?.text || t('chat.project.unavailable') }; + } else if (copied.status === 'rejected') { + newNotice = { kind: 'error', text: t('chat.project.copyFailed') }; + } else newNotice = { kind: 'info', text: t('chat.project.draftCopied') }; + busy = false; + paint(); + }); + }); + open.addEventListener('click', () => perform(callbacks.open, current.id)); + draft.addEventListener('input', () => { submit.disabled = busy || !draft.value.trim(); }); + form.addEventListener('submit', (event) => { + event.preventDefault(); + if (!form.hidden && draft.value.trim()) perform(callbacks.append, draft.value); + }); + + return { + root, + viewing(id) { return visible && !composing && !pickerOpen && current.id === id && !preview.hidden; }, + suspend() { visible = false; pickerOpen = false; }, + setVisible(value) { + const entering = value && !visible; + visible = value; + root.hidden = !value; + if (!value) pickerOpen = false; + if (entering) paint(); + }, + update(snapshot) { + if (snapshot.id !== current.id) notice = null; + current = snapshot; + paint(); + }, + translate() { + projectList.setAttribute('aria-label', t('chat.choose')); + preview.setAttribute('aria-label', t('chat.latest')); + draft.placeholder = t('chat.draft'); + draft.setAttribute('aria-label', t('chat.draft')); + submit.textContent = t('chat.append'); + projectLabel.textContent = t('chat.project.label'); + newInput.placeholder = t('chat.inline.placeholder'); + newInput.setAttribute('aria-label', newInput.placeholder); + handoff.title = t('chat.project.handoff'); + handoff.setAttribute('aria-label', handoff.title); + paint(); + }, + dispose() { disposed = true; callbacks = {}; doc.removeEventListener('pointerdown', outside); root.remove(); }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs index 9a573130..e1eb8a11 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs @@ -1,5 +1,6 @@ import { markdownToPlainText, renderMarkdown, resetMarkdown } from './markdown.mjs'; -import { t } from './i18n.mjs'; +import { getLanguage, t } from './i18n.mjs'; +import { createCompactChat } from './compact-chat.mjs'; const STATUS_KEYS = { running: 'desk.statusRunning', error: 'status.error', completed: 'status.completed', aborted: 'status.aborted', idle: 'status.idle', needs_answer: 'status.needsAnswer' }; const statusLabel = (status) => (STATUS_KEYS[status] ? t(STATUS_KEYS[status]) : t('desk.toView')); @@ -13,15 +14,50 @@ export const taskStatus = (row) => row?.needsAnswer === true ? 'needs_answer' /** Task notifications and their complete replies stay beside the pet. */ export function createCompactPetView({ - container, onClose, onSelectTask, onOpenSession, + container, getAnchor, onClose, onSelectTask, onOpenSession, onChangeView, onSelectChat, onAppendDraft, onOpenProject, onOpenDelivery, quota, }) { if (!container?.ownerDocument) throw new TypeError('A compact pet container is required.'); const doc = container.ownerDocument; const hadRootClass = container.classList.contains('compact-pet-card'); container.classList.add('compact-pet-card'); + container.hidden = true; let disposed = false, opened = false, view = 'tasks', reminders = { items: [] }; - let allSessions = null, taskSelection = {}, detailBackView = 'tasks'; + let allSessions = null, taskSelection = {}, detailBackView = 'tasks', originId = null; + let notificationSelection = null; + let chatSessions = [], projects = []; let paintedDetailId = null, openToken = 0; + let language; + let panelMotion; + const restFrame = { clipPath: 'inset(0 0 0 0 round 12px)' }; + + function reveal(show, animate = true) { + const liveStyle = panelMotion ? doc.defaultView.getComputedStyle(container) : null; + const interrupted = liveStyle && { clipPath: liveStyle.clipPath }; + panelMotion?.cancel(); + panelMotion = undefined; + container.inert = !show; + if (show) container.hidden = false; + if (!animate || !container.animate || doc.defaultView.matchMedia('(prefers-reduced-motion: reduce)').matches) { + container.hidden = !show; + return; + } + const anchor = getAnchor?.() || { width: 84, height: 42 }; + const side = Math.max(0, (container.offsetWidth - anchor.width) / 2); + const bottom = Math.max(0, container.offsetHeight - anchor.height); + const narrow = { clipPath: `inset(0 ${side}px ${bottom}px ${side}px round 12px)` }; + const wide = { clipPath: `inset(0 0 ${bottom}px 0 round 12px)`, offset: .45 }; + const frames = interrupted ? [interrupted, show ? restFrame : narrow] : + show ? [narrow, wide, restFrame] : [restFrame, wide, narrow]; + const motion = container.animate(frames, + { duration: show ? 220 : 155, easing: 'cubic-bezier(.2,.65,.25,1)', fill: 'both' }); + panelMotion = motion; + motion.onfinish = () => { + if (panelMotion !== motion) return; + panelMotion = undefined; + container.hidden = !show; + motion.cancel(); + }; + } const rows = new Map(); const setText = (node, value) => { const next = String(value ?? ''); if (node.textContent !== next) node.textContent = next; }; const element = (tag, className, text) => { @@ -38,11 +74,16 @@ export function createCompactPetView({ return node; }; const selection = () => { - const id = textOf(taskSelection.selectedSessionId); + const source = view === 'detail' && notificationSelection ? notificationSelection : taskSelection; + const id = textOf(source.selectedSessionId); return { id, - session: id && taskSelection.session?.sessionId === id ? taskSelection.session : null, - detail: id && taskSelection.detail?.sessionId === id ? taskSelection.detail : null, - available: taskSelection.availability === 'ready', + session: id && source.session?.sessionId === id ? source.session : null, + detail: id && source.detail?.sessionId === id ? source.detail : null, + available: source.availability === 'ready', + steps: source.steps || [], + loading: source.detailLoading, + error: source.detailError, + canOpenHost: source.canOpenHost !== false, }; }; const call = async (callback, ...args) => { @@ -55,9 +96,15 @@ export function createCompactPetView({ const state = element('span', 'compact-state'); state.setAttribute('role', 'status'); const closeButton = button('×', 'compact-close', () => { if (disposed) return; - api.close(); void call(onClose); + if (onClose) void call(onClose); + else api.close(); }); - header.append(state, closeButton); + const switchView = button('', 'compact-switch', () => { + const next = view === 'chat' ? 'tasks' : 'chat'; + if (onChangeView) void call(onChangeView, next); + else api.open(next); + }); + header.append(state, switchView, closeButton); const tasksPane = element('div', 'compact-tasks compact-body'); const taskList = element('ul', 'compact-task-list'); @@ -74,17 +121,18 @@ export function createCompactPetView({ // Only the reply scrolls; the title and the actions stay pinned so a long title or a // long reply can never push the buttons out of the 280px card. const detailBody = element('div', 'compact-detail-body'); + const detailSteps = element('ul', 'compact-detail-steps'); const detailReply = element('div', 'compact-detail-reply md'); detailReply.tabIndex = 0; - detailBody.append(detailReply); + detailBody.append(detailSteps, detailReply); const detailFooter = element('div', 'compact-footer'); const back = button('', 'compact-detail-back compact-link', () => api.open(detailBackView)); const openHint = element('p', 'compact-hint'); openHint.setAttribute('role', 'status'); openHint.hidden = true; const setHint = (text, kind = 'info') => { setText(openHint, text); openHint.dataset.kind = kind; openHint.hidden = !openHint.textContent; }; // The Host checks user activation, so the callback must run synchronously inside this click. const openSession = button(t('tasks.open'), 'compact-open', () => { - const { id } = selection(); - if (disposed || !id || typeof onOpenSession !== 'function') return; + const { id, canOpenHost } = selection(); + if (disposed || !id || !canOpenHost || typeof onOpenSession !== 'function') return; const token = ++openToken; openSession.disabled = true; setHint(t('desk.openHint')); void call(onOpenSession, id).then((result) => { @@ -96,7 +144,11 @@ export function createCompactPetView({ }); detailFooter.append(back, openSession); detailPane.append(detailHead, detailBody, detailFooter, openHint); - container.append(header, tasksPane, detailPane); + const chat = createCompactChat({ + document: doc, onSelect: onSelectChat, onOpen: onOpenSession, onAppend: onAppendDraft, onOpenProject, onOpenDelivery, + }); + container.append(header, tasksPane, detailPane, chat.root); + if (quota) container.append(quota.panel); function paintTasks() { const reminderItems = Array.isArray(reminders?.items) ? reminders.items : Array.isArray(reminders) ? reminders : []; @@ -134,7 +186,7 @@ export function createCompactPetView({ } function paintDetail() { - const { id, session, detail, available } = selection(); + const { id, session, detail, available, steps, loading, error, canOpenHost } = selection(); const needsAnswer = available && session?.needsAnswer === true; const status = taskStatus(session) || taskStatus(detail); setText(detailTitle, textOf(session?.title) || textOf(detail?.title) || t('desk.reply')); @@ -145,25 +197,29 @@ export function createCompactPetView({ else if (needsAnswer) text = t('status.needsAnswer'); // A background refresh keeps the matching reply mounted; a short loading // placeholder would shrink its scroll range and reset a reader's position. - else if (taskSelection.detailLoading && !detail) text = t('desk.loading'); - else if (taskSelection.detailError) text = t('desk.replyFailed', { code: failureCode(taskSelection.detailError) }); + else if (loading && !detail) text = t('desk.loading'); + else if (error) text = t('desk.replyFailed', { code: failureCode(error) }); else if (!id) text = t('desk.chooseTask'); else if (!detail) text = t('desk.loading'); else text = (detail.status === 'error' && textOf(detail.error)) || textOf(detail.lastAssistantText) || t('desk.replyEmpty'); // Status copy stays plain text; an actual reply is markdown. renderMarkdown keeps // the DOM when the text is unchanged and restores the scroll offset when a // streaming reply replaces it. - if (needsAnswer || !available || taskSelection.detailLoading && !detail) { + if (needsAnswer || !available || loading && !detail) { if (detailReply.dataset.mdSource !== text) { resetMarkdown(detailReply); setText(detailReply, text); } } else { - renderMarkdown(detailReply, text); + renderMarkdown(detailReply, text, { sessionId: available && canOpenHost ? id : undefined, onOpenDelivery }); + } + if (steps.length !== detailSteps.children.length || steps.some((label, index) => detailSteps.children[index].textContent !== label)) { + detailSteps.replaceChildren(...steps.map((label) => element('li', '', label))); } - detailPane.setAttribute('aria-busy', String(available && !needsAnswer && taskSelection.detailLoading === true)); + detailSteps.hidden = steps.length === 0; + detailPane.setAttribute('aria-busy', String(available && !needsAnswer && loading === true)); if (paintedDetailId !== id) { detailReply.scrollTop = 0; detailBody.scrollTop = 0; paintedDetailId = id; openToken++; openSession.disabled = false; setHint(''); } - openSession.hidden = typeof onOpenSession !== 'function' || !available || !id; + openSession.hidden = typeof onOpenSession !== 'function' || !available || !canOpenHost || !id; setText(openSession, needsAnswer ? t('tasks.goAnswer') : t('tasks.open')); openSession.setAttribute('aria-label', t('desk.openAria', { action: needsAnswer ? t('tasks.goAnswer') : t('tasks.open'), @@ -172,37 +228,74 @@ export function createCompactPetView({ } function paint() { - if (disposed) return; + if (disposed || !opened) return; // Labels follow the interface language, which the page resolves after this view exists. closeButton.setAttribute('aria-label', t('desk.closePanel')); detailReply.setAttribute('aria-label', t('desk.replyAria')); setText(allTasks, t('tasks.all')); setText(back, t('tasks.back')); - container.hidden = !opened; tasksPane.hidden = !['tasks', 'allTasks'].includes(view); detailPane.hidden = view !== 'detail'; - setText(state, view === 'tasks' ? t('desk.panelState.tasks') : view === 'allTasks' ? t('desk.panelState.allTasks') : t('desk.panelState.detail')); - paintTasks(); paintDetail(); + const chatting = view === 'chat'; + setText(state, chatting ? t('chat.title') : view === 'tasks' ? t('desk.panelState.tasks') : view === 'allTasks' ? t('desk.panelState.allTasks') : t('desk.panelState.detail')); + setText(switchView, chatting ? t('app.tabTasks') : t('chat.title')); + if (language !== getLanguage()) { + language = getLanguage(); + chat.translate(); + quota?.translate(); + } + if (quota) quota.panel.hidden = !chatting; + if (chatting) { + const { id, session, detail } = selection(); + const allowed = chatSessions.some((row) => row.sessionId === id); + chat.update({ sessions: chatSessions, id: allowed ? id : '', session: allowed ? session : null, detail: allowed ? detail : null, originId, projects, availability: taskSelection.availability, + loading: taskSelection.detailLoading, error: taskSelection.detailError }); + } + chat.setVisible(chatting); + if (view === 'detail') paintDetail(); + else if (!chatting) paintTasks(); } const api = { get opened() { return opened && !disposed; }, get view() { return view; }, + get progressSlot() { return header; }, + viewing(id) { + return opened && (view === 'chat' ? chat.viewing(id) : view === 'detail' && + selection().id === id && Boolean(selection().available && selection().detail)); + }, update(next = {}) { if (disposed) return; reminders = next.reminders || { items: [] }; allSessions = Array.isArray(next.allSessions) ? next.allSessions : null; + chatSessions = next.chatSessions || []; + projects = next.projects || []; taskSelection = next.taskSelection || {}; + notificationSelection = next.notificationSelection || null; + originId = next.originId || null; paint(); }, open(next = 'tasks') { - if (disposed || !['tasks', 'allTasks', 'detail'].includes(next)) return false; + if (disposed || !['tasks', 'allTasks', 'detail', 'chat'].includes(next)) return false; if (next === 'detail' && ['tasks', 'allTasks'].includes(view)) detailBackView = view; - view = next; opened = true; paint(); return true; + const entering = !opened; + view = next; + opened = true; + paint(); + if (entering) reveal(true); + return true; + }, + close({ animate = true } = {}) { + if (disposed || (!opened && (animate || container.hidden))) return; + opened = false; + // Freeze the last layout while the panel exits. Reset the picker for the next open. + chat.suspend(); + reveal(false, animate); }, - close() { if (!disposed) { opened = false; paint(); } }, dispose() { if (disposed) return; disposed = true; opened = false; + panelMotion?.cancel(); panelMotion = undefined; + chat.dispose(); for (const unbind of callbacks) unbind(); header.remove(); tasksPane.remove(); detailPane.remove(); rows.clear(); container.hidden = true; diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs new file mode 100644 index 00000000..cfc474b6 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs @@ -0,0 +1,42 @@ +export function completionRecord(raw) { + const { sessionId, turnId, title, text, updatedAtMs, viewed } = raw ?? {}; + if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || + typeof turnId !== 'string' || !turnId || turnId.length > 256 || + !Number.isSafeInteger(updatedAtMs) || updatedAtMs < 0) return null; + return { sessionId, turnId, title: typeof title === 'string' ? title.slice(0, 350) : '', + text: viewed !== true && typeof text === 'string' ? text.slice(0, 6000) : '', updatedAtMs, viewed: viewed === true }; +} + +export function createCompletionInbox({ onChange } = {}) { + const latest = new Map(); + const unread = () => [...latest.values()].filter((row) => !row.viewed); + return { + complete(row, { viewed = false } = {}) { + const record = completionRecord({ ...row, viewed }); + if (!record) return; + const current = latest.get(record.sessionId); + if (current && (current.turnId === record.turnId || current.updatedAtMs > record.updatedAtMs)) return; + latest.set(record.sessionId, record); + onChange?.({ action: 'complete', row: record }); + }, + view(sessionId, turnId) { + const row = latest.get(sessionId); + if (!row || row.viewed || turnId && row.turnId !== turnId) return undefined; + latest.set(sessionId, { ...row, text: '', viewed: true }); + onChange?.({ action: 'view', sessionId, turnId: row.turnId }); + return row; + }, + restore(records) { + for (const raw of records) { + const row = completionRecord(raw); + if (!row) continue; + const current = latest.get(row.sessionId); + if (!current || current.updatedAtMs < row.updatedAtMs || + (current.turnId === row.turnId && row.viewed && !current.viewed)) latest.set(row.sessionId, row); + } + }, + get count() { return unread().length; }, + get rows() { return unread().sort((a, b) => b.updatedAtMs - a.updatedAtMs); }, + clear() { latest.clear(); }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs new file mode 100644 index 00000000..9132cde5 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs @@ -0,0 +1,17 @@ +const rasterTypes = new Map([ + ['png', 'image/png'], ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'], + ['webp', 'image/webp'], ['gif', 'image/gif'], +]); +const textTypes = new Set([ + 'txt', 'csv', 'tsv', 'json', 'xml', 'yaml', 'yml', 'toml', 'sql', 'js', 'mjs', + 'cjs', 'ts', 'tsx', 'jsx', 'py', 'ps1', 'sh', 'java', 'html', 'css', 'log', +]); + +export function deliveryFormat(path) { + const extension = /\.([a-z0-9]+)$/iu.exec(path)?.[1].toLowerCase(); + const mime = rasterTypes.get(extension); + if (mime) return { kind: 'image', mime }; + if (['md', 'markdown'].includes(extension)) return { kind: 'markdown', mime: 'text/plain; charset=utf-8' }; + if (textTypes.has(extension)) return { kind: 'text', mime: 'text/plain; charset=utf-8' }; + return null; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html new file mode 100644 index 00000000..9ea166cb --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html @@ -0,0 +1,23 @@ + + + + + + + MiniMax Pet + + + + +
+
+

+ +
+
+

正在加载…

+
+
+
+ + diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs new file mode 100644 index 00000000..b5052967 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs @@ -0,0 +1,68 @@ +import { setLanguage, t } from './i18n.mjs'; +import { renderMarkdown } from './markdown.mjs'; + +const title = document.querySelector('h1'); +const scale = document.querySelector('.delivery-preview-scale'); +const body = document.querySelector('.delivery-preview-body'); +const status = document.querySelector('.delivery-preview-status'); +const content = document.querySelector('.delivery-preview-content'); +const previewPath = location.pathname; + +async function checkedResponse(resource) { + const response = await fetch(`${previewPath}/${resource}`); + if (!response.ok) throw new Error('preview_unavailable'); + return response; +} + +function showError() { + content.replaceChildren(); + status.textContent = t('delivery.unavailable'); + status.hidden = false; +} + +scale.addEventListener('click', () => { + const original = content.classList.toggle('is-original'); + scale.textContent = t(original ? 'delivery.fit' : 'delivery.original'); + scale.setAttribute('aria-pressed', String(original)); + body.scrollLeft = original ? (body.scrollWidth - body.clientWidth) / 2 : 0; + body.scrollTop = original ? (body.scrollHeight - body.clientHeight) / 2 : 0; +}); + +window.addEventListener('keydown', (event) => { + if (event.key === 'Escape') window.close(); +}); + +async function loadPreview() { + const { title: caption, kind, language, theme } = await (await checkedResponse('info')).json(); + setLanguage(language); + document.documentElement.lang = language; + if (theme) document.documentElement.dataset.theme = theme; + title.textContent = caption; + title.title = caption; + document.title = caption; + status.textContent = t('desk.loading'); + content.dataset.kind = kind; + if (kind === 'image') { + const image = document.createElement('img'); + image.alt = caption; + image.addEventListener('load', () => { + status.hidden = true; + scale.textContent = t('delivery.original'); + scale.hidden = false; + }, { once: true }); + image.addEventListener('error', showError, { once: true }); + content.append(image); + image.src = `${previewPath}/content`; + return; + } + const text = await (await checkedResponse('content')).text(); + status.hidden = true; + if (kind === 'markdown') renderMarkdown(content, text); + else { + const pre = document.createElement('pre'); + pre.textContent = text; + content.append(pre); + } +} + +void loadPreview().catch(showError); diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/i18n.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/i18n.mjs index 18ed5be4..ff06b44a 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/i18n.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/i18n.mjs @@ -135,11 +135,11 @@ export const MESSAGES = Object.freeze({ 'settings.languageFollows': '语言跟随 MiniMax Code(当前 {{language}})。', 'settings.languageSet': '界面语言已切换为 {{language}}。', 'settings.notice': '任务通知', - 'settings.noticeHint': '完成或异常后,桌面卡片显示多少秒后自动收起;填 0 表示一直显示,直到手动关闭。收起不会把任务标记为已读。', - 'settings.noticeField': '显示时长', + 'settings.noticeHint': '完成提醒自动显示 5 秒,收起后可从铃铛查看。异常提醒的时长可调整,填 0 表示手动关闭。', + 'settings.noticeField': '异常提醒时长', 'settings.secondsUnit': '秒', - 'settings.noticeSaved': '桌面卡片显示 {{seconds}} 秒后收起。', - 'settings.noticeNever': '桌面卡片会一直显示到手动关闭。', + 'settings.noticeSaved': '异常提醒在 {{seconds}} 秒后收起。', + 'settings.noticeNever': '异常提醒会一直显示到手动关闭。', 'settings.noticeInvalid': '请输入 0 到 {{max}} 之间的整数秒。', 'settings.reminders': '本次提醒', 'settings.remindersHint': '静音的任务可在这里恢复;重新打开桌宠后恢复默认提醒。', @@ -277,8 +277,56 @@ export const MESSAGES = Object.freeze({ 'markdown.image': '[图片{{alt}}]', 'markdown.truncated': '…(内容过长,已截断显示)', 'markdown.imageAlt': ':{{alt}}', + 'markdown.imageUnavailable': '图片暂不可用', + 'delivery.file': '交付物', + 'delivery.openImage': '查看大图:{{title}}', + 'delivery.original': '原始大小', + 'delivery.fit': '适应窗口', + 'delivery.unavailable': '暂时无法预览,请在主窗口查看交付物。', + 'delivery.windowFailed': '预览窗口未能打开,请在主窗口查看交付物。', // Common + 'chat.title': '会话', + 'chat.choose': '选择会话', + 'chat.noProject': '未选择项目', + 'chat.empty': '暂无可选会话', + 'chat.untitled': '未命名会话', + 'chat.inline.new': '编写桌面会话草稿', + 'chat.inline.back': '返回会话列表', + 'chat.inline.placeholder': '开始新聊天…', + 'chat.project.label': '项目', + 'chat.project.handoff': '复制草稿并打开主窗口', + 'chat.project.draftCopied': '草稿已复制,请在桌面端新建并粘贴发送。', + 'chat.project.copyFailed': '自动复制失败,请手动复制这条草稿。', + 'chat.project.unavailable': '暂时无法打开桌面会话入口。', + 'live.unreadCount': '{{count}} 个已完成会话未查看', + 'chat.openNative': '在主窗口继续', + 'chat.latest': '最新一条回复', + 'chat.draft': '给此会话写草稿', + 'chat.append': '交给主窗口', + 'chat.draftAdded': '草稿已交给主窗口,请在那里发送。', + 'chat.draftUnknown': '请先检查主窗口里的草稿。', + 'chat.hostUnavailable': '宿主会话暂不可用', + 'chat.actionError': '操作失败({{code}})', + 'chat.quota.label': 'MiniMax 订阅额度', + 'live.show': '会话进度', + 'live.expandTasks': '展开 {{count}} 个会话', + 'live.jumpTask': '跳转到会话:{{title}}', + 'live.stopInHost': '在主窗口停止任务:{{title}}', + 'live.command.working': '正在执行命令', + 'live.command.done': '已执行命令', + 'live.command.error': '命令执行失败', + 'live.tool.working': '正在调用 {{name}}', + 'live.tool.done': '已执行 {{name}}', + 'live.tool.error': '{{name}} 执行失败', + 'chat.quota.interval': '5 小时', + 'chat.quota.weekly': '本周', + 'chat.quota.loading': '读取额度…', + 'chat.quota.signedOut': '额度需登录', + 'chat.quota.unavailable': '无可显示的额度', + 'chat.quota.error': '额度暂不可用', + 'chat.quota.stale': '待刷新', + 'chat.quota.reset': '{{date}} 重置', 'common.ok': '知道了', 'common.cancelled': '已取消', }, @@ -405,11 +453,11 @@ export const MESSAGES = Object.freeze({ 'settings.languageFollows': 'Language follows MiniMax Code (currently {{language}}).', 'settings.languageSet': 'Interface language set to {{language}}.', 'settings.notice': 'Task notifications', - 'settings.noticeHint': 'How long a desktop card stays after a task finishes or fails. Use 0 to keep it until you close it. Hiding a card does not mark the task as read.', - 'settings.noticeField': 'Show for', + 'settings.noticeHint': 'Completion notices tuck away after 5 seconds and remain in the bell. Set an error notice duration of 0 to keep errors until dismissed.', + 'settings.noticeField': 'Error notice duration', 'settings.secondsUnit': 'sec', - 'settings.noticeSaved': 'Desktop cards hide after {{seconds}} seconds.', - 'settings.noticeNever': 'Desktop cards stay until you close them.', + 'settings.noticeSaved': 'Error notices hide after {{seconds}} seconds.', + 'settings.noticeNever': 'Error notices stay until dismissed.', 'settings.noticeInvalid': 'Enter a whole number of seconds from 0 to {{max}}.', 'settings.reminders': 'This session’s reminders', 'settings.remindersHint': 'Restore muted tasks here; reopening the pet restores the default reminders.', @@ -543,7 +591,55 @@ export const MESSAGES = Object.freeze({ 'markdown.image': '[Image{{alt}}]', 'markdown.truncated': '… (too long; truncated)', 'markdown.imageAlt': ': {{alt}}', + 'markdown.imageUnavailable': 'Image unavailable', + 'delivery.file': 'Deliverable', + 'delivery.openImage': 'View full image: {{title}}', + 'delivery.original': 'Actual size', + 'delivery.fit': 'Fit to window', + 'delivery.unavailable': 'Preview unavailable. Open the deliverable in the main window.', + 'delivery.windowFailed': 'Couldn’t open the preview window. Open the deliverable in the main window.', + 'chat.title': 'Chat', + 'chat.choose': 'Choose a chat', + 'chat.noProject': 'No project', + 'chat.empty': 'No chats available', + 'chat.untitled': 'Untitled chat', + 'chat.inline.new': 'Draft a desktop chat', + 'chat.inline.back': 'Back to chats', + 'chat.inline.placeholder': 'Start a new chat…', + 'chat.project.label': 'Project', + 'chat.project.handoff': 'Copy draft and open the main window', + 'chat.project.draftCopied': 'Draft copied. Start a desktop chat, then paste and send.', + 'chat.project.copyFailed': 'Copying failed. You can copy the draft manually.', + 'chat.project.unavailable': 'Unable to open the desktop chat view.', + 'live.unreadCount': '{{count}} completed chats to review', + 'chat.openNative': 'Continue in MiniMax Code', + 'chat.latest': 'Latest reply', + 'chat.draft': 'Draft for this chat', + 'chat.append': 'Hand off draft', + 'chat.draftAdded': 'Draft added. Send it from MiniMax Code.', + 'chat.draftUnknown': 'Check the draft in MiniMax Code first.', + 'chat.hostUnavailable': 'Desktop chats are unavailable', + 'chat.actionError': 'Request failed ({{code}})', + 'chat.quota.label': 'MiniMax subscription quota', + 'live.show': 'Show chat progress', + 'live.expandTasks': 'Expand {{count}} chats', + 'live.jumpTask': 'Go to chat: {{title}}', + 'live.stopInHost': 'Stop in the main window: {{title}}', + 'live.command.working': 'Running command', + 'live.command.done': 'Command executed', + 'live.command.error': 'Command failed', + 'live.tool.working': 'Using {{name}}', + 'live.tool.done': 'Finished {{name}}', + 'live.tool.error': '{{name}} failed', + 'chat.quota.interval': '5 hours', + 'chat.quota.weekly': 'Weekly', + 'chat.quota.loading': 'Loading quota…', + 'chat.quota.signedOut': 'Sign in for quota', + 'chat.quota.unavailable': 'No quota available', + 'chat.quota.error': 'Quota unavailable', + 'chat.quota.stale': 'Updating', + 'chat.quota.reset': 'Resets {{date}}', 'common.ok': 'OK', 'common.cancelled': 'Cancelled', }, diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/index.html b/plugins/minimax-ai/minimax-pet/miniapp/client/index.html index 416c7f92..a3b64f59 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/index.html +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/index.html @@ -181,7 +181,7 @@

任务连接

版本与帮助
-

MiniMax Pet 0.9.4

+

MiniMax Pet 0.10.0

@@ -201,19 +201,31 @@

任务连接

diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs new file mode 100644 index 00000000..0aa56603 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs @@ -0,0 +1,106 @@ +import { t } from './i18n.mjs'; +import { createCompletionInbox } from './completion-inbox.mjs'; + +const textOf = (value) => typeof value === 'string' ? value : ''; +const commandTool = /(?:^|[_.:-])(?:bash|shell|terminal|powershell|command|exec|runshellcommand|run_shell_command|run_command|execute_command)(?:$|[_.:-])/i; +const MAX_TEXT = 24_000; +const joinText = (committed, delta) => [committed, delta].filter(Boolean).join('\n\n'); + +function toolLabel(event) { + const action = event.type === 'tool.started' ? 'working' : event.ok ? 'done' : 'error'; + return commandTool.test(event.name) ? t(`live.command.${action}`) : t(`live.tool.${action}`, { name: event.name }); +} + +export function createLiveProgress({ button, onChange, isVisibleSession }) { + const badge = button.querySelector('.desk-bell-badge'); + const conversations = new Map(); + let writes = Promise.resolve(); + const inbox = createCompletionInbox({ onChange(change) { + writes = writes.catch(() => {}).then(async () => { + const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(change), keepalive: true }; + for (let attempt = 0; attempt < 3; attempt++) { + try { + if ((await fetch('/api/completions', options)).ok) return; + } catch { /* Retry a transient connection failure below. */ } + await new Promise((resolve) => setTimeout(resolve, 200 * (attempt + 1))); + } + console.warn('[pet] completion_store_write_failed'); + }); + } }); + let running = false, active = false, disposed = false, timer = null; + const unread = () => inbox.rows.filter((row) => isVisibleSession(row.sessionId)); + + function paint() { + if (disposed) return; + const count = unread().length; + button.hidden = !active || (!count && !running); + button.title = count ? t('live.unreadCount', { count }) : t('live.show'); + button.setAttribute('aria-label', button.title); + badge.hidden = count === 0; + badge.textContent = count > 99 ? '99+' : String(count); + } + function schedule() { + if (disposed) return; + paint(); + if (timer === null) timer = setTimeout(() => { timer = null; if (!disposed) onChange?.(); }, 85); + } + + function receive(event) { + if (disposed || !event?.sessionId || !event.turnId) return; + if (!['turn.started', 'turn.finished', 'tool.started', 'tool.finished', 'text.delta', 'message.committed'].includes(event.type)) return; + let progress = conversations.get(event.sessionId); + if (!progress || progress.turnId !== event.turnId) { + progress = { turnId: event.turnId, steps: [], committed: '', delta: '' }; + conversations.delete(event.sessionId); + conversations.set(event.sessionId, progress); + if (conversations.size > 4) conversations.delete(conversations.keys().next().value); + } + if (event.type === 'text.delta') progress.delta = (progress.delta + textOf(event.text)).slice(-MAX_TEXT); + else if (event.type === 'message.committed') { + progress.committed = joinText(progress.committed, textOf(event.text)).slice(-MAX_TEXT); + progress.delta = ''; + } else if (event.type === 'tool.started' || event.type === 'tool.finished') { + const name = textOf(event.name).slice(0, 120); + if (!name) return; + const previous = progress.steps.at(-1); + if (event.type === 'tool.finished' && previous?.type === 'tool.started' && previous.name === name) progress.steps.pop(); + progress.steps.push({ type: event.type, name, ok: event.ok === true }); + if (progress.steps.length > 6) progress.steps.shift(); + } else if (event.type === 'turn.finished') { + if (textOf(event.text)) { progress.committed = event.text.slice(-MAX_TEXT); progress.delta = ''; } + } + if (timer === null) timer = setTimeout(() => { timer = null; if (!disposed) onChange?.(); }, 85); + } + + async function refresh() { + try { + const response = await fetch('/api/completions', { cache: 'no-store' }); + if (!response.ok) return; + const { records } = await response.json(); + if (!disposed && Array.isArray(records)) { inbox.restore(records); schedule(); } + } catch { /* The in-memory inbox can still receive new completions. */ } + } + + void refresh(); + return { + receive, refresh, + get unread() { return unread(); }, + progress(sessionId) { + const progress = conversations.get(sessionId); + return progress && { turnId: progress.turnId, text: joinText(progress.committed, progress.delta), steps: progress.steps.map(toolLabel) }; + }, + complete(row, viewed = false) { + const progress = conversations.get(row.sessionId); + inbox.complete({ ...row, text: row.text || (progress ? joinText(progress.committed, progress.delta) : '') }, { viewed }); + schedule(); + }, + viewed(sessionId, turnId) { if (inbox.view(sessionId, turnId)) schedule(); }, + update(hasRunning, show) { + running = hasRunning; active = show; + paint(); + }, + clear() { conversations.clear(); schedule(); }, + translate: paint, + dispose() { disposed = true; clearTimeout(timer); conversations.clear(); inbox.clear(); }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/markdown.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/markdown.mjs index cb2f1771..ba00aefb 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/markdown.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/markdown.mjs @@ -4,6 +4,7 @@ // createTextNode, so model output can never inject markup. import { parseMarkdown } from './vendor/markdown.mjs'; import { t } from './i18n.mjs'; +import { deliveryFormat } from './delivery-formats.mjs'; // A reply is at most a few thousand characters in practice. Keep a ceiling so one // pathological response cannot stall the page, and bound the parse cache. @@ -119,7 +120,83 @@ function appendInline(doc, parent, children) { // Block nodes // --------------------------------------------------------------------------- -function blockNode(doc, node) { +function deliveryItems(value) { + const block = /^\s*\s*([\s\S]*?)<\/deliver-assets>\s*$/iu.exec(value); + if (!block) return []; + const items = []; + for (const [, attributes] of block[1].matchAll(/]|"[^"]*"|'[^']*')*)\/>/giu)) { + const fields = new Map(); + for (const [, name, double, single] of attributes.matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gu)) { + fields.set(name.toLowerCase(), double ?? single); + } + const path = fields.get('src') || ''; + const name = path.split(/[/\\]/u).at(-1) || ''; + const caption = (fields.get('caption') || '').trim(); + const nodeId = fields.get('node_id') || ''; + const kind = deliveryFormat(path)?.kind || (fields.get('type')?.toLowerCase() === 'image' && nodeId ? 'image' : ''); + items.push({ path, name, caption, nodeId, kind }); + } + return items; +} + +function imageLabel(caption) { + return t('markdown.image', { alt: caption ? t('markdown.imageAlt', { alt: caption }) : '' }); +} + +function renderDeliveries(doc, items, { sessionId, onOpenDelivery }) { + const group = doc.createElement('div'); + group.className = 'md-delivery'; + for (const { nodeId, name, path, caption, kind } of items) { + const title = caption || name || (kind === 'image' ? imageLabel('') : t('delivery.file')); + const params = new URLSearchParams({ session: sessionId || '' }); + if (kind === 'image' && /^[\w-]{1,128}$/u.test(nodeId)) params.set('node', nodeId); + else if (path) params.set('file', path); + const url = '/api/session-asset?' + params; + const previewable = Boolean(kind && sessionId && onOpenDelivery && (params.has('node') || params.has('file'))); + const open = () => onOpenDelivery({ asset: Object.fromEntries(params), title }); + if (kind === 'image' && previewable) { + const figure = doc.createElement('figure'); + const label = doc.createElement('figcaption'); + label.textContent = title; + const button = doc.createElement('button'); + button.type = 'button'; + button.className = 'md-delivery-thumbnail'; + button.setAttribute('aria-label', t('delivery.openImage', { title })); + button.addEventListener('click', open); + const image = doc.createElement('img'); + image.alt = title; + image.loading = 'lazy'; + image.decoding = 'async'; + image.addEventListener('error', () => { + button.remove(); + label.append(doc.createTextNode(` · ${t('markdown.imageUnavailable')}`)); + }, { once: true }); + image.src = url; + button.append(image); + figure.append(button, label); + group.append(figure); + continue; + } + const file = doc.createElement(previewable ? 'button' : 'div'); + file.className = 'md-delivery-file'; + if (previewable) { + file.type = 'button'; + file.addEventListener('click', open); + } + const label = doc.createElement('span'); + label.textContent = title; + file.append(label); + if (name && name !== title) { + const filename = doc.createElement('small'); + filename.textContent = name; + file.append(filename); + } + group.append(file); + } + return group; +} + +function blockNode(doc, node, context) { switch (node.type) { case 'paragraph': { const p = doc.createElement('p'); @@ -150,7 +227,7 @@ function blockNode(doc, node) { li.classList.add('md-task'); li.dataset.checked = String(item.checked); } - appendBlocks(doc, li, item.children, { tight: !item.spread }); + appendBlocks(doc, li, item.children, { tight: !item.spread, context }); list.append(li); } return list; @@ -167,7 +244,7 @@ function blockNode(doc, node) { case 'blockquote': { const quote = doc.createElement('blockquote'); quote.className = 'md-quote'; - appendBlocks(doc, quote, node.children, {}); + appendBlocks(doc, quote, node.children, { context }); return quote; } case 'thematicBreak': { @@ -201,8 +278,9 @@ function blockNode(doc, node) { return wrap; } case 'html': { - // Raw HTML is shown as its literal source, never parsed: the author meant it - // to be a block, so dropping it silently would hide half the reply. + const items = deliveryItems(node.value); + if (items.length) return renderDeliveries(doc, items, context); + // Other HTML stays literal text. const p = doc.createElement('p'); p.className = 'md-p md-raw'; p.textContent = typeof node.value === 'string' ? node.value : ''; @@ -217,7 +295,7 @@ function blockNode(doc, node) { // degrade to their text rather than disappearing. const container = doc.createElement('div'); container.className = 'md-block'; - appendBlocks(doc, container, node.children, {}); + appendBlocks(doc, container, node.children, { context }); if (!container.childNodes.length) container.textContent = inlineText(node); return container; } @@ -246,10 +324,10 @@ function tableRow(doc, row, cellTag, align = []) { return tr; } -function appendBlocks(doc, parent, children, { tight = false } = {}) { +function appendBlocks(doc, parent, children, { tight = false, context } = {}) { for (const child of Array.isArray(children) ? children : []) { if (!child || child.type === 'footnoteDefinition') continue; - const node = blockNode(doc, child); + const node = blockNode(doc, child, context); // A list item that holds only paragraphs becomes plain inline content when the // list is tight, matching how markdown renders without paragraph spacing. if (tight && child.type === 'paragraph' && node.classList?.contains('md-p')) { @@ -271,15 +349,15 @@ function appendBlocks(doc, parent, children, { tight = false } = {}) { * A reply that is still streaming changes on every poll, so the reader's scroll * position is captured and restored around the replace. */ -export function renderMarkdown(target, text) { +export function renderMarkdown(target, text, context = {}) { const source = typeof text === 'string' ? text : ''; - const key = sourceKey(source); + const key = `${context.sessionId || ''}:${sourceKey(source)}`; if (target.dataset.mdSource === key) return false; const doc = target.ownerDocument; const fragment = doc.createDocumentFragment(); for (const child of tree(source).children) { if (!child || child.type === 'footnoteDefinition') continue; - const node = blockNode(doc, child); + const node = blockNode(doc, child, context); if (node) fragment.append(node); } const keepTop = target.scrollTop; @@ -332,8 +410,11 @@ function blockText(node, depth = 0) { return typeof node.value === 'string' ? node.value : ''; case 'thematicBreak': return '—'; - case 'html': - return typeof node.value === 'string' ? node.value : ''; + case 'html': { + const items = deliveryItems(node.value); + return items.length ? items.map(({ kind, caption, name }) => kind === 'image' + ? imageLabel(caption || name) : caption || name || t('delivery.file')).join(' · ') : typeof node.value === 'string' ? node.value : ''; + } case 'list': { const items = Array.isArray(node.children) ? node.children : []; return items.map((item, index) => { diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-app.js b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-app.js index f65d3d74..5eae5376 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-app.js +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-app.js @@ -2,9 +2,11 @@ import { STATUS_ANIM, createActivitySource } from './activity.mjs'; import { DEFAULT_PREFERENCES, MAX_NOTICE_TIMEOUT_SECONDS, loadPreferences, preferenceRequest } from './preferences.mjs'; import { restoreWindowPosition, fitWindowToScreen } from './window-position.mjs'; -import { aggregateText, notificationItems, noticeRemaining, notificationText, visibleNotices, createAnimationGate } from './pet-presentation.mjs'; +import { aggregateText, notificationItems, noticeKey, noticeRemaining, notificationText, visibleNotices, createAnimationGate } from './pet-presentation.mjs'; import { createReminderStore } from './activity-reminders.mjs'; import { createCompactPetView, taskStatus } from './compact-pet-view.mjs'; +import { createPetQuota } from './pet-quota.mjs'; +import { createLiveProgress } from './live-progress.mjs'; import { createNotificationPreviews } from './notification-previews.mjs'; import { createAskObserver } from './ask-observer.mjs'; import { createPanelNavigation } from './panel-navigation.mjs'; @@ -36,6 +38,11 @@ const THUMB_SCALE = 0.375; const DRAG_THRESHOLD = 4; const DIRECTION_HYSTERESIS = 12; const LOOK_DEAD_ZONE = 1; +const LOOK_MARGIN = 12; +const WINDOWS_DESKTOP = /^win/i.test(navigator.userAgentData?.platform ?? navigator.platform ?? ''); +let desktopDragWarm; +let desktopDragReady = false; +let deskPointerFrame = null; // --------------------------------------------------------------------------- // Small helpers @@ -79,6 +86,7 @@ const params = new URLSearchParams(location.search); const host = window.mcode?.miniapp ?? null; const win = host?.window ?? null; const agent = host?.agent ?? null; +const hostMessage = host?.message ?? null; const hostNavigation = host?.host?.navigation ?? null; const canOpenSession = typeof hostNavigation?.open === 'function'; const explicitDemo = params.get('demo') === '1'; @@ -144,19 +152,17 @@ const app = { ctFailures: 0, pointer: null, drag: null, - dragMove: null, dragging: false, menuOpen: false, menuView: 'root', menuAnchor: { x: 0, y: 0 }, menuCloseTimer: null, - quickbarTimer: null, transient: null, transientTimer: null, - bubbleSessionId: null, oneShot: false, oneShotToken: 0, looking: false, + workbenchNodded: false, }; const importState = { @@ -246,23 +252,47 @@ const els = { bubbleTitle: $('bubble-title'), bubbleText: $('bubble-text'), notificationStack: $('notification-stack'), + noticeList: $('pet-notice-list'), quickbar: $('quickbar'), - quickTasks: $('quick-tasks'), - quickMenu: $('quick-menu'), + quickChat: $('quick-chat'), + quickQuota: $('quick-quota'), + quotaRing: $('quick-quota-ring'), + quickBell: $('quick-bell'), menu: $('menu'), }; let animationGate = null; let workbenchView = null; +let previewBlurDeadline = 0; +let bellView = ''; +let petNod; +let shortcutHideTimer; +let shortcutSize = { width: 84, height: 42 }; +let completionSequence = 0; +let desktopCatalog; + +async function refreshDesktopCatalog() { + try { + const response = await fetch('/api/desktop-catalog', { cache: 'no-store' }); + if (!response.ok) throw new Error('desktop_catalog_unavailable'); + const { sessions, projects } = await response.json(); + const bySession = new Map(); + const firstSession = new Map(); + for (const row of sessions) { + bySession.set(row.id, row.projectId); + if (!firstSession.has(row.projectId)) firstSession.set(row.projectId, row.id); + } + desktopCatalog = { bySession, firstSession, projects }; + } catch { desktopCatalog = undefined; } +} +let petQuota = null; +let liveProgress = null; +let notificationTask = null; const reminders = createReminderStore(); -// The desktop window is one fixed size that already fits the open card. Toggling the card -// by resizing the native window moves its origin and repaints the old layout at the new -// top-left, so the pet visibly jumped up (and left, while the card was wider). Keeping the -// geometry constant removes that class of flicker entirely; the area above the pet is -// transparent and forwards clicks. +// Keep room for the panel below the pet and task notifications above it. +// Both panels open inside the existing bounds without moving the sprite. const DESK_WIDTH = 280; -const deskHeight = (scale) => Math.max(380, Math.ceil(208 * scale) + 332); -// Saved positions are the top-left a 280x340 window would have had, so they keep working -// after the window grows: the bottom edge is what must stay fixed on screen. +const deskHeight = (scale) => Math.ceil(208 * scale) + 422; +// Positions use the bottom-right anchor of the native window. const LEGACY_DESK_HEIGHT = 340; const savedTopLeft = (position, height) => ({ x: position.x, y: position.y + LEGACY_DESK_HEIGHT - height }); let notificationPreviews = null; @@ -316,13 +346,39 @@ function availabilityText() { } function applyActivity() { - renderActivityUI(); - renderBubble(); - renderMenuIfOpen(); - if (!app.pet || app.oneShot || app.dragging) return; + renderVisibleActivity(); + if (!app.pet || app.dragging || petNod) return; + if (app.workbenchOpen && !app.workbenchNodded && player.supportsLook && !reducedMotion.matches && !document.hidden) { + app.oneShotToken++; + app.oneShot = false; + player.look(180); + app.looking = app.workbenchNodded = true; + petNod = els.sprite.animate([{ transform: 'none' }, { transform: 'translateY(2px) scaleY(.985)', offset: .55 }, + { transform: 'none' }], { duration: 175, easing: 'ease-out' }); + petNod.onfinish = () => { + petNod = undefined; + applyActivity(); + }; + return; + } + if (app.oneShot) return; const desired = desiredAnimation(); - if (!['idle', 'running', 'waving'].includes(desired.state)) stopLook(); animationGate?.apply(desired.state, desired.key, { loop: app.source === 'demo' }); + followPointer(); +} + +function renderVisibleActivity() { + if (document.hidden) return; + if (app.mode === 'window') { + renderDeskShortcuts(); + renderSpriteActivityLabel(); + syncNotificationPreviews(); + renderBubble(); + renderMenuIfOpen(); + if (app.workbenchOpen) renderCompactView(); + } else { + renderActivityUI(); + } } function playOneShot(state) { @@ -344,10 +400,27 @@ async function initActivitySource() { if (disposed) return; syncObservedAsks(); applyActivity(); + }, onProgress: (event) => { + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.receive(event); } }); disposers.push(() => askObserver.dispose()); activitySource = createActivitySource({ agent, + refreshCatalog: refreshDesktopCatalog, + allowSession: (id) => Boolean(desktopCatalog?.bySession.has(id)), + onSettled: (event) => { + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.receive(event); + if (event.status === 'finished') { + const row = app.sessions.find((item) => item.sessionId === event.sessionId); + const completion = { sessionId: event.sessionId, turnId: event.turnId || row?.observedTurnId || `observed-${++completionSequence}`, + title: event.title || row?.title, text: typeof event.text === 'string' ? event.text : '', updatedAtMs: Date.now() }; + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.complete(completion); + else void refreshDesktopCatalog().then(() => { + if (!disposed && desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.complete(completion); + }); + } + }, + pollingEnabled: !document.hidden, onChange(snapshot) { Object.assign(app, { availability: snapshot.availability, sessionsError: snapshot.error, @@ -355,22 +428,40 @@ async function initActivitySource() { selectedSessionId: snapshot.selectedSessionId, detail: snapshot.detail, detailLoading: snapshot.detailLoading, detailError: snapshot.detailError, }); - askObserver.update({ availability: snapshot.availability, sessions: snapshot.sessions, selectedSessionId: snapshot.selectedSessionId }); + if (snapshot.availability === 'not_permitted') liveProgress?.clear(); + syncAskWatches(); syncObservedAsks(); - renderHeader(); + if (app.mode !== 'window' && !document.hidden) renderHeader(); applyActivity(); }, }); disposers.push(() => activitySource.dispose()); + listen(document, 'visibilitychange', () => { + activitySource.setPollingEnabled(!document.hidden); + petQuota?.setActive(app.mode === 'window' && !document.hidden); + if (document.hidden) stopNoticeTimer(); + else { + void liveProgress?.refresh(); + if (app.mode !== 'window') renderHeader(); + applyActivity(); + } + }); void activitySource.start(); } function syncObservedAsks() { const ids = new Set(askObserver?.getState().needsAnswerIds ?? []); - app.sessions = app.rawSessions.map((row) => ({ ...row, needsAnswer: row.status === 'running' && ids.has(row.sessionId) })); + app.sessions = app.rawSessions.filter((row) => desktopCatalog?.bySession.has(row.sessionId)) + .map((row) => ({ ...row, needsAnswer: row.status === 'running' && ids.has(row.sessionId) })); reminders.update(app.sessions); } +function syncAskWatches() { + const eligible = app.rawSessions.filter((row) => desktopCatalog?.bySession.has(row.sessionId)); + askObserver?.update({ availability: app.availability, sessions: eligible, trackSelected: app.mode === 'window', + selectedSessionId: app.selectedSessionId || eligible.find((row) => row.status === 'running')?.sessionId }); +} + function setDemoStatus(status) { if (!Object.hasOwn(STATUS_ANIM, status)) return; app.demoStatus = status; @@ -440,21 +531,40 @@ function describeOpenError(code) { /** Must be called synchronously from a click or key handler: the Host checks user activation. */ function openSessionInHost(sessionId) { + return openInHost({ id: 'session', sessionId, source: 'local' }); +} + +function openInHost(target) { if (!canOpenSession) return Promise.resolve({ kind: 'error', text: t('tasks.openNoApi') }); - return callBridge(() => hostNavigation.open({ id: 'session', sessionId, source: 'local' })).then( + return callBridge(() => hostNavigation.open(target)).then( (result) => { - if (result?.status === 'opened') return { kind: 'ok', text: t('tasks.openOpened') }; + if (result?.status === 'opened') return { kind: 'ok', text: target.id === 'session' ? t('tasks.openOpened') : '' }; if (result?.reason === 'user_cancelled') return { kind: 'info', text: t('tasks.openCancelled') }; return { kind: 'info', text: t('tasks.openSuperseded') }; }, (error) => { const code = errCode(error); - console.warn('[pet] open_session_failed:', code, error); + console.warn('[pet] open_host_target_failed:', code, error); return { kind: 'error', text: describeOpenError(code) }; }, ); } +function appendDraftToHost(text) { + if (app.availability !== 'ready' || !app.selectedSessionId || app.selectedSessionId !== app.originSession?.sessionId) { + return { kind: 'error', text: t('tasks.openTargetUnavailable') }; + } + return callBridge(() => hostMessage.append(text)).then( + () => ({ kind: 'ok', text: t('chat.draftAdded') }), + (error) => { + const code = errCode(error); + if (code === 'user_cancelled') return { kind: 'info', text: t('common.cancelled') }; + if (code === 'result_unknown') return { kind: 'error', text: t('chat.draftUnknown') }; + return { kind: 'error', text: t('chat.actionError', { code }) }; + }, + ); +} + function openSelectedSession() { const sessionId = app.selectedSessionId; if (!sessionId) return; @@ -479,6 +589,8 @@ function applyLanguage(tag) { root.lang = next; applyStaticText(); document.title = t('app.title'); + petQuota?.translate(); + liveProgress?.translate(); renderAll(); renderNoticeTimeout(); return next; @@ -621,7 +733,7 @@ function onWindowState(state) { }); return; } - if (!app.restoringPosition) rememberPosition(); + if (!app.restoringPosition && !app.dragging) rememberPosition(); } if (state.mode !== app.mode) applyMode(state.mode); } @@ -644,10 +756,15 @@ function applyMode(mode) { const leavingWindow = app.mode === 'window' && mode !== 'window'; if (leavingWindow) { app.hovered = false; animationGate?.invalidate(); } app.mode = mode; + bellView = ''; + previewBlurDeadline = 0; + notificationTask = null; + syncAskWatches(); app.workbenchOpen = false; + app.workbenchNodded = false; app.compacting = false; app.workbenchRevision++; - workbenchView?.close(); + workbenchView?.close({ animate: false }); root.classList.remove('workbench-open'); if (mode !== 'window') { app.positionRestoreToken++; app.restoringPosition = false; app.awaitingPointer = false; } root.classList.toggle('mode-window', mode === 'window'); @@ -657,15 +774,16 @@ function applyMode(mode) { els.desk.hidden = mode !== 'window'; closeMenu(); - hideQuickbar(); cancelDrag(); stopLook(); + renderDeskShortcuts(); app.pointer = null; clearForwardingWatchdog(); app.ctSafeHold = false; if (leavingWindow) app.clickThrough = null; if (mode === 'window') { + warmDesktopDrag(); els.deskPetSlot.append(els.sprite); els.sprite.tabIndex = 0; els.sprite.setAttribute('role', 'button'); @@ -742,7 +860,7 @@ function isOverPet(x, y) { function isOverOverlay(x, y) { return [els.bubble, els.notificationStack, els.quickbar, els.menu, els.workbench].some( - (el) => !el.hidden && pointInRect(el.getBoundingClientRect(), x, y), + (el) => !el.hidden && !el.inert && pointInRect(el.getBoundingClientRect(), x, y), ); } @@ -755,7 +873,7 @@ function refreshInteractivity() { const interactive = app.dragging || app.menuOpen || - (p ? isOverPet(p.x, p.y) || isOverOverlay(p.x, p.y) : app.workbenchOpen); + (p ? isOverPet(p.x, p.y) || isOverOverlay(p.x, p.y) : app.workbenchOpen || Boolean(bellView)); setClickThrough(!interactive); } @@ -838,20 +956,35 @@ function onDocumentMouseMove(e) { if (app.restoringPosition) return; app.awaitingPointer = false; noteForwardedMove(e); - if (!app.dragging && !insideDesk(e.clientX, e.clientY)) { - onPointerLeave(); + if (app.dragging) { + app.pointer = { x: e.clientX, y: e.clientY }; return; } app.pointer = { x: e.clientX, y: e.clientY }; - refreshInteractivity(); - trackMenuHover(e.clientX, e.clientY); - updateLook(e.clientX, e.clientY); + if (deskPointerFrame !== null) return; + deskPointerFrame = requestAnimationFrame(() => { + deskPointerFrame = null; + const point = app.pointer; + if (disposed || app.mode !== 'window' || app.dragging || !point) return; + if (!insideDesk(point.x, point.y)) { + onPointerLeave(); + return; + } + syncQuickbar(); + refreshInteractivity(); + trackMenuHover(point.x, point.y); + followPointer(); + }); } function onPointerLeave() { if (app.mode !== 'window') return; + if (deskPointerFrame !== null) cancelAnimationFrame(deskPointerFrame); + deskPointerFrame = null; app.pointer = null; - stopLook(); + app.hovered = false; + syncQuickbar(); + followPointer(); refreshInteractivity(); // stays interactive while menu/drag force it if (app.menuOpen) armMenuClose(); } @@ -860,25 +993,26 @@ function onPointerLeave() { // Look direction (v2) + idle liveliness // --------------------------------------------------------------------------- -function updateLook(x, y) { - if (!app.pet || !player.supportsLook) return; +function followPointer() { + if (petNod || !app.pet || !player.supportsLook) return; + const point = app.pointer; if ( + !point || app.mode !== 'window' || - app.hovered || app.dragging || app.menuOpen || app.oneShot || - app.workbenchOpen || reducedMotion.matches || - !['idle', 'running', 'waving'].includes(activityAnim()) + document.hidden ) { stopLook(); return; } const r = els.sprite.getBoundingClientRect(); - const dx = x - (r.left + r.width / 2); - const dy = y - (r.top + r.height / 2); - if (Math.hypot(dx, dy) <= LOOK_DEAD_ZONE) { + const dx = point.x - (r.left + r.width / 2); + const dy = point.y - (r.top + r.height / 2); + if (Math.abs(dx) > r.width / 2 + LOOK_MARGIN || Math.abs(dy) > r.height / 2 + LOOK_MARGIN || + Math.hypot(dx, dy) <= LOOK_DEAD_ZONE) { stopLook(); return; } @@ -889,6 +1023,8 @@ function updateLook(x, y) { } function stopLook() { + petNod?.cancel(); + petNod = undefined; if (!app.looking) return; app.looking = false; player?.look(null); @@ -902,6 +1038,26 @@ function noteInteraction() { // Dragging // --------------------------------------------------------------------------- +async function requestDesktopDrag(action, offset = {}) { + try { + const response = await fetch('/api/desktop-drag', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ action, ...offset }), + keepalive: action === 'stop', + }); + return response.ok && (await response.json()).ok === true; + } catch { + return false; + } +} + +function warmDesktopDrag() { + if (!WINDOWS_DESKTOP || desktopDragReady || desktopDragWarm) return; + desktopDragWarm = requestDesktopDrag('warm').then((ready) => { desktopDragReady = ready; }) + .finally(() => { desktopDragWarm = null; }); +} + function onSpritePointerDown(e) { if (app.mode !== 'window' || app.restoringPosition || app.scaleChanging || e.button !== 0 || !app.pet) return; noteInteraction(); @@ -912,7 +1068,7 @@ function onSpritePointerDown(e) { } catch (error) { console.warn('[pet] pointer_capture_failed:', errCode(error), error); } - const startX = app.winPos?.x ?? e.clientX; + const startX = e.screenX; app.drag = { pointerId: e.pointerId, grabX: e.clientX, @@ -926,10 +1082,7 @@ function onSpritePointerDown(e) { function onSpritePointerMove(e) { const d = app.drag; - // While the Host is moving the window, client coordinates may be relative to either origin. - // Resume from the next pointer event after the Host confirms the new bounds. - if (!d || e.pointerId !== d.pointerId || app.scaleChanging || app.dragMove) return; - const origin = app.winPos; + if (!d || e.pointerId !== d.pointerId || app.scaleChanging) return; const dx = e.clientX - d.grabX; const dy = e.clientY - d.grabY; if (!d.active) { @@ -939,25 +1092,17 @@ function onSpritePointerMove(e) { app.oneShotToken++; app.oneShot = false; stopLook(); - hideQuickbar(); + renderDeskShortcuts(); els.sprite.classList.add('is-dragging'); refreshInteractivity(); - if (!origin) console.warn('[pet] drag_without_window_position: no window position yet, animation only'); - } - const x = origin ? Math.round(origin.x + dx) : e.clientX; - updateDragDirection(d, x); - if (!origin) return; - const y = Math.round(origin.y + dy); - if (x === origin.x && y === origin.y) return; - // On Windows a position-only update can return enlarged native bounds. Send the - // design size with the move, rather than carrying the enlarged bounds into the next one. - app.dragMove = callBridge(() => win.update({ x, y, width: DESK_WIDTH, height: deskHeight(prefs.scale) })).then((state) => { - if (app.mode === 'window') onWindowState(state); - }).catch((error) => { - const code = errCode(error); - if (code === 'not_permitted') console.debug('[pet] drag_move_rejected: not_permitted (target is off every display)'); - else console.warn('[pet] drag_move_failed:', code, error); - }).finally(() => { app.dragMove = null; }); + const limit = (offset) => Math.max(-512, Math.min(512, Math.round(offset))); + void requestDesktopDrag('drag', { dx: limit(dx), dy: limit(dy) }).then((started) => { + if (!started && app.drag === d && !disposed && app.mode === 'window') { + showTransient(t('mode.positionFailed', { code: 'desktop_drag_unavailable' }), 'error'); + } + }); + } + updateDragDirection(d, e.screenX); } function updateDragDirection(d, sx) { @@ -986,7 +1131,8 @@ function updateDragDirection(d, sx) { function finishDrag(e, cancelled) { const d = app.drag; if (!d || e.pointerId !== d.pointerId) return; - if (!cancelled && d.active) onSpritePointerMove(e); + if (cancelled && d.active) void requestDesktopDrag('stop'); + else if (d.active) onSpritePointerMove(e); app.drag = null; try { if (els.sprite.hasPointerCapture(e.pointerId)) els.sprite.releasePointerCapture(e.pointerId); @@ -996,22 +1142,25 @@ function finishDrag(e, cancelled) { els.sprite.classList.remove('is-dragging'); if (d.active) { app.dragging = false; - if (cancelled || desiredAnimation().state === 'jumping') { + renderDeskShortcuts(); + if (app.workbenchOpen || cancelled || desiredAnimation().state === 'jumping') { // Hover already owns the same three-cycle jump; release must not queue it twice. animationGate?.invalidate(); applyActivity(); } else playOneShot('jumping'); - if (!app.dragMove) callBridge(() => win.getState()).then(onWindowState, logError('get_state_after_drag')); + callBridge(() => win.getState()).then(onWindowState, logError('get_state_after_drag')); } else if (!cancelled) { - void openWorkbench('tasks'); + void openWorkbench('chat'); } refreshInteractivity(); } function cancelDrag() { - if (!app.drag && !app.dragging) return; + if (!app.drag && !app.dragging) return undefined; + const stopped = app.drag?.active ? requestDesktopDrag('stop') : undefined; app.drag = null; app.dragging = false; els.sprite.classList.remove('is-dragging'); + return stopped; } // --------------------------------------------------------------------------- @@ -1034,15 +1183,12 @@ function renderBubble() { renderNotificationStack(); if (app.workbenchOpen) { els.bubble.hidden = true; - app.bubbleSessionId = null; refreshInteractivity(); return; } - const a = activity(); let title = ''; let text = ''; let kind = 'info'; - let clickable = false; if (app.transient) { ({ text, kind } = app.transient); } else if (!app.pet && app.loadError) { @@ -1051,30 +1197,20 @@ function renderBubble() { } else if (app.source === 'real' && app.availability !== 'ready') { text = availabilityText(); kind = app.availability === 'connecting' ? 'info' : 'error'; - } else { - if (a.session) { - text = a.session.needsAnswer ? t('status.needsAnswer') : a.status === 'running' ? '' : statusText(a.status); - title = a.session.title; - clickable = !!text; - } - } if (app.source === 'demo') { title = t('tasks.demoTitle'); text = statusText(app.demoStatus) ? t('tasks.demoStatus', { status: statusText(app.demoStatus) }) : ''; - clickable = false; } els.bubbleTitle.textContent = title; els.bubbleTitle.hidden = !title; els.bubbleText.textContent = text; els.bubble.dataset.kind = kind; - els.bubble.classList.toggle('is-clickable', clickable); els.bubble.tabIndex = text ? 0 : -1; els.bubble.setAttribute('aria-label', text ? (title ? t('desk.bubbleAriaTitle', { title, text }) : t('desk.bubbleAria', { text })) : t('desk.bubbleIdle')); els.bubble.hidden = !text || (!app.transient && !els.notificationStack.hidden); - app.bubbleSessionId = clickable && a.session ? a.session.sessionId : null; refreshInteractivity(); } @@ -1083,96 +1219,273 @@ function stopNoticeTimer() { noticeTimer = null; } -function armNoticeTimer(shown) { +function armNoticeTimer(shown, options) { stopNoticeTimer(); - if (!(prefs.noticeTimeout > 0) || noticePaused || !shown.length) return; let next = Infinity; for (const item of shown) { - const remaining = noticeRemaining(item, { shownAt: noticeShownAt, now: Date.now(), timeoutSeconds: prefs.noticeTimeout }); + if (noticePaused && item.displayStatus !== 'completed') continue; + const remaining = noticeRemaining(item, options); if (remaining !== null) next = Math.min(next, remaining); } if (!Number.isFinite(next)) return; noticeTimer = setTimeout(() => { noticeTimer = null; renderBubble(); - }, Math.max(250, next + 50)); + }, Math.max(16, next)); } function pauseNotices(paused) { if (paused === noticePaused) return; const now = Date.now(); noticePaused = paused; - if (paused) { noticePauseAt = now; return; } - // Shift every card's start by the paused span so the remaining time is exact. - const pausedMs = now - noticePauseAt; - noticePauseAt = 0; - if (pausedMs > 0) for (const [id, since] of noticeShownAt) noticeShownAt.set(id, since + pausedMs); + if (paused) noticePauseAt = now; + else { + for (const item of notificationItems(reminders.getState().items)) { + const key = noticeKey(item); + const since = noticeShownAt.get(key); + if (item.displayStatus !== 'completed' && Number.isFinite(since)) { + noticeShownAt.set(key, since + Math.max(0, now - Math.max(noticePauseAt, since))); + } + } + noticePauseAt = 0; + } renderBubble(); } -function renderNotificationStack() { - const container = els.notificationStack; - const all = notificationItems(reminders.getState().items); - const now = Date.now(); - // Records the moment a card first appeared; a card that stays hidden by the - // workbench keeps its original start instead of restarting on every paint. - for (const item of all) if (!noticeShownAt.has(item.sessionId)) noticeShownAt.set(item.sessionId, now); - for (const id of [...noticeShownAt.keys()]) if (!all.some((item) => item.sessionId === id)) noticeShownAt.delete(id); - const items = visibleNotices(all, { shownAt: noticeShownAt, now, timeoutSeconds: prefs.noticeTimeout }); - const visible = app.mode === 'window' && app.availability === 'ready' && items.length - && !app.workbenchOpen && !app.transient; - container.hidden = !visible; - // Keep a timer running only while cards can actually expire on screen. - if (visible) armNoticeTimer(items); else stopNoticeTimer(); - if (!visible) return; +function bellTasks() { + const running = app.sessions.filter((row) => row.status === 'running') + .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true) || b.updatedAtMs - a.updatedAtMs); + const runningIds = new Set(running.map((row) => row.sessionId)); + const finished = (liveProgress?.unread ?? []).filter((row) => !runningIds.has(row.sessionId)); + const included = new Set([...runningIds, ...finished.map((row) => row.sessionId)]); const previews = notificationPreviews?.getState().previews ?? {}; - const existing = new Map([...container.children].map((node) => [node.dataset.sessionId, node])); - const nodes = items.map((item) => { - let node = existing.get(item.sessionId); - if (!node) { - node = document.createElement('div'); node.className = 'pet-notice'; node.dataset.sessionId = item.sessionId; - const open = document.createElement('button'); open.type = 'button'; open.className = 'pet-notice-open'; - const title = document.createElement('strong'), preview = document.createElement('span'); preview.className = 'pet-notice-preview'; - open.append(title, preview); - open.addEventListener('click', () => { openTaskPreview(node.dataset.sessionId); }); - const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.className = 'pet-notice-dismiss'; dismiss.textContent = '×'; - dismiss.addEventListener('click', () => { reminders.dismiss(node.dataset.sessionId); applyActivity(); }); - node.append(open, dismiss); + const errors = reminders.getState().items.filter((row) => row.displayStatus === 'error' && !included.has(row.sessionId)); + return [ + ...running.map((row) => { + const progress = liveProgress?.progress(row.sessionId); + const preview = row.needsAnswer ? t('status.needsAnswer') + : progress?.steps.at(-1) || progress?.text || t('status.runningText'); + return { ...row, displayStatus: 'running', preview }; + }), + ...finished.map((row) => ({ ...row, displayStatus: 'completed', preview: row.text || t('desk.noticeCompleted') })), + ...errors.map((row) => ({ ...row, preview: notificationText(row, previews) })), + ]; +} + +function closeBellStack() { + if (!bellView) return false; + bellView = ''; + syncQuickbar(); + renderBubble(); + return true; +} + +function openNoticeInHost(id, toStop = false) { + if (app.availability !== 'ready' || !desktopCatalog?.bySession.has(id)) return; + if (toStop && !app.sessions.some((row) => row.sessionId === id && row.status === 'running')) return; + const completion = !toStop && liveProgress?.unread.find((row) => row.sessionId === id); + void openSessionInHost(id).then((result) => { + if (disposed) return; + if (result.kind === 'error') { + showTransient(result.text, 'error'); + return; } - const open = node.children[0]; - open.children[0].textContent = item.title; - // A notification shows a five-line preview, so markdown is flattened, not rendered. - open.children[1].textContent = markdownToPlainText(notificationText(item, previews)); - open.setAttribute('aria-label', t('desk.noticeView', { title: item.title })); - node.children[1].setAttribute('aria-label', t('desk.noticeClose', { title: item.title })); - return node; + if (result.kind !== 'ok' || !completion) return; + const native = app.sessions.find((row) => row.sessionId === id); + if (native?.liveCompleted && (!native.observedTurnId || native.observedTurnId === completion.turnId)) reminders.dismiss(id); + liveProgress?.viewed(id, completion.turnId); + applyActivity(); }); - if (nodes.length !== container.children.length || nodes.some((node, i) => node !== container.children[i])) container.replaceChildren(...nodes); } -function toggleQuickbar() { - if (els.quickbar.hidden) showQuickbar(); - else hideQuickbar(); -} -function showQuickbar() { - if (app.mode !== 'window') return; - els.quickbar.hidden = false; - armQuickbarHide(); - refreshInteractivity(); +function createNoticeCard(id) { + const node = document.createElement('div'); + node.className = 'pet-notice'; + node.dataset.sessionId = id; + node.setAttribute('role', 'listitem'); + const open = document.createElement('button'); + open.type = 'button'; + open.className = 'pet-notice-open'; + const title = document.createElement('strong'); + const preview = document.createElement('span'); + preview.className = 'pet-notice-preview'; + open.append(title, preview); + open.addEventListener('click', () => { + if (node.dataset.expand === 'true') { + bellView = 'expanded'; + syncQuickbar(); + renderBubble(); + els.noticeList.querySelector('.pet-notice-open')?.focus({ preventScroll: true }); + } else openTaskPreview(id); + }); + const actions = document.createElement('span'); + actions.className = 'pet-notice-actions'; + const button = (className, text, action) => { + const element = document.createElement('button'); + element.type = 'button'; + element.className = className; + element.textContent = text; + element.addEventListener('click', action); + actions.append(element); + }; + button('pet-notice-action pet-notice-jump', '↵', () => openNoticeInHost(id)); + button('pet-notice-action pet-notice-stop', '■', () => openNoticeInHost(id, true)); + button('pet-notice-dismiss', '×', () => { reminders.dismiss(id); applyActivity(); }); + const count = document.createElement('span'); + count.className = 'pet-stack-count'; + count.setAttribute('aria-hidden', 'true'); + actions.append(count); + node.append(open, actions); + return node; +} + +function animateNotice(node, leaving) { + const resting = { opacity: 1, transform: 'translateY(0) scale(1)' }; + const tucked = { opacity: 0, transform: 'translateY(9px) scale(.94)' }; + return node.animate(leaving ? [resting, tucked] : [tucked, resting], + { duration: leaving ? 155 : 190, easing: leaving ? 'ease-in' : 'ease-out', fill: leaving ? 'forwards' : 'none' }); +} + +function syncNoticeCards(nodes, animate) { + const list = els.noticeList; + const wanted = new Set(nodes); + for (const node of [...list.children]) { + if (wanted.has(node)) continue; + if (!animate || node.dataset.automatic !== 'true') { node.remove(); continue; } + if (node.dataset.leaving === 'true') continue; + node.dataset.leaving = 'true'; + node.inert = true; + node.getAnimations().forEach((animation) => animation.cancel()); + animateNotice(node, true).onfinish = () => { + node.remove(); + if (!disposed) renderBubble(); + }; + } + nodes.forEach((node, index) => { + const entering = node.parentElement !== list; + if (node.dataset.leaving === 'true') { + node.getAnimations().forEach((animation) => animation.cancel()); + delete node.dataset.leaving; + } + if (list.children[index] !== node) list.insertBefore(node, list.children[index] || null); + if (animate && entering) animateNotice(node, false); + }); } -function hideQuickbar() { - clearTimeout(app.quickbarTimer); - if (els.quickbar.hidden) return; - els.quickbar.hidden = true; - refreshInteractivity(); + +function layoutExpandedNotices(count) { + const expanded = count > 0; + els.desk.classList.toggle('show-all-notices', expanded); + if (!expanded) return; + const lower = app.workbenchOpen ? Math.max(100, Math.min(els.workbench.offsetHeight, 220)) : 48; + const available = Math.max(40, els.desk.clientHeight - els.sprite.offsetHeight - lower - 24); + const columns = Math.ceil(count / Math.max(1, Math.floor(available / 41))); + els.desk.style.setProperty('--notice-lower-reserve', `${lower}px`); + els.noticeList.style.setProperty('--notice-columns', String(columns)); } -function armQuickbarHide() { - clearTimeout(app.quickbarTimer); - app.quickbarTimer = setTimeout(() => { - const p = app.pointer; - if (p && pointInRect(els.quickbar.getBoundingClientRect(), p.x, p.y)) armQuickbarHide(); - else hideQuickbar(); - }, 6000); + +function renderNotificationStack() { + const container = els.notificationStack; + const list = els.noticeList; + const all = notificationItems(reminders.getState().items); + const now = Date.now(); + const ready = app.mode === 'window' && app.availability === 'ready' && !app.transient; + const tasks = bellView ? bellTasks() : []; + if (!tasks.length) bellView = ''; + const manual = Boolean(bellView); + const keys = new Set(all.map(noticeKey)); + for (const key of noticeShownAt.keys()) if (!keys.has(key)) noticeShownAt.delete(key); + if (ready) for (const key of keys) if (!noticeShownAt.has(key)) noticeShownAt.set(key, now); + const timing = { shownAt: noticeShownAt, now, timeoutSeconds: prefs.noticeTimeout, pausedAt: noticePauseAt }; + const items = !ready ? [] : manual ? tasks : visibleNotices(all, timing); + const expanded = manual && bellView === 'expanded'; + const stacked = !expanded && items.length > 1; + const animate = ready && !manual && !reducedMotion.matches; + container.classList.toggle('is-manual', manual); + container.classList.toggle('is-expanded', expanded); + if (ready && !manual) armNoticeTimer(items, timing); else stopNoticeTimer(); + const previews = notificationPreviews?.getState().previews ?? {}; + const existing = new Map([...list.children].map((node) => [node.dataset.noticeKey, node])); + const nodes = (stacked ? items.slice(0, 3) : items).map((item, index) => { + const key = manual ? item.sessionId : noticeKey(item); + const node = existing.get(key) || createNoticeCard(item.sessionId); + const [open, actions] = node.children; + const [jump, stop, dismiss, count] = actions.children; + const title = item.title || t('chat.untitled'); + const expand = stacked && index === 0; + node.dataset.noticeKey = key; + node.dataset.automatic = String(!manual); + node.dataset.layer = String(stacked ? index : 0); + node.dataset.expand = String(expand); + node.inert = stacked && index > 0; + node.dataset.status = item.displayStatus; + open.children[0].textContent = title; + open.children[1].textContent = markdownToPlainText(manual ? item.preview : notificationText(item, previews)); + open.setAttribute('aria-label', expand ? t('live.expandTasks', { count: items.length }) : t('desk.noticeView', { title })); + count.hidden = !expand; + count.textContent = expand ? String(items.length) : ''; + jump.hidden = stacked || !canOpenSession; + jump.title = t('live.jumpTask', { title }); + jump.setAttribute('aria-label', jump.title); + stop.hidden = stacked || !canOpenSession || item.displayStatus !== 'running'; + stop.title = t('live.stopInHost', { title }); + stop.setAttribute('aria-label', stop.title); + dismiss.hidden = stacked || manual; + dismiss.setAttribute('aria-label', t('desk.noticeClose', { title })); + return node; + }); + syncNoticeCards(nodes, animate); + container.classList.toggle('is-stacked', stacked || (!expanded && list.children.length > 1)); + const visible = ready && list.children.length > 0; + container.hidden = !visible; + if (!visible && noticePaused) queueMicrotask(() => { if (!disposed && container.hidden) pauseNotices(false); }); + els.quickBell.setAttribute('aria-expanded', String(visible && manual)); + layoutExpandedNotices(visible && expanded ? items.length : 0); +} + +function renderDeskShortcuts() { + const desktop = app.mode === 'window'; + const available = desktop && !app.dragging && !app.menuOpen; + const expanded = app.workbenchOpen && !els.workbench.hidden; + const bellParent = expanded ? workbenchView?.progressSlot : els.quickbar; + if (bellParent && els.quickBell.parentElement !== bellParent) { + if (expanded) bellParent.insertBefore(els.quickBell, bellParent.lastElementChild); + else bellParent.append(els.quickBell); + } + petQuota?.setActive(desktop && !document.hidden); + liveProgress?.update(app.sessions.some((row) => row.status === 'running') || + reminders.getState().items.some((row) => row.displayStatus === 'error'), available); + syncQuickbar(); +} + +function syncQuickbar(hideNow = false) { + const available = app.mode === 'window' && !app.workbenchOpen && !app.dragging && !app.menuOpen; + if (!available) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = true; + return; + } + const pointer = app.pointer; + const focus = document.activeElement; + const buttonFocused = focus?.matches(':focus-visible') && (els.quickbar.contains(focus) || focus === els.sprite); + const overPet = pointer && isOverPet(pointer.x, pointer.y); + let overShortcuts = false; + if (pointer && !els.quickbar.hidden) { + const rect = els.quickbar.getBoundingClientRect(); + const sprite = els.sprite.getBoundingClientRect(); + overShortcuts = pointer.x >= rect.left - 4 && pointer.x <= rect.right + 4 && + pointer.y >= sprite.bottom - 22 && pointer.y <= rect.bottom + 3; + } + if (bellView || app.hovered || overPet || overShortcuts || buttonFocused) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = false; + return; + } + if (hideNow) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = true; + } else if (!els.quickbar.hidden && shortcutHideTimer === undefined) { + shortcutHideTimer = setTimeout(() => { shortcutHideTimer = undefined; syncQuickbar(true); refreshInteractivity(); }, 210); + } } // --------------------------------------------------------------------------- @@ -1335,10 +1648,10 @@ function positionMenu() { function openMenu(x, y) { if (app.mode !== 'window') return; noteInteraction(); - hideQuickbar(); stopLook(); disarmMenuClose(); app.menuOpen = true; + renderDeskShortcuts(); app.menuView = 'root'; app.menuAnchor = { x, y }; renderMenu(0); @@ -1347,6 +1660,7 @@ function openMenu(x, y) { function closeMenu({ restoreFocus = false } = {}) { if (!app.menuOpen) return; app.menuOpen = false; + renderDeskShortcuts(); disarmMenuClose(); els.menu.hidden = true; els.menu.replaceChildren(); @@ -1534,10 +1848,10 @@ function setScale(value) { const intent = ++scaleIntent; // Geometry stays with the size setting until its bounds and preference agree. app.scaleChanging = true; - cancelDrag(); + const stopped = cancelDrag(); const current = () => !disposed && intent === scaleIntent; scaleUpdates = scaleUpdates.then(async () => { - if (app.dragMove) await app.dragMove; + if (stopped) await stopped; if (!current()) return; if (app.workbenchOpen) await closeWorkbench(); if (!current()) return; @@ -1824,12 +2138,11 @@ async function confirmImport() { function renderAll() { renderHeader(); - renderActivityUI(); + renderVisibleActivity(); renderScale(); renderNoticeTimeout(); renderLanguage(); renderGallery(); - renderBubble(); } function renderHeader() { @@ -1880,6 +2193,10 @@ function renderActivityUI() { const text = real && !available ? availabilityText() : a.session?.needsAnswer ? t('status.needsAnswer') : a.session || !real ? statusText(a.status) || t('status.idleNow') : t('tasks.noCurrent'); els.panelStatus.textContent = a.session?.needsAnswer ? t('status.needsAnswerFor', { title: a.session.title }) : a.session && statusText(a.status) ? `「${a.session.title}」${text}` : text; renderDetail(); + renderSpriteActivityLabel(a); +} + +function renderSpriteActivityLabel(a = activity()) { const name = app.pet?.displayName ?? t('desk.pet'); const stateLabel = a.session?.needsAnswer ? t('status.needsAnswer') : statusLabel(a.status) || sourceLabelForActivity(); els.sprite.setAttribute('aria-label', app.mode === 'window' @@ -1968,28 +2285,145 @@ function renderDetailOpen(needsAnswer) { els.detailOpen.textContent = needsAnswer ? t('tasks.goAnswer') : t('tasks.open'); } +async function openDeliveryWindow({ asset, title }) { + // The separate viewer can focus itself after the spawn request has returned. + const deadline = performance.now() + 5000; + previewBlurDeadline = deadline; + try { + const response = await fetch('/api/delivery-preview', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + asset, title, language: root.lang, theme: root.dataset.theme, + area: { x: screen.availLeft, y: screen.availTop, width: screen.availWidth, height: screen.availHeight }, + }), + }); + if (!response.ok) throw new Error('preview_window_unavailable'); + } catch { + if (previewBlurDeadline === deadline) previewBlurDeadline = 0; + if (!disposed) showTransient(t('delivery.windowFailed'), 'error'); + } +} + function initWorkbench() { + petQuota = createPetQuota({ document, ring: els.quotaRing, button: els.quickQuota }); + liveProgress = createLiveProgress({ button: els.quickBell, isVisibleSession: (id) => desktopCatalog?.bySession.has(id), + onChange: () => { + syncQuickbar(); + if (app.mode === 'window' && !document.hidden) { + renderBubble(); + if (app.workbenchOpen) renderCompactView(); + } + }, + }); workbenchView = createCompactPetView({ container: els.workbench, + getAnchor: () => shortcutSize, onClose: () => { void closeWorkbench(); }, + onChangeView: openWorkbench, onSelectTask: openTaskPreview, onOpenSession: canOpenSession ? openSessionInHost : null, + onSelectChat: (sessionId) => activitySource?.selectSession(sessionId), + onOpenDelivery: openDeliveryWindow, + onOpenProject: typeof hostNavigation?.open === 'function' ? (projectId) => { + const project = desktopCatalog?.projects.find((item) => item.id === projectId); + if (!project) return { kind: 'error', text: t('chat.project.unavailable') }; + if (!project.path) return openInHost({ id: 'home' }); + const sessionId = desktopCatalog.firstSession.get(projectId); + return sessionId ? openSessionInHost(sessionId) : openInHost({ id: 'home' }); + } : null, + onAppendDraft: typeof hostMessage?.append === 'function' ? appendDraftToHost : null, + quota: petQuota, + }); + const resizeWorkbench = new ResizeObserver(() => { + if (app.workbenchOpen && !app.restoringPosition) keepDeskPartVisible(els.workbench); }); - notificationPreviews = createNotificationPreviews({ agent, onChange: () => { renderBubble(); renderCompactView(); } }); - disposers.push(() => { notificationPreviews.dispose(); workbenchView.dispose(); }); + resizeWorkbench.observe(els.workbench); + notificationPreviews = createNotificationPreviews({ agent, onChange: () => { + if (document.hidden || app.mode !== 'window') return; + renderBubble(); + if (app.workbenchOpen) renderCompactView(); + } }); + disposers.push(() => { resizeWorkbench.disconnect(); notificationPreviews.dispose(); workbenchView.dispose(); petQuota.dispose(); liveProgress.dispose(); }); +} + +function syncNotificationPreviews() { + notificationPreviews?.update({ availability: app.availability, items: notificationItems(reminders.getState().items) }); } function renderCompactView() { const notice = reminders.getState(); - notificationPreviews?.update({ availability: app.availability, items: notificationItems(notice.items) }); const previews = notificationPreviews?.getState().previews ?? {}; - workbenchView?.update({ reminders: { ...notice, items: notice.items.map((item) => ({ ...item, previewText: item.needsAnswer ? t('status.needsAnswer') : markdownToPlainText(previews[item.sessionId] || '') })) }, allSessions: app.sessions, - taskSelection: { availability: app.availability, selectedSessionId: app.selectedSessionId, session: app.sessions.find((row) => row.sessionId === app.selectedSessionId), detail: app.detail, detailLoading: app.detailLoading, detailError: app.detailError } }); + const selected = app.sessions.find((row) => row.sessionId === app.selectedSessionId); + const unread = liveProgress?.unread ?? []; + const unreadIds = new Set(unread.map((row) => row.sessionId)); + const finishedRows = unread.map((row) => ({ ...row, status: 'idle', liveCompleted: true, previewText: row.text })); + const recent = [...finishedRows, ...notice.items.filter((item) => !unreadIds.has(item.sessionId)).map((item) => ({ + ...item, previewText: previews[item.sessionId] || '', + }))]; + const task = workbenchView?.view === 'detail' ? notificationTask : null; + const detailState = task ? taskPreviewState(task, unread.find((row) => row.sessionId === task.sessionId)) : null; + const chatSessions = app.sessions.map((row) => ({ ...row, projectId: desktopCatalog?.bySession.get(row.sessionId) })); + const projects = app.availability === 'ready' ? desktopCatalog?.projects || [] : []; + workbenchView?.update({ reminders: { ...notice, items: recent }, + allSessions: [...finishedRows, ...app.sessions.filter((row) => !unreadIds.has(row.sessionId))], + chatSessions, projects, + originId: app.originSession?.sessionId, + notificationSelection: detailState, + taskSelection: { availability: app.availability, selectedSessionId: app.selectedSessionId, session: selected, detail: app.detail, detailLoading: app.detailLoading, detailError: app.detailError } }); + if (detailState?.readable && workbenchView.viewing(task.sessionId)) { + const turn = task.completion?.turnId || detailState.session?.observedTurnId || detailState.session?.updatedAtMs; + if (task.readTurn !== turn) { + task.readTurn = turn; + if (detailState.reminderCompleted) reminders.dismiss(task.sessionId); + liveProgress?.viewed(task.sessionId, task.completion?.turnId); + } + } else if (!task && selected?.liveCompleted && app.detail?.sessionId === selected.sessionId && + app.detail.updatedAtMs >= selected.updatedAtMs && workbenchView?.viewing(selected.sessionId)) { + reminders.dismiss(selected.sessionId); + liveProgress?.viewed(selected.sessionId, selected.observedTurnId); + } +} + +function taskPreviewState(task, completion) { + const id = task.sessionId; + if (completion) task.completion = completion; + const saved = task.completion; + const native = app.sessions.find((row) => row.sessionId === id); + const allowed = app.availability === 'ready'; + const observed = liveProgress?.progress(id); + const progress = saved && observed?.turnId !== saved.turnId ? null : observed; + const session = saved ? { ...saved, status: 'idle', liveCompleted: true } : native || task.row; + const hostDetail = app.detail?.sessionId === id ? app.detail : task.detail; + const hasReply = Boolean(saved?.text || hostDetail || progress?.text); + const detailLoading = Boolean(task.waiting || app.selectedSessionId === id && app.detailLoading); + const detail = hasReply || saved && !detailLoading ? { ...session, sessionId: id, status: session?.status, + lastAssistantText: saved?.text || progress?.text || hostDetail?.lastAssistantText || '' } : null; + return { availability: allowed || saved || progress ? 'ready' : app.availability, selectedSessionId: id, session, detail, + detailLoading, detailError: saved ? null : task.error || (app.selectedSessionId === id ? app.detailError : null), + steps: progress?.steps, canOpenHost: allowed && !id.startsWith('pet:'), + reminderCompleted: native?.liveCompleted && (!saved || !native.observedTurnId || native.observedTurnId === saved.turnId), + readable: Boolean(detail && (saved || native?.liveCompleted && hostDetail && hostDetail.updatedAtMs >= native.updatedAtMs)) }; } function openTaskPreview(sessionId) { - if (!activitySource || app.availability !== 'ready') { showTransient(availabilityText(), 'error'); return; } - try { void activitySource.selectSession(sessionId).catch((error) => showTransient(t('desk.replyFailed', { code: errCode(error) }), 'error')); } - catch (error) { showTransient(t('desk.replyFailed', { code: errCode(error) }), 'error'); return; } + const completion = liveProgress?.unread.find((row) => row.sessionId === sessionId); + const row = app.sessions.find((item) => item.sessionId === sessionId); + if (!row && !completion) return; + bellView = ''; + if (row?.liveCompleted) reminders.dismiss(sessionId); + const task = { sessionId, row, completion, waiting: false }; + notificationTask = task; + if (!sessionId.startsWith('pet:') && app.availability === 'ready') { + if (row && activitySource) { + task.waiting = !completion?.text; + void callBridge(() => activitySource.selectSession(sessionId)).catch((error) => { task.error = errCode(error); }) + .finally(() => { task.waiting = false; if (notificationTask === task && app.workbenchOpen) renderCompactView(); }); + } else if (typeof agent?.session === 'function' && !completion?.text) { + task.waiting = true; + void callBridge(() => agent.session(sessionId)).then((detail) => { task.detail = detail; }, (error) => { task.error = errCode(error); }) + .finally(() => { task.waiting = false; if (notificationTask === task && app.workbenchOpen) renderCompactView(); }); + } + } void openWorkbench('detail'); } @@ -1998,6 +2432,18 @@ function focusFullPanel(view) { else { panelNavigation?.showTab('tasks'); panelNavigation?.showTaskList(); } } +function keepDeskPartVisible(element) { + const bounds = app.winBounds; + const top = screen.availTop, height = screen.availHeight; + if (app.mode !== 'window' || app.dragging || element.hidden || !bounds || !Number.isFinite(top) || !(height > 0)) return; + const rect = element.getBoundingClientRect(); + const minY = Math.ceil(top - rect.top + 4); + const maxY = Math.floor(top + height - rect.bottom - 4); + if (minY > maxY) return; + const y = clamp(bounds.y, minY, maxY); + if (y !== bounds.y) void callBridge(() => win.update({ y })).then(onWindowState, logError('show_card_in_work_area')); +} + async function openWorkbench(view = 'tasks') { if (disposed) return; app.workbenchView = view; @@ -2007,8 +2453,14 @@ async function openWorkbench(view = 'tasks') { } const token = ++app.workbenchRevision; app.compacting = false; + const entering = !app.workbenchOpen; + if (entering && !els.quickbar.hidden) { + const { width, height } = els.quickbar.getBoundingClientRect(); + shortcutSize = { width, height }; + } app.workbenchOpen = true; - closeMenu(); hideQuickbar(); stopLook(); + closeMenu(); + if (entering) stopLook(); setClickThrough(false); const waitingAt = Date.now(); while (app.restoringPosition && token === app.workbenchRevision && !disposed && Date.now() - waitingAt < 3000) await new Promise((resolve) => setTimeout(resolve, 20)); @@ -2016,14 +2468,20 @@ async function openWorkbench(view = 'tasks') { workbenchView.open(view); root.classList.add('workbench-open'); applyActivity(); + keepDeskPartVisible(els.workbench); } -async function closeWorkbench() { +async function closeWorkbench({ restoreFocus = true } = {}) { const token = ++app.workbenchRevision; + previewBlurDeadline = 0; app.compacting = true; app.workbenchOpen = false; + app.workbenchNodded = false; + notificationTask = null; + if (restoreFocus && els.workbench.contains(document.activeElement)) els.sprite.focus({ preventScroll: true }); workbenchView.close(); root.classList.remove('workbench-open'); + stopLook(); applyActivity(); app.compacting = false; if (!disposed && token === app.workbenchRevision && app.mode === 'window' && !app.workbenchOpen) refreshInteractivity(); @@ -2031,7 +2489,6 @@ async function closeWorkbench() { function renderReminders() { const state = reminders.getState(); - renderCompactView(); els.reminderNote.textContent = state.items.length ? t('tasks.reminderNote.active') : t('tasks.reminderNote.idle'); const existing = new Map([...els.reminderList.children].map((node) => [node.dataset.sessionId, node])); const nodes = state.items.slice(0, 10).map((item) => { @@ -2088,10 +2545,11 @@ function setNoticeTimeout(raw) { els.noticeInput.value = String(next); if (next === prefs.noticeTimeout) { setMsg(els.noticeMsg, ''); return; } prefs.noticeTimeout = next; - // Restart every card's clock so the new duration applies from now. const at = Date.now(); - for (const id of noticeShownAt.keys()) noticeShownAt.set(id, at); - // Keep counting from now if the input is focused while the pointer stays on a card. + for (const item of notificationItems(reminders.getState().items)) { + const key = noticeKey(item); + if (item.displayStatus === 'error' && noticeShownAt.has(key)) noticeShownAt.set(key, at); + } noticePauseAt = noticePaused ? at : 0; setMsg(els.noticeMsg, next === 0 ? t('settings.noticeNever') : t('settings.noticeSaved', { seconds: next }), 'ok'); savePreferences({ noticeTimeout: next }); @@ -2258,12 +2716,29 @@ function bindDesk() { if (!e.relatedTarget) onPointerLeave(); }); listen(root, 'mouseleave', onPointerLeave); + listen(document, 'visibilitychange', () => { + if (!document.hidden) return; + onPointerLeave(); + stopLook(); + }); listen(window, 'blur', () => { - if (app.mode === 'window') closeMenu(); + if (app.mode !== 'window') return; + const openingPreview = performance.now() < previewBlurDeadline; + previewBlurDeadline = 0; + onPointerLeave(); + closeMenu(); + if (!openingPreview) closeBellStack(); + if (app.workbenchOpen && !openingPreview && !app.dragging && !app.modeSwitching) { + void closeWorkbench({ restoreFocus: false }); + } }); listen(els.sprite, 'pointerenter', () => { if (app.mode !== 'window') return; app.hovered = true; applyActivity(); }); listen(els.sprite, 'pointerleave', () => { app.hovered = false; applyActivity(); }); + listen(els.sprite, 'focusin', () => syncQuickbar()); + listen(els.sprite, 'focusout', () => queueMicrotask(() => !disposed && syncQuickbar())); + listen(els.quickbar, 'focusin', () => syncQuickbar()); + listen(els.quickbar, 'focusout', () => queueMicrotask(() => !disposed && syncQuickbar())); listen(els.sprite, 'pointerdown', onSpritePointerDown); listen(els.sprite, 'pointermove', onSpritePointerMove); listen(els.sprite, 'pointerup', (e) => finishDrag(e, false)); @@ -2273,7 +2748,7 @@ function bindDesk() { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); noteInteraction(); - void openWorkbench('tasks'); + void openWorkbench('chat'); } else if (e.key === 'F10' && e.shiftKey) { e.preventDefault(); const r = els.sprite.getBoundingClientRect(); @@ -2298,35 +2773,54 @@ function bindDesk() { listen(document, 'pointerdown', (e) => { if (app.mode !== 'window') return; + previewBlurDeadline = 0; noteInteraction(); if (app.menuOpen && !els.menu.contains(e.target)) closeMenu(); + if (bellView && !els.quickBell.contains(e.target) && !els.notificationStack.contains(e.target)) closeBellStack(); + if (app.workbenchOpen && e.button === 0 && + ![els.workbench, els.sprite, els.quickbar, els.bubble, els.notificationStack, els.menu].some((element) => element.contains(e.target))) { + void closeWorkbench({ restoreFocus: false }); + } }); listen(document, 'keydown', (e) => { if (app.mode !== 'window' || e.key !== 'Escape') return; + if (closeBellStack()) { + els.quickBell.focus({ preventScroll: true }); + return; + } if (app.workbenchOpen) { void closeWorkbench(); } - else hideQuickbar(); }); listen(els.menu, 'keydown', onMenuKeyDown); - listen(els.quickTasks, 'click', () => { void openWorkbench('tasks'); }); - listen(els.bubble, 'click', () => { void openWorkbench('tasks'); }); + listen(els.quickChat, 'click', () => { + if (app.workbenchOpen && workbenchView.view === 'chat') void closeWorkbench(); + else void openWorkbench('chat'); + }); + listen(els.quickQuota, 'click', () => { + void openWorkbench('chat').then(() => petQuota.panel.focus({ preventScroll: true })); + }); + const previewBubble = () => { void openWorkbench('tasks'); }; + listen(els.bubble, 'click', previewBubble); listen(els.bubble, 'keydown', (event) => { - if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); void openWorkbench('tasks'); } + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); previewBubble(); } }); - listen(els.quickMenu, 'click', () => { - const r = els.quickMenu.getBoundingClientRect(); - openMenu(r.left + r.width / 2, r.bottom); + listen(els.quickBell, 'click', () => { + if (closeBellStack()) return; + if (!bellTasks().length) return; + bellView = 'stacked'; + syncQuickbar(); + renderBubble(); }); - listen(els.quickbar, 'pointerenter', armQuickbarHide); + listen(window, 'resize', () => { if (bellView === 'expanded') renderBubble(); }); - // Reading a card, with a pointer or a keyboard, must outlast the timeout. + // Hover or keyboard focus pauses dismissible error cards. listen(els.notificationStack, 'pointerenter', () => pauseNotices(true)); listen(els.notificationStack, 'pointerleave', () => pauseNotices(false)); listen(els.notificationStack, 'focusin', () => pauseNotices(true)); listen(els.notificationStack, 'focusout', (e) => { - if (!els.notificationStack.contains(e.relatedTarget)) pauseNotices(false); + if (!els.notificationStack.contains(e.relatedTarget)) queueMicrotask(() => { if (!disposed) pauseNotices(false); }); }); } @@ -2356,6 +2850,7 @@ async function boot() { player.setReducedMotion(e.matches); importState.player?.setReducedMotion(e.matches); if (e.matches) stopLook(); + else applyActivity(); }); initHostUi(); @@ -2388,12 +2883,16 @@ async function boot() { function disposeApp() { if (disposed) return; disposed = true; + stopLook(); + if (deskPointerFrame !== null) cancelAnimationFrame(deskPointerFrame); + clearTimeout(shortcutHideTimer); + cancelDrag(); for (const dispose of disposers.splice(0).reverse()) { try { dispose(); } catch (error) { console.warn('[pet] dispose_failed:', errCode(error), error); } } stopNoticeTimer(); noticeShownAt.clear(); - for (const key of ['positionTimer', 'ctWatchdog', 'menuCloseTimer', 'quickbarTimer', 'transientTimer']) { + for (const key of ['positionTimer', 'ctWatchdog', 'menuCloseTimer', 'transientTimer']) { clearTimeout(app[key]); clearInterval(app[key]); app[key] = null; diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-player.js b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-player.js index cfaa102b..21c3d353 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-player.js +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-player.js @@ -24,6 +24,9 @@ const ATLAS_WIDTH = CELL.width * CELL.columns; // 1536 const ROWS = { 1: 9, 2: 11 }; const LOOK_ROW = 9; const ALPHA_THRESHOLD = 24; +const FAST_BLINK = [42, 55, 48]; +const CHAO_YIN_IDLE = [1700, 850, 1670, ...FAST_BLINK]; +const CHAO_YIN_EYES = { x: 63, y: 69, width: 70, height: 25 }; /** 1536×1872 → 1, 1536×2288 → 2, otherwise null. */ export function atlasVersionFromSize(width, height) { @@ -148,6 +151,9 @@ export class SpritePlayer { this._scale = clampScale(scale); this._reduced = false; this._lookIndex = null; + this._blinkTimer = null; + this._blinkStep = null; + this._eyelids = null; this._state = 'idle'; // requested semantic state, independent of the rendered pose this._pose = 'idle'; this._loop = false; @@ -167,6 +173,7 @@ export class SpritePlayer { /** @param {LoadedPet} loadedPet */ setPet(loadedPet) { if (this._destroyed) return; + this._clearBlink(); this._pet = loadedPet; if (loadedPet.version !== 2) this._lookIndex = null; this._restart(); @@ -187,6 +194,7 @@ export class SpritePlayer { } get supportsLook() { return this._pet?.version === 2; } + get _hasShortBlink() { return this._pet?.id === 'chao-yin-soundwave-teacher-smooth'; } /** * Request a normal playback track. Non-idle actions play three cycles, then @@ -229,15 +237,18 @@ export class SpritePlayer { if (angleDegOrNull === null || angleDegOrNull === undefined || !Number.isFinite(angleDegOrNull)) { if (this._lookIndex === null) return; this._lookIndex = null; + this._clearBlink(); this._restart(); return; } const index = ((Math.round(angleDegOrNull / 22.5) % 16) + 16) % 16; + if (this._lookIndex === index) return; const wasLooking = this._lookIndex !== null; this._lookIndex = index; if (!wasLooking) { this._stopTimer(); if (this._transientThen !== null) this._finishTransient(); + this._scheduleBlink(); } this._render(); } @@ -269,6 +280,8 @@ export class SpritePlayer { destroy() { if (this._destroyed) return; + this._clearBlink(); + this._eyelids?.remove(); this._stopTimer(); this._settle(); document.removeEventListener('visibilitychange', this._onVisibility); @@ -317,11 +330,55 @@ export class SpritePlayer { this._col = 0; if (!this._pet || this._reduced || this._lookIndex !== null) { if (this._transientThen !== null) this._finishTransient(); + if (this._reduced) this._clearBlink(); + else this._scheduleBlink(); this._render(); return; } this._render(); - this._schedule(ANIMATIONS[this._pose].durations[0]); + this._schedule(this._durations()[0]); + } + + _durations() { return this._pose === 'idle' && this._hasShortBlink ? CHAO_YIN_IDLE : ANIMATIONS[this._pose].durations; } + + _clearBlink() { + clearTimeout(this._blinkTimer); + this._blinkTimer = this._blinkStep = null; + if (this._eyelids) this._eyelids.hidden = true; + } + + _scheduleBlink(delay = 3900) { + if (this._blinkTimer !== null || !this._hasShortBlink || this._lookIndex === null || this._reduced || document.hidden) return; + this._blinkTimer = setTimeout(() => { + this._blinkTimer = null; + this._blinkStep = this._blinkStep === null ? 0 : this._blinkStep + 1; + if (this._blinkStep === FAST_BLINK.length) this._blinkStep = null; + this._paintBlink(); + this._scheduleBlink(this._blinkStep === null ? 3900 : FAST_BLINK[this._blinkStep]); + }, delay); + } + + _paintBlink() { + if (this._blinkStep === null) { + if (this._eyelids) this._eyelids.hidden = true; + return; + } + if (!this._eyelids) { + this._eyelids = this._el.ownerDocument.createElement('span'); + this._eyelids.className = 'pet-blink-overlay'; + this._eyelids.setAttribute('aria-hidden', 'true'); + this._el.append(this._eyelids); + } + const { x, y, width, height } = CHAO_YIN_EYES, scale = this._scale; + const style = this._eyelids.style; + style.left = `${x * scale}px`; + style.top = `${y * scale}px`; + style.width = `${width * scale}px`; + style.height = `${height * scale}px`; + style.backgroundImage = this._el.style.backgroundImage; + style.backgroundSize = this._el.style.backgroundSize; + style.backgroundPosition = `-${((this._blinkStep + 3) * CELL.width + x) * scale}px -${y * scale}px`; + this._eyelids.hidden = false; } _schedule(ms) { @@ -337,7 +394,7 @@ export class SpritePlayer { this._timer = null; if (this._destroyed) return; this._col += 1; - if (this._col >= ANIMATIONS[this._pose].durations.length) { + if (this._col >= this._durations().length) { this._col = 0; this._round += 1; if (!this._loop && this._round >= this._repeat) { @@ -346,12 +403,13 @@ export class SpritePlayer { } } this._render(); - this._schedule(ANIMATIONS[this._pose].durations[this._col]); + this._schedule(this._durations()[this._col]); } _handleVisibility() { if (this._destroyed) return; if (document.hidden) { + this._clearBlink(); if (this._timer === null) return; clearTimeout(this._timer); this._timer = null; @@ -360,7 +418,7 @@ export class SpritePlayer { const ms = this._remaining; this._remaining = null; this._schedule(ms); - } + } else this._scheduleBlink(); } _render() { @@ -374,6 +432,7 @@ export class SpritePlayer { s.backgroundRepeat = 'no-repeat'; s.backgroundSize = `${ATLAS_WIDTH * k}px ${ROWS[this._pet.version] * CELL.height * k}px`; s.backgroundPosition = `-${col * CELL.width * k}px -${row * CELL.height * k}px`; + this._paintBlink(); } } diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs index 6eb01618..2f6fa8ee 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs @@ -13,32 +13,25 @@ export function aggregateText(counts, locale) { export function notificationItems(items) { return items.filter((item) => item.needsAnswer === true || ['completed', 'error'].includes(item.displayStatus)) - .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true)).slice(0, 3); + .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true)); } -/** - * Notification cards hide themselves; they never dismiss the reminder. `needsAnswer` - * cards ignore the timeout because they are the one thing the user must act on. - * A zero or negative timeout keeps every card until the user closes it. - */ -export function visibleNotices(items, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0 } = {}) { - const list = Array.isArray(items) ? items : []; - if (!(timeoutSeconds > 0)) return list; - const limit = timeoutSeconds * 1000; - return list.filter((item) => { - if (item?.needsAnswer === true) return true; - const since = shownAt instanceof Map ? shownAt.get(item?.sessionId) : shownAt?.[item?.sessionId]; - // An unknown start counts as just shown; the next paint records it. - return !Number.isFinite(since) || now - since < limit; - }); +export const noticeKey = (item) => item?.reminderKey || item?.sessionId; + +export function visibleNotices(items, options) { + return (Array.isArray(items) ? items : []).filter((item) => noticeRemaining(item, options) !== 0); } /** Milliseconds left before `item` hides, or null when it never does. */ -export function noticeRemaining(item, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0 } = {}) { - if (!(timeoutSeconds > 0) || item?.needsAnswer === true) return null; - const since = shownAt instanceof Map ? shownAt.get(item?.sessionId) : shownAt?.[item?.sessionId]; - if (!Number.isFinite(since)) return timeoutSeconds * 1000; - return Math.max(0, timeoutSeconds * 1000 - (now - since)); +export function noticeRemaining(item, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0, pausedAt = 0 } = {}) { + const completed = item?.displayStatus === 'completed'; + const duration = (completed ? 5 : timeoutSeconds) * 1000; + if (!(duration > 0) || item?.needsAnswer === true) return null; + const key = noticeKey(item); + const since = shownAt instanceof Map ? shownAt.get(key) : shownAt?.[key]; + if (!Number.isFinite(since)) return duration; + const clock = !completed && pausedAt ? Math.max(since, pausedAt) : now; + return Math.max(0, duration - (clock - since)); } export function notificationText(item, previews = {}) { diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs new file mode 100644 index 00000000..71ee4799 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs @@ -0,0 +1,86 @@ +import { t } from './i18n.mjs'; + +const label = (item) => t(`chat.quota.${item.id}`); +const percentage = (item) => item.unlimited ? '∞' : Math.round(item.remaining) + '%'; +const color = (item) => `hsl(${Math.round(item.remaining * 1.16)} 62% 39%)`; + +export function createPetQuota({ document: doc, ring, button }) { + const make = (tag, className, text) => { + const node = doc.createElement(tag); + if (className) node.className = className; + if (text) node.textContent = text; + return node; + }; + const panel = make('section', 'chat-quota'); + panel.tabIndex = -1; + panel.hidden = true; + let snapshot, active = false, pending = false, timer, updated = 0, disposed = false; + + function paint() { + const windows = snapshot?.windows || []; + const main = windows.find((item) => item.id === 'interval') || windows[0]; + const labelText = t('chat.quota.label'); + panel.setAttribute('aria-label', labelText); + const heading = make('strong', 'chat-quota-title', snapshot?.tier ? 'MiniMax ' + snapshot.tier : 'MiniMax'); + panel.replaceChildren(heading); + if (!windows.length || snapshot?.stale) { + panel.append(make('span', 'chat-quota-status', t(`chat.quota.${snapshot?.stale ? 'stale' : snapshot?.status || 'loading'}`))); + } + for (const item of windows) { + const cell = make('div', 'chat-quota-cell'); + const meter = make('span', 'chat-quota-meter'); + const fill = make('i'); + fill.style.width = item.remaining + '%'; + fill.style.backgroundColor = color(item); + meter.append(fill); + const title = label(item) + ' ' + percentage(item); + cell.append(make('span', '', label(item)), make('b', '', percentage(item)), meter); + cell.title = item.resetAt ? title + ' · ' + t('chat.quota.reset', { date: new Date(item.resetAt).toLocaleString(doc.documentElement.lang) }) : title; + panel.append(cell); + } + if (!ring || !button) return; + ring.textContent = main ? percentage(main) : '—'; + ring.style.setProperty('--quota-progress', main ? main.remaining + '%' : '0%'); + ring.style.setProperty('--quota-color', main ? color(main) : 'transparent'); + const title = main ? labelText + ' · ' + label(main) + ' ' + percentage(main) : labelText; + button.title = title; + button.setAttribute('aria-label', title); + } + + async function refresh() { + if (!active || pending || disposed) return; + pending = true; + try { + const response = await fetch('/api/minimax-quota', { cache: 'no-store' }); + if (!response.ok) throw new Error('quota'); + snapshot = await response.json(); + } catch { + snapshot = snapshot?.windows?.length ? { ...snapshot, stale: true } : { status: 'error', windows: [] }; + } finally { + pending = false; + updated = Date.now(); + if (!disposed) { paint(); schedule(); } + } + } + + function schedule() { + clearTimeout(timer); + if (!active) return; + const interval = snapshot?.stale || snapshot?.status === 'error' ? 15_000 : 60_000; + const remaining = (updated + interval) - Date.now(); + if (!updated || remaining <= 0) void refresh(); + else timer = setTimeout(refresh, remaining); + } + + paint(); + return { + panel, + translate: paint, + setActive(value) { + if (value === active) return; + active = value; + schedule(); + }, + dispose() { disposed = true; active = false; clearTimeout(timer); panel.remove(); }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/pet.css b/plugins/minimax-ai/minimax-pet/miniapp/client/pet.css index fd48054d..1e300453 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/pet.css +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/pet.css @@ -623,14 +623,15 @@ html.mode-window body { } .desk-overlays { + position: relative; display: flex; flex-direction: column; align-items: center; + justify-content: flex-end; + flex: 1; gap: 6px; - max-width: 100%; + width: min(100%, 264px); min-height: 0; - max-height: calc(100% - var(--minimax-pet-height, 104px) - 12px); - overflow-y: auto; } .desk-pet-slot { @@ -639,11 +640,32 @@ html.mode-window body { justify-content: center; } +.desk-lower { + display: grid; + flex: none; + grid-template: minmax(0, 1fr) / minmax(0, 1fr); + place-items: start center; + width: min(100%, 264px); + height: clamp(108px, calc(100vh - var(--minimax-pet-height, 104px) - 104px), 282px); +} +.desk-lower > .quickbar, .desk-lower > .workbench { grid-area: 1 / 1; } +.desk.show-all-notices .desk-overlays { flex: 1 0 auto; } +.desk.show-all-notices .desk-lower { flex: 0 1 auto; min-height: var(--notice-lower-reserve, 48px); } + html.mode-window .pet-sprite { + position: relative; cursor: grab; touch-action: none; border-radius: 8px; } +.pet-blink-overlay { + position: absolute; + pointer-events: none; + background-repeat: no-repeat; + mask-image: radial-gradient(ellipse, #000 61%, transparent 100%); +} +.chat-inline-project { display: flex; flex: none; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--mcode-text-muted); } +.chat-inline-project select { min-width: 0; max-width: calc(100% - 32px); height: 24px; color: var(--mcode-text); background: var(--mcode-bg-secondary); border: 1px solid var(--mcode-border); border-radius: 5px; font: inherit; } html.mode-window .pet-sprite.is-dragging { cursor: grabbing; } @@ -701,31 +723,55 @@ html.mode-window .pet-sprite:focus-visible { .quickbar { display: flex; - gap: 6px; -} - -.chip { - height: 28px; - padding: 0 10px; + flex: none; + align-items: center; + gap: 2px; + padding: 3px; border: 1px solid var(--mcode-border); - border-radius: 8px; + border-radius: 13px; background: var(--mcode-surface); color: var(--mcode-text); box-shadow: var(--pet-bubble-shadow); - font: inherit; - font-size: 12px; - white-space: nowrap; - cursor: pointer; - transition: background-color 150ms ease-out; } -.chip:hover, -.chip:active { - background: var(--mcode-bg-secondary); +@media (prefers-reduced-motion: no-preference) { + .quickbar:not([hidden]) { animation: shortcuts-reveal 140ms ease-out both; } + @keyframes shortcuts-reveal { from { opacity: 0; transform: scaleX(.78); } } } -.chip:disabled { - opacity: 0.5; - cursor: not-allowed; +.desk-shortcut { + position: relative; + display: grid; + place-items: center; + width: 38px; + height: 34px; + padding: 0; + background: transparent; + color: inherit; + border: 0; + border-radius: 8px; + cursor: pointer; } +.desk-shortcut:hover, .desk-shortcut[aria-expanded='true'] { background: var(--mcode-bg-secondary); } +.desk-chat-icon { position: relative; width: 17px; height: 14px; border: 1.6px solid currentColor; border-radius: 5px; } +.desk-chat-icon::after { content: ''; position: absolute; bottom: -3px; left: 3px; width: 5px; height: 5px; border-bottom: 1.6px solid; border-right: 1.6px solid; background: var(--mcode-surface); transform: rotate(45deg); } +.desk-chat-icon::before { content: ''; position: absolute; width: 7px; height: 1px; top: 5px; left: 3px; background: currentColor; } +.desk-quota-ring { + --quota-track: color-mix(in srgb, var(--mcode-text) 13%, var(--mcode-surface)); + display: grid; + place-items: center; + width: 31px; + height: 31px; + border-radius: 50%; + background: radial-gradient(closest-side, var(--mcode-surface) 79%, transparent 81%), + conic-gradient(var(--quota-color, transparent) var(--quota-progress, 0%), var(--quota-track) 0); + font-size: 9px; + font-weight: 700; + font-variant-numeric: tabular-nums; +} +.desk-bell-icon { width: 14px; height: 14px; border: 1.6px solid currentColor; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; position: relative; } +.desk-bell-icon::after { content: ''; position: absolute; height: 3px; width: 5px; bottom: -5px; left: 50%; transform: translateX(-50%); border: 1.5px solid currentColor; border-top: none; border-radius: 0 0 4px 4px; } +.desk-bell-badge { position: absolute; top: 1px; right: 3px; width: 12px; height: 12px; border-radius: 50%; background: var(--mcode-accent); color: #fff; font-size: 8px; line-height: 12px; font-weight: 700; } +.desk-bell-badge { min-width: 12px; width: auto; padding-inline: 2px; } + .menu { position: absolute; @@ -817,21 +863,16 @@ html.mode-window .pet-sprite:focus-visible { /* Small companion bubble; detailed workflows stay in the main panel. */ .workbench { - position: absolute; z-index: 5; - left: 8px; - right: 8px; - bottom: calc(var(--minimax-pet-height, 104px) + 8px); - /* Keep the 280px desk's two 8px gutters even if the native viewport becomes wider. */ - max-width: 264px; - margin-inline: auto; - /* Use the space the expanded window provides, up to what the desk leaves above the pet. */ - max-height: max(216px, calc(100% - var(--minimax-pet-height, 104px) - 24px)); + width: 100%; + min-height: 0; + max-height: 100%; display: flex; flex-direction: column; border: 1px solid var(--mcode-border); border-radius: 12px; overflow: hidden; + transform-origin: top center; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); color: var(--mcode-text); @@ -841,17 +882,66 @@ html.mode-window .pet-sprite:focus-visible { font-size: 12px; line-height: 18px; } -.compact-header { display: flex; align-items: center; justify-content: space-between; min-height: 32px; padding: 0 6px 0 10px; gap: 6px; } -.compact-state { color: var(--mcode-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.compact-header { display: flex; flex: none; align-items: center; justify-content: space-between; min-height: 32px; padding: 0 6px 0 10px; gap: 6px; } +.compact-state { color: var(--mcode-text-muted); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .compact-button { border: 0; border-radius: 6px; background: transparent; color: var(--mcode-text); font: inherit; cursor: pointer; padding: 3px 6px; } .compact-button:hover { background: var(--mcode-bg-secondary); } .compact-button:disabled { opacity: .4; cursor: default; } .compact-close { color: var(--mcode-text-muted); margin-left: auto; font-size: 17px; padding: 0 5px; min-width: 32px; min-height: 32px; } +.compact-switch { margin-left: auto; min-height: 26px; white-space: nowrap; } +.compact-switch ~ .compact-close { margin-left: 0; } +.compact-header .desk-bell { width: 30px; height: 28px; } +.chat-quota { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 9px; flex: none; padding: 7px 9px 8px; border-top: 1px solid var(--mcode-border); background: var(--mcode-bg-secondary); font-size: 10px; line-height: 13px; } +.chat-quota:focus-visible { outline-offset: -2px; } +.chat-quota strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chat-quota-status { color: var(--mcode-text-muted); } +.chat-quota-cell { display: grid; grid-template-columns: auto auto; gap: 2px 4px; align-items: baseline; flex: none; } +.chat-quota-cell span { color: var(--mcode-text-muted); } +.chat-quota-cell b { font-variant-numeric: tabular-nums; } +.chat-quota-meter { grid-column: 1 / -1; display: block; height: 3px; overflow: hidden; border-radius: 3px; background: color-mix(in srgb, var(--mcode-text) 15%, transparent); } +.chat-quota-meter i { display: block; height: 100%; } +.compact-chat { display: flex; flex-direction: column; gap: 6px; min-height: 0; padding: 2px 8px 8px; overflow: auto; scrollbar-width: thin; } +.chat-content { display: flex; flex-direction: column; gap: 5px; min-height: 0; overflow: auto; scrollbar-width: thin; } +.chat-sessions, .chat-actions, .chat-composer { display: flex; align-items: center; gap: 5px; flex: none; } +.chat-picker, .chat-input { + box-sizing: border-box; color: var(--mcode-text); background: var(--mcode-bg-secondary); font: inherit; + border: 1px solid var(--mcode-border); border-radius: 6px; padding: 3px 5px; min-width: 0; +} +.chat-picker { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex: 1; height: 32px; width: 0; padding-inline: 8px; font-size: 12px; cursor: pointer; text-align: left; } +.chat-picker:disabled { cursor: default; opacity: .65; } +.chat-picker-label, .chat-session-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chat-picker-label { min-width: 0; } +.chat-picker-chevron { flex: none; width: 6px; height: 6px; border: solid currentColor; border-width: 0 1px 1px 0; transform: translateY(-2px) rotate(45deg); transition: transform 120ms ease; } +.chat-picker[aria-expanded='true'] .chat-picker-chevron { transform: translateY(1px) rotate(225deg); } +.chat-project-list { min-height: 0; max-height: min(144px, 29vh); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; border: 1px solid var(--mcode-border); border-radius: 8px; padding: 3px; } +.chat-session-row { display: flex; align-items: center; gap: 5px; width: 100%; min-width: 0; padding: 4px 6px; border: 0; border-radius: 5px; background: transparent; color: var(--mcode-text); text-align: left; font: inherit; line-height: 17px; cursor: pointer; } +.chat-session-row:hover, .chat-session-row[aria-current='true'] { background: var(--mcode-bg-secondary); } +.chat-session-row:focus-visible { outline-offset: -2px; } +.chat-session-label { min-width: 0; flex: 1; } +.chat-session-check { color: var(--mcode-accent); } +.chat-session-running { width: 5px; height: 5px; flex: none; border-radius: 50%; background: var(--mcode-accent); } +.chat-empty { margin: 0; padding: 5px 6px; color: var(--mcode-text-muted); } +.chat-new { font-size: 18px; border: 1px solid var(--mcode-border); min-width: 32px; height: 32px; line-height: 20px; } +.chat-preview.md { min-height: 18px; max-height: min(126px, 25vh); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; } +.chat-open { padding-left: 2px; color: var(--mcode-accent); } +.chat-input { flex: 1; resize: vertical; min-height: 32px; max-height: 62px; font-size: 13px; line-height: 19px; user-select: text; } +.compact-button.chat-draft-submit { border: 1px solid var(--mcode-border); font-weight: 600; white-space: nowrap; } +.chat-status { flex: none; margin: 0; font-size: 11px; line-height: 15px; } +.chat-sessions.is-composing .chat-new { order: -1; } +.chat-sessions.is-composing .chat-new, +.compact-button.chat-inline-send { flex: none; width: 28px; min-width: 28px; height: 28px; padding: 0; border: 0; border-radius: 50%; font-size: 16px; line-height: 1; } +.chat-sessions.is-composing .chat-new { color: var(--mcode-text-muted); background: var(--mcode-bg-secondary); } +.chat-inline-compose { min-width: 0; flex: 1; display: flex; gap: 5px; align-items: flex-end; } +.chat-inline-compose .chat-input { min-width: 0; width: 0; min-height: 28px; max-height: 76px; field-sizing: content; padding: 4px 7px; resize: none; scrollbar-width: thin; font-size: 12px; line-height: 18px; } +.compact-button.chat-inline-send { color: var(--mcode-text-muted); background: var(--mcode-bg-secondary); } +.compact-button.chat-inline-send:not(:disabled) { color: white; background: var(--mcode-accent); } +@media (prefers-reduced-motion: reduce) { .chat-picker-chevron { transition: none; } } .compact-body { min-height: 0; overflow: auto; padding: 2px 10px 8px; } /* The detail pane owns the height: head and footer are fixed, the reply is the only scroller. */ .compact-detail { display: flex; flex-direction: column; gap: 4px; min-height: 0; padding: 2px 10px 8px; overflow: hidden; } .compact-detail-head { display: flex; align-items: baseline; gap: 6px; flex: none; min-width: 0; } .compact-detail-body { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; } +.compact-detail-steps { margin: 0 0 5px; padding-left: 16px; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-detail .compact-footer { flex: none; margin-top: 0; padding-top: 4px; border-top: 1px solid var(--mcode-border); } .compact-detail .compact-hint { flex: none; } .compact-hint { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; color: var(--mcode-text-muted); margin: 4px 0; font-size: 12px; line-height: 16px; } @@ -865,25 +955,42 @@ html.mode-window .pet-sprite:focus-visible { .compact-task-status { justify-self: end; padding-inline: 6px; text-align: right; white-space: nowrap; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-task-preview { grid-column: 1 / -1; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 5; overflow: hidden; margin: 0; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-empty { color: var(--mcode-text-muted); padding: 8px 0; } -.notification-stack { display: flex; flex-direction: column-reverse; gap: 5px; width: 248px; max-height: 216px; overflow-y: auto; } -.pet-notice { display: flex; align-items: start; border: 0.5px solid var(--mcode-border); border-radius: 12px; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); padding: 6px 7px 6px 10px; flex: none; } +.notification-stack { width: min(100%, 248px); } +.pet-notice-list { display: grid; gap: 3px; padding: 1px 2px 3px; } +.pet-notice { display: flex; align-items: center; gap: 5px; min-width: 0; border: 1px solid var(--mcode-border); border-radius: 18px; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); padding: 6px 7px 6px 11px; } +.notification-stack.is-stacked .pet-notice-list { isolation: isolate; padding-bottom: 14px; } +.notification-stack.is-stacked .pet-notice { grid-area: 1 / 1; align-self: start; } +.notification-stack.is-stacked .pet-notice[data-layer='0'] { z-index: 3; } +.notification-stack.is-stacked .pet-notice[data-layer='1'] { z-index: 2; translate: 0 6px; scale: .96; background: var(--mcode-bg-secondary); } +.notification-stack.is-stacked .pet-notice[data-layer='2'] { z-index: 1; translate: 0 12px; scale: .91; background: var(--mcode-bg-secondary); } +.notification-stack.is-stacked .pet-notice[data-layer='1'] > *, +.notification-stack.is-stacked .pet-notice[data-layer='2'] > * { visibility: hidden; } +.notification-stack.is-expanded .pet-notice-list { grid-template-columns: repeat(var(--notice-columns, 1), minmax(0, 1fr)); } +@media (prefers-reduced-motion: no-preference) { + .pet-notice { transition: translate 140ms ease-out, scale 140ms ease-out; } + .notification-stack.is-expanded .pet-notice { animation: notice-expand 180ms ease-out both; } + @keyframes notice-expand { + from { opacity: .5; transform: translateY(7px) scale(.97); } + to { opacity: 1; transform: none; } + } +} +.pet-stack-count { flex: none; min-width: 22px; height: 22px; padding-inline: 5px; border-radius: 11px; background: var(--mcode-bg-secondary); color: var(--mcode-text-muted); text-align: center; line-height: 22px; font-variant-numeric: tabular-nums; } .pet-notice-open { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--mcode-text); text-align: left; font: inherit; font-size: 12px; line-height: 16px; padding: 0; cursor: pointer; } .pet-notice-open strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; } -.pet-notice-preview { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 5; overflow: hidden; color: var(--mcode-text-muted); overflow-wrap: anywhere; } +.pet-notice[data-status='running'] strong::before { content: '●'; color: var(--mcode-accent); margin-right: 5px; font-size: 8px; } +.pet-notice[data-status='completed'] strong::before { content: '✓'; color: var(--mcode-success); margin-right: 5px; } +.pet-notice-preview { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; color: var(--mcode-text-muted); overflow-wrap: anywhere; } +.pet-notice-actions { flex: none; display: flex; gap: 4px; align-items: center; } +.pet-notice-action { display: grid; place-items: center; width: 25px; height: 25px; border: 0; border-radius: 50%; background: var(--mcode-bg-secondary); color: var(--mcode-text-muted); padding: 0; font-size: 14px; cursor: pointer; } +.pet-notice-action:hover { color: var(--mcode-accent); } +.pet-notice-stop { font-size: 10px; } +.pet-notice-stop:hover { color: var(--mcode-danger); } +.notification-stack.is-manual .pet-notice { padding-block: 3px; } +.notification-stack.is-manual .pet-notice-open { line-height: 14px; } +.notification-stack.is-manual .pet-notice-list .pet-notice-preview { -webkit-line-clamp: 1; } .compact-detail-title { flex: 1; min-width: 0; margin: 0; font-size: 13px; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .compact-detail-status { flex: none; font-size: 12px; line-height: 16px; color: var(--mcode-text-muted); } .compact-detail-reply { margin: 0; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } -/* The desktop card is 280px wide; keep the same structure at a tighter scale. */ -.compact-detail-reply.md { font-size: 12px; line-height: 17px; text-align: left; } -.compact-detail-reply.md .md-p, -.compact-detail-reply.md .md-list, -.compact-detail-reply.md .md-pre, -.compact-detail-reply.md .md-table, -.compact-detail-reply.md .md-quote { margin-bottom: 5px; } -.compact-detail-reply.md .md-heading { margin: 8px 0 4px; font-size: 13px; line-height: 18px; } -.compact-detail-reply.md .md-pre { padding: 6px 8px; } -.compact-detail-reply.md .md-table th, -.compact-detail-reply.md .md-table td { padding: 3px 6px; font-size: 11px; } .compact-detail-back { color: var(--mcode-text-muted); font-size: 12px; line-height: 16px; } .compact-open { font-size: 12px; font-weight: 600; } .pet-notice-dismiss { flex: none; border: 0; background: transparent; color: var(--mcode-text-muted); cursor: pointer; font-size: 15px; padding: 0 2px 0 6px; } @@ -912,6 +1019,29 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } overflow-wrap: anywhere; } +.md-delivery { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 6px; } +.md-delivery figure { margin: 0; width: fit-content; max-width: min(100%, 170px); } +.md-delivery-thumbnail { display: block; max-width: 100%; padding: 0; border: 0; background: none; cursor: zoom-in; border-radius: 5px; } +.md-delivery img { display: block; max-width: 100%; max-height: 100px; width: auto; height: auto; border-radius: 5px; } +.md-delivery figcaption { margin-top: 2px; color: var(--mcode-text-muted); font-size: 11px; line-height: 14px; } +.md-delivery-file { display: grid; width: 100%; gap: 2px; padding: 6px 8px; border: 1px solid var(--mcode-border); border-radius: 6px; background: var(--mcode-bg-secondary); color: var(--mcode-text); text-align: left; font: inherit; overflow-wrap: anywhere; } +button.md-delivery-file { cursor: pointer; } +button.md-delivery-file:hover { border-color: var(--mcode-accent); } +.md-delivery-file small { font-size: 10px; line-height: 14px; color: var(--mcode-text-muted); } + +.delivery-preview-page body { margin: 0; overflow: hidden; background: var(--mcode-surface); color: var(--mcode-text); } +.delivery-preview { display: flex; flex-direction: column; height: 100dvh; } +.delivery-preview-header { display: flex; align-items: center; flex: none; gap: 10px; min-height: 45px; padding: 4px 12px 4px 16px; border-bottom: 1px solid var(--mcode-border); } +.delivery-preview-header h1 { flex: 1; min-width: 0; margin: 0; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.delivery-preview-header button { min-height: 32px; font-size: 12px; white-space: nowrap; } +.delivery-preview-body { flex: 1; min-height: 0; overflow: auto; padding: 12px 16px; scrollbar-width: thin; overscroll-behavior: contain; user-select: text; -webkit-user-select: text; } +.delivery-preview-status { margin: 0; font-size: 13px; color: var(--mcode-text-muted); } +.delivery-preview-content { font-size: 14px; line-height: 1.6; } +.delivery-preview-content[data-kind='image']:not(.is-original) { display: grid; place-items: center; height: 100%; } +.delivery-preview-content > img { display: block; max-width: 100%; max-height: calc(100dvh - 69px); } +.delivery-preview-content.is-original > img { width: auto; max-width: none; max-height: none; } +.delivery-preview-content > pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } + .md > :first-child { margin-top: 0; } .md > :last-child { margin-bottom: 0; } @@ -969,14 +1099,18 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } overflow-wrap: anywhere; } +/* Wide blocks scroll sideways and let vertical wheel input reach the reply. */ +.md :is(.md-pre, .md-table) { + overflow-x: auto; + overscroll-behavior-x: contain; +} + .md .md-pre { margin: 0 0 8px; padding: 8px 10px; border: 1px solid var(--mcode-border); border-radius: 8px; background: var(--mcode-surface-muted); - overflow: auto; - overscroll-behavior: contain; } .md .md-pre code { @@ -1013,8 +1147,6 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } .md .md-table { margin: 0 0 8px; - overflow-x: auto; - overscroll-behavior: contain; } .md .md-table table { @@ -1067,6 +1199,20 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } .md strong { font-weight: 600; } .md del { color: var(--mcode-text-muted); } +/* The floating chat and task replies share one compact Markdown scale. */ +.desk .md { font-size: 12px; line-height: 17px; } +.desk .md :where(.md-p, .md-list, .md-pre, .md-table, .md-quote, .md-block) { margin-bottom: 5px; } +.desk .md .md-heading { margin: 8px 0 4px; font-size: 13px; line-height: 18px; } +.desk .md .md-list { padding-left: 17px; } +.desk .md .md-li { margin: 1px 0; } +.desk .md .md-task { margin-left: -17px; padding-left: 17px; } +.desk .md .md-pre { padding: 5px 7px; } +.desk .md .md-pre code { font-size: 11px; line-height: 16px; } +.desk .md .md-table th, +.desk .md .md-table td { padding: 3px 5px; } +.desk .md > :first-child { margin-top: 0; } +.desk .md > :last-child { margin-bottom: 0; } + /* Main panel: appearance, task reading, and settings share one quiet surface. All selectors are panel-scoped so the desktop companion keeps its layout. */ html.mode-inline, diff --git a/plugins/minimax-ai/minimax-pet/miniapp/client/preferences.mjs b/plugins/minimax-ai/minimax-pet/miniapp/client/preferences.mjs index 5895a2ec..dc6a2a5e 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/client/preferences.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/client/preferences.mjs @@ -1,6 +1,5 @@ -// noticeTimeout: seconds a desktop notification card stays before it hides itself. -// 0 keeps the card until the user closes it. The card hiding never dismisses the -// reminder itself, so the task list keeps showing the same round. +// noticeTimeout controls error cards. Zero keeps errors visible until dismissed. +// Completion cards use their own five-second timer and keep the reminder unread. export const DEFAULT_PREFERENCES = Object.freeze({ petId: null, scale: 0.75, autoCycle: false, windowPosition: null, noticeTimeout: 10, language: 'auto' }); export const LANGUAGES = Object.freeze(['auto', 'zh-Hans', 'en']); export const MAX_NOTICE_TIMEOUT_SECONDS = 3600; diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs new file mode 100644 index 00000000..686f4264 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs @@ -0,0 +1,43 @@ +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { completionRecord } from '../client/completion-inbox.mjs'; + +export function createCompletionStore(dataDir) { + const file = join(dataDir, 'completions.json'); + let queue = Promise.resolve(); + let records; + async function load() { + if (records) return records; + let data; + try { data = JSON.parse(await readFile(file, 'utf8')); } + catch (error) { if (error.code !== 'ENOENT') throw error; } + if (data && (data.version !== 1 || !Array.isArray(data.records))) throw new Error('completion_store_invalid'); + records = new Map((data?.records || []).map(completionRecord).filter(Boolean).map((row) => [row.sessionId, row])); + return records; + } + return { + async get() { await queue; return [...(await load()).values()]; }, + apply(change) { + const result = queue.then(async () => { + const values = await load(); + const row = change?.action === 'complete' ? completionRecord(change.row) : null; + const current = values.get(row?.sessionId || change?.sessionId); + const next = row && current?.turnId !== row.turnId && (!current || row.updatedAtMs >= current.updatedAtMs) ? row : + change?.action === 'view' && current && !current.viewed && current.turnId === change.turnId ? { ...current, text: '', viewed: true } : null; + if (!next) return; + const updated = new Map(values).set(next.sessionId, next); + const temporary = join(dataDir, `.completions-${randomUUID()}.tmp`); + await mkdir(dataDir, { recursive: true }); + try { + await writeFile(temporary, JSON.stringify({ version: 1, records: [...updated.values()] }), { mode: 0o600, flag: 'wx' }); + await rename(temporary, file); + records = updated; + } finally { await rm(temporary, { force: true }).catch(() => {}); } + }); + queue = result.catch(() => {}); + return result; + }, + flush: () => queue, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs new file mode 100644 index 00000000..f853eb54 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs @@ -0,0 +1,68 @@ +import { existsSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +const listedProject = ` + p.hidden = 0 AND (p.project_kind = 'default' OR p.listed_at_ms IS NOT NULL) + AND json_type(CASE WHEN json_valid(p.extra_data_json) THEN p.extra_data_json ELSE '{}' END, '$.sidebarRemoval') IS NULL +`; +const sidebarSession = ` + s.archived = 0 AND s.visibility = 'visible' + AND s.session_kind IN ('conversation', 'task') + AND coalesce(s.parent_session_id, '') = '' AND coalesce(s.origin_cron_id, '') = '' + AND json_extract(CASE WHEN json_valid(s.extra_data_json) THEN s.extra_data_json ELSE '{}' END, '$.miniAppOrigin') IS NULL + AND ${listedProject} + AND (p.project_kind <> 'default' OR s.is_default_workspace = 1) +`; + +async function withDesktopDatabase(read, roots = [process.env.MINIMAX_DATA_DIR, process.env.MINIS_MAX_DATA_DIR, process.env.MAVIS_DATA_DIR, join(homedir(), '.minimax')]) { + const path = roots + .filter(Boolean).map((root) => join(root, 'v2', 'sqlite', 'runtime-state.sqlite')).find(existsSync); + if (!path) return null; + let db; + try { + const { DatabaseSync } = await import('node:sqlite'); + db = new DatabaseSync(path, { readOnly: true }); + db.exec('PRAGMA busy_timeout = 250'); + return read(db); + } catch { + return null; + } finally { db?.close(); } +} + +// Filter against the desktop sidebar using metadata only. +export function readDesktopCatalog(roots) { + return withDesktopDatabase((db) => { + const projects = db.prepare(` + SELECT project_id AS id, workspace_dir AS path, display_name AS name + FROM local_runtime_projects p + WHERE ${listedProject} + ORDER BY pinned DESC, order_index, recent_at_ms DESC + `).all().map((row) => ({ id: String(row.id), path: row.path || '', name: row.name || '' })); + const sessions = db.prepare(` + SELECT s.session_id AS id, s.project_id AS projectId + FROM local_runtime_sessions s + JOIN local_runtime_projects p ON s.project_id = p.project_id + WHERE ${sidebarSession} + ORDER BY s.updated_at_ms DESC + `).all().map((row) => ({ id: row.id, projectId: String(row.projectId) })); + return { projects, sessions }; + }, roots); +} + +export function readDesktopAsset(sessionId, { nodeId, path }, roots) { + const match = nodeId + ? "a.asset_type = 'image' AND cast(json_extract(CASE WHEN json_valid(a.data_json) THEN a.data_json ELSE '{}' END, '$.nodeId') AS TEXT) = ?" + : `replace(a.path, char(92), '/') = ? ${process.platform === 'win32' ? 'COLLATE NOCASE' : ''}`; + return withDesktopDatabase((db) => db.prepare(` + SELECT a.path, coalesce(nullif(s.workspace_dir, ''), p.workspace_dir) AS workspace + FROM local_runtime_session_assets a + JOIN local_runtime_sessions s ON s.session_id = a.session_id + JOIN local_runtime_projects p ON p.project_id = s.project_id + WHERE a.session_id = ? AND a.role = 'assistant' AND a.source_tag = 'deliver-assets' + AND ${match} + AND ${sidebarSession} + ORDER BY a.updated_at_ms DESC + LIMIT 1 + `).get(sessionId, nodeId || path?.replaceAll('\\', '/')) || null, roots); +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs new file mode 100644 index 00000000..65ae1be3 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs @@ -0,0 +1,74 @@ +import { spawn } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { createInterface } from 'node:readline'; + +export function createDesktopDrag(pluginRoot) { + let worker; + let pending; + let requests = Promise.resolve(); + let stopped = false; + + function disconnect(child, error) { + if (worker !== child) return; + worker = undefined; + pending?.finish(error); + } + + async function connect() { + const script = await readFile(join(pluginRoot, 'miniapp/node/desktop-drag.ps1'), 'utf8'); + if (stopped) throw new Error('desktop_drag_stopped'); + const shell = join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'); + const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { + stdio: ['pipe', 'pipe', 'ignore'], + windowsHide: true, + }); + worker = child; + child.once('error', (error) => disconnect(child, error)); + child.once('close', () => disconnect(child, new Error('desktop_drag_closed'))); + child.stdin.on('error', (error) => disconnect(child, error)); + createInterface({ input: child.stdout }).on('line', (line) => { + if (worker !== child) return; + if (line === 'ok') pending?.finish(undefined, true); + else if (line === 'ignored') pending?.finish(undefined, false); + else if (line === 'error') pending?.finish(new Error('desktop_drag_failed')); + }); + return child; + } + + return { + send(command) { + const task = requests.then(async () => { + if (stopped) throw new Error('desktop_drag_stopped'); + const child = worker ?? await connect(); + if (worker !== child) throw new Error('desktop_drag_closed'); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + disconnect(child, new Error('desktop_drag_timeout')); + child.kill(); + }, 6_000); + pending = { + finish(error, result) { + clearTimeout(timeout); + pending = undefined; + if (error) reject(error); + else resolve(result); + }, + }; + child.stdin.write(command + '\n'); + }); + }); + requests = task.catch(() => {}); + return task; + }, + async dispose() { + stopped = true; + if (worker) { + const child = worker; + disconnect(child, new Error('desktop_drag_stopped')); + child.kill(); + } + await requests; + }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 new file mode 100644 index 00000000..c088ff23 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 @@ -0,0 +1,130 @@ +$ErrorActionPreference = 'Stop' + +Add-Type -TypeDefinition @' +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +public static class MiniMaxPetDrag { + private static int moving; + private static int cancellation; + [StructLayout(LayoutKind.Sequential)] + private struct Rect { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] + private struct Point { public int X, Y; } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr FindWindow(string className, string title); + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process); + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] + private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] + private static extern uint GetDpiForWindow(IntPtr window); + [DllImport("user32.dll")] + private static extern bool GetWindowRect(IntPtr window, out Rect rectangle); + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out Point point); + [DllImport("user32.dll")] + private static extern short GetAsyncKeyState(int key); + [DllImport("user32.dll")] + private static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] + private static extern bool SetWindowPos(IntPtr window, IntPtr order, int x, int y, int width, int height, uint flags); + [DllImport("winmm.dll")] + private static extern uint timeBeginPeriod(uint period); + [DllImport("winmm.dll")] + private static extern uint timeEndPeriod(uint period); + + public static void Stop() { + Interlocked.Increment(ref cancellation); + } + + private static IntPtr FindPetWindow() { + IntPtr window = FindWindow("Chrome_WidgetWin_1", "MiniMax Pet"); + IntPtr main = FindWindow("Chrome_WidgetWin_1", "MiniMax Code"); + uint owner, mainOwner; + GetWindowThreadProcessId(window, out owner); + GetWindowThreadProcessId(main, out mainOwner); + if (window == IntPtr.Zero || !IsWindowVisible(window) || owner == 0 || owner != mainOwner) + return IntPtr.Zero; + try { + using (Process process = Process.GetProcessById((int)owner)) { + if (process.ProcessName != "MiniMax Code") return IntPtr.Zero; + } + } catch (ArgumentException) { return IntPtr.Zero; } + catch (InvalidOperationException) { return IntPtr.Zero; } + return window; + } + + public static bool Start(int dx, int dy) { + IntPtr window = FindPetWindow(); + if (window == IntPtr.Zero) return false; + int primary = GetSystemMetrics(23) != 0 ? 2 : 1; // SM_SWAPBUTTON + if (GetAsyncKeyState(primary) >= 0) return false; + + Rect frame; + Point cursor; + IntPtr previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); + try { + if (!GetWindowRect(window, out frame) || !GetCursorPos(out cursor)) return false; + } finally { + if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi); + } + double scale = GetDpiForWindow(window) / 96.0; + int pressX = cursor.X - (int)Math.Round(dx * scale); + int pressY = cursor.Y - (int)Math.Round(dy * scale); + if (scale <= 0 || pressX < frame.Left || pressX >= frame.Right || pressY < frame.Top || pressY >= frame.Bottom) + return false; + if (Interlocked.CompareExchange(ref moving, 1, 0) != 0) return false; + + int ticket = Volatile.Read(ref cancellation); + Thread thread = new Thread(delegate() { + SetThreadDpiAwarenessContext(new IntPtr(-4)); + int lastX = frame.Left, lastY = frame.Top; + const uint moveOnly = 0x0001 | 0x0004 | 0x0010; // NOSIZE, NOZORDER, NOACTIVATE + bool highResolution = timeBeginPeriod(1) == 0; + try { + Point point; + while (ticket == Volatile.Read(ref cancellation) && GetAsyncKeyState(primary) < 0 && + IsWindowVisible(window) && GetCursorPos(out point)) { + int x = frame.Left + point.X - pressX, y = frame.Top + point.Y - pressY; + if (x != lastX || y != lastY) { + if (!SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, moveOnly)) break; + lastX = x; + lastY = y; + } + Thread.Sleep(5); + } + } finally { + if (highResolution) timeEndPeriod(1); + Interlocked.Exchange(ref moving, 0); + } + }); + thread.IsBackground = true; + thread.Start(); + return true; + } +} +'@ + +while ($null -ne ($line = [Console]::ReadLine())) { + try { + if ($line -eq 'warm') { + [Console]::WriteLine('ok') + } elseif ($line -eq 'stop') { + [MiniMaxPetDrag]::Stop() + [Console]::WriteLine('ok') + } elseif ($line -match '^drag (-?\d+) (-?\d+)$') { + $started = [MiniMaxPetDrag]::Start([int]$Matches[1], [int]$Matches[2]) + [Console]::WriteLine($(if ($started) {'ok'} else {'ignored'})) + } else { + [Console]::WriteLine('error') + } + } catch { + [Console]::WriteLine('error') + } +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs new file mode 100644 index 00000000..37a8856c --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs @@ -0,0 +1,121 @@ +import { createHash } from 'node:crypto'; +import { access, readFile, readdir } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +// Same two account endpoints used by the Agent 额度看板 plugin. +const MEMBERSHIP_URL = 'https://agent.minimax.cn/matrix/api/v1/commerce/get_membership_info'; +const QUOTA_URL = 'https://www.minimaxi.com/v1/api/openplatform/coding_plan/remains'; +const QUERY = { + device_platform: 'web', biz_id: '3', app_id: '3001', version_code: '22201', timezone_offset: '0', + sys_language: 'zh', lang: 'zh', device_id: '0', user_id: '0', client: 'desktop', region: 'cn', is_desktop: '1', +}; +const number = (value) => typeof value === 'number' || typeof value === 'string' && value.trim() ? Number(value) : NaN; +const tokenText = (value) => typeof value === 'string' ? value.trim() : ''; +const md5 = (value) => createHash('md5').update(value).digest('hex'); + +async function findAuth(root) { + const dirs = [join(root, 'auth')]; + while (dirs.length) { + const dir = dirs.pop(); + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + const path = join(dir, entry.name); + if (entry.isDirectory()) dirs.push(path); + if (!entry.isFile() || entry.name !== 'auth.json') continue; + try { + const profile = JSON.parse(await readFile(path, 'utf8')); + for (const item of Object.values(profile.records ?? {})) { + const token = tokenText(item?.accessToken); + const expiry = number(item?.expiresAtMs); + if (token && (!Number.isFinite(expiry) || expiry > Date.now())) return token; + } + } catch { /* A profile may be replaced during an account change. */ } + } + } + return ''; +} + +async function readAccountToken() { + const homeData = join(homedir(), '.minimax'); + const roots = [process.env.MINIS_MAX_DATA_DIR, process.env.MAVIS_DATA_DIR, process.env.MINIMAX_DATA_DIR, process.env.DATA_DIR, homeData]; + for (const root of roots) { + if (!root) continue; + if (root !== homeData && !await access(join(root, 'v2', 'sqlite')).then(() => true, () => false)) continue; + return findAuth(root); + } + return ''; +} + +export function quotaWindows(payload) { + const models = payload?.data?.model_remains ?? payload?.model_remains; + if (!Array.isArray(models)) return []; + const source = models.find((model) => model?.model_name === 'general') ?? models.find((model) => tokenText(model?.model_name)); + if (!source) return []; + return [['interval', 'remains_time'], ['weekly', 'weekly_remains_time']].flatMap(([id, resetKey]) => { + const prefix = `current_${id}`; + const unlimited = number(source[`${prefix}_status`]) === 3; + const explicit = number(source[`${prefix}_remaining_percent`]); + const total = number(source[`${prefix}_total_count`]); + const remainingCount = number(source[`${prefix}_usage_count`]); + const percent = explicit >= 0 && explicit <= 100 ? explicit : total > 0 ? remainingCount / total * 100 : NaN; + if (!unlimited && !Number.isFinite(percent)) return []; + const resetMs = number(source[resetKey]); + return [{ id, remaining: unlimited ? 100 : Math.min(100, Math.max(0, percent)), unlimited, + resetAt: Number.isFinite(resetMs) && resetMs > 0 ? Date.now() + resetMs : null }]; + }); +} + +export function createMiniMaxQuota({ fetch: request = globalThis.fetch, readToken = readAccountToken } = {}) { + let cache, pending; + const controller = new AbortController(); + async function fetchQuota() { + try { + const token = await readToken(); + if (!token) return { status: 'signedOut', windows: [] }; + const now = Date.now(), second = Math.floor(now / 1000); + const url = new URL(MEMBERSHIP_URL); + url.search = new URLSearchParams({ ...QUERY, unix: String(now) }).toString(); + const body = JSON.stringify({ workspace_id: 0 }); + const auth = { Accept: 'application/json', Authorization: `Bearer ${token}` }; + const options = () => ({ redirect: 'error', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]) }); + const membershipResponse = await request(url, { + ...options(), method: 'POST', body, + headers: { + ...auth, 'Content-Type': 'application/json', + yy: md5(`${encodeURIComponent(url.pathname + url.search)}_${body}${md5(String(now))}ooui`), + 'x-timestamp': String(second), + 'x-signature': md5(`${second}I*7Cf%WZ#S&%1RlZJ&C2${body}`), + }, + }); + if (!membershipResponse.ok) throw new Error('membership request failed'); + const membership = await membershipResponse.json(); + const groupId = tokenText(membership?.op_group_id ?? membership?.data?.op_group_id); + if (!groupId) return { status: 'unavailable', windows: [] }; + const quotaUrl = new URL(QUOTA_URL); + quotaUrl.search = new URLSearchParams({ business: 'Agent', device_platform: 'desktop' }).toString(); + const quotaResponse = await request(quotaUrl, { ...options(), headers: { ...auth, 'X-Group-Id': groupId } }); + if (!quotaResponse.ok) throw new Error('quota request failed'); + const windows = quotaWindows(await quotaResponse.json()); + const tier = tokenText(membership?.token_plan_tier ?? membership?.data?.token_plan_tier).slice(0, 40); + return { status: windows.length ? 'ok' : 'unavailable', tier, windows }; + } catch { + return { status: 'error', windows: [] }; + } + } + + return { + get() { + if (cache?.until > Date.now()) return Promise.resolve(cache.value); + pending ??= fetchQuota().then((value) => { + if (value.status === 'error' && cache?.value?.windows.length) { + value = { ...cache.value, stale: true }; + } + cache = { value, until: Date.now() + (value.status === 'error' || value.stale ? 12_000 : 55_000) }; + return value; + }).finally(() => { pending = undefined; }); + return pending; + }, + dispose() { controller.abort(); }, + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs new file mode 100644 index 00000000..b7033d76 --- /dev/null +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs @@ -0,0 +1,39 @@ +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { stat } from 'node:fs/promises'; +import { join } from 'node:path'; + +export function previewWindowBounds(area) { + if (!area || ![area.x, area.y, area.width, area.height].every(Number.isFinite) || + Math.abs(area.x) > 100_000 || Math.abs(area.y) > 100_000 || + area.width < 200 || area.height < 180 || area.width > 16_000 || area.height > 16_000) { + return { width: 840, height: 480 }; + } + const width = Math.round(Math.min(area.width, Math.max(360, area.width / 2))); + const height = Math.round(Math.min(area.height, Math.max(260, area.height / 2))); + return { width, height, x: Math.round(area.x + (area.width - width) / 2), y: Math.round(area.y + (area.height - height) / 2) }; +} + +export function createPreviewLauncher(dataDir, spawnProcess = spawn) { + const profile = join(dataDir, 'delivery-preview-browser'); + let edge; + return async ({ url, bounds }) => { + if (process.platform !== 'win32') throw new Error('preview_window_unavailable'); + if (!edge) { + for (const root of [process.env['ProgramFiles(x86)'], process.env.ProgramFiles, process.env.LOCALAPPDATA]) { + if (!root) continue; + const candidate = join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'); + if ((await stat(candidate).catch(() => null))?.isFile()) { edge = candidate; break; } + } + } + if (!edge) throw new Error('preview_window_unavailable'); + const position = Number.isFinite(bounds.x) && Number.isFinite(bounds.y) + ? [`--window-position=${bounds.x},${bounds.y}`] : []; + const child = spawnProcess(edge, [ + `--app=${url}`, `--user-data-dir=${profile}`, `--window-size=${bounds.width},${bounds.height}`, ...position, + '--no-first-run', '--no-default-browser-check', '--disable-background-mode', + ], { stdio: 'ignore', windowsHide: false }); + await once(child, 'spawn'); + child.unref(); + }; +} diff --git a/plugins/minimax-ai/minimax-pet/miniapp/node/server.mjs b/plugins/minimax-ai/minimax-pet/miniapp/node/server.mjs index 5eac7caf..a6a0a593 100644 --- a/plugins/minimax-ai/minimax-pet/miniapp/node/server.mjs +++ b/plugins/minimax-ai/minimax-pet/miniapp/node/server.mjs @@ -2,12 +2,19 @@ // MiniMax Pet — Codex Pet Mini App Node entry. Serves the pet page, static client assets, and the pet API. import { open, readFile, realpath } from 'node:fs/promises'; +import { randomBytes } from 'node:crypto'; import { createServer } from 'node:http'; -import { extname, join, resolve, sep } from 'node:path'; +import { extname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { pipeline } from 'node:stream/promises'; import { PET_ID_PATTERN, PetError, createPetStore } from './pet-store.mjs'; import { PreferenceError, createPreferenceStore } from './preferences-store.mjs'; +import { createDesktopDrag } from './desktop-drag.mjs'; +import { createMiniMaxQuota } from './minimax-quota.mjs'; +import { createCompletionStore } from './completion-store.mjs'; +import { readDesktopCatalog, readDesktopAsset } from './desktop-catalog.mjs'; +import { deliveryFormat } from '../client/delivery-formats.mjs'; +import { createPreviewLauncher, previewWindowBounds } from './preview-window.mjs'; /** * @typedef {{ debug(m: string, f?: object): void, info(m: string, f?: object): void, warn(m: string, f?: object): void, error(m: string, f?: object): void }} Logger @@ -18,6 +25,10 @@ import { PreferenceError, createPreferenceStore } from './preferences-store.mjs' const BODY_LIMIT = 12 * 1024 * 1024; const DRAIN_LIMIT = 4 * BODY_LIMIT; +const IMAGE_LIMIT = 20 * 1024 * 1024; +const TEXT_PREVIEW_LIMIT = 512 * 1024; +const PREVIEW_LIFETIME = 8 * 60 * 60 * 1000; +const MAX_PREVIEWS = 32; const ASSET_MIME = /** @type {Record} */ ({ '.html': 'text/html; charset=utf-8', @@ -44,11 +55,15 @@ class HttpError extends Error { * @param {MiniAppContext} context * @returns {Promise<{ dispose(): Promise }>} */ -export async function start(context) { +export async function start(context, { launchPreview = createPreviewLauncher(context.dataDir) } = {}) { const clientRoot = resolve(context.pluginRoot, 'miniapp', 'client'); const logger = context.logger; const store = createPetStore({ clientRoot, dataDir: context.dataDir, logger }); const preferences = createPreferenceStore({ dataDir: context.dataDir }); + const completions = createCompletionStore(context.dataDir); + const previews = new Map(); + const desktopDrag = process.platform === 'win32' ? createDesktopDrag(context.pluginRoot) : null; + const quota = createMiniMaxQuota(); /** @type {string | null} */ let clientRootReal = null; @@ -85,6 +100,80 @@ export async function start(context) { requireMethod(method, ['GET']); return serveAsset(response, path.slice('/assets/'.length)); } + if (path === '/api/session-asset') { + requireMethod(method, ['GET']); + requireLocalOrigin(request); + return serveSessionAsset(response, new URLSearchParams(queryAt === -1 ? '' : rawUrl.slice(queryAt + 1))); + } + if (path === '/api/delivery-preview') { + requireMethod(method, ['POST']); + const origin = requireLocalOrigin(request); + const body = await readJsonBody(request, 16 * 1024); + const params = new URLSearchParams(); + for (const field of ['session', 'node', 'file']) { + if (typeof body?.asset?.[field] === 'string') params.set(field, body.asset[field]); + } + const { format, name } = await resolveSessionAsset(params); + const token = randomBytes(24).toString('base64url'); + const title = typeof body?.title === 'string' ? body.title.trim().slice(0, 300) : ''; + const theme = body?.theme === 'dark' || body?.theme === 'light' ? body.theme : ''; + const language = typeof body?.language === 'string' && /^zh\b/iu.test(body.language) ? 'zh-Hans' : 'en'; + if (previews.size >= MAX_PREVIEWS) previews.delete(previews.keys().next().value); + previews.set(token, { params, title: title || name, kind: format.kind, theme, language, expires: Date.now() + PREVIEW_LIFETIME }); + try { + await launchPreview({ url: `${origin}/preview/${token}`, bounds: previewWindowBounds(body?.area) }); + } catch { + previews.delete(token); + throw new HttpError(503, 'preview_window_unavailable', 'preview window unavailable'); + } + return sendJson(response, 200, { opened: true }); + } + if (path.startsWith('/preview/')) { + requireMethod(method, ['GET']); + const route = /^\/preview\/([\w-]{32})(?:\/(info|content))?$/u.exec(path); + const preview = route && previews.get(route[1]); + if (!preview || preview.expires <= Date.now()) throw notFound(); + if (!route[2]) { + const html = await readFile(join(clientRoot, 'delivery-preview.html')); + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff', + 'referrer-policy': 'no-referrer', + 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'", + }); + response.end(html); + return; + } + requireLocalOrigin(request); + if (route[2] === 'content') return serveSessionAsset(response, preview.params); + return sendJson(response, 200, { title: preview.title, kind: preview.kind, theme: preview.theme, language: preview.language }); + } + if (path === '/api/completions' || path === '/api/desktop-catalog') { + if ((request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin') || + (request.headers.origin && request.headers.origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + if (path === '/api/desktop-catalog') { + requireMethod(method, ['GET']); + const catalog = await readDesktopCatalog(); + if (!catalog) throw new HttpError(503, 'desktop_catalog_unavailable', 'desktop catalog unavailable'); + return sendJson(response, 200, catalog); + } + requireMethod(method, ['GET', 'POST']); + if (method === 'GET') return sendJson(response, 200, { records: await completions.get() }); + await completions.apply(await readJsonBody(request, 64 * 1024)); + return sendJson(response, 200, { saved: true }); + } + if (path === '/api/minimax-quota') { + requireMethod(method, ['GET']); + const origin = request.headers.origin; + const fetchSite = request.headers['sec-fetch-site']; + if ((fetchSite && fetchSite !== 'same-origin') || (origin && origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + return sendJson(response, 200, await quota.get()); + } if (path === '/api/preferences') { requireMethod(method, ['GET', 'PATCH']); if (method === 'GET') return sendJson(response, 200, await preferences.get()); @@ -95,6 +184,31 @@ export async function start(context) { if (condition !== undefined && condition !== '*') throw new HttpError(400, 'invalid_preferences_condition', 'only If-None-Match: * is supported'); return sendJson(response, 200, await preferences.patch(await readJsonBody(request, 16 * 1024), { onlyIfUnpersisted: condition === '*' })); } + if (path === '/api/desktop-drag') { + requireMethod(method, ['POST']); + const origin = request.headers.origin; + if (request.headers['sec-fetch-site'] === 'cross-site' || (origin && origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin write not allowed'); + } + const body = await readJsonBody(request, 512); + const action = body?.action; + if (action !== 'warm' && action !== 'stop' && action !== 'drag') { + throw new HttpError(400, 'invalid_drag_action', 'invalid desktop drag action'); + } + let command = action; + if (action === 'drag') { + const { dx, dy } = body; + if (![dx, dy].every((offset) => Number.isInteger(offset) && Math.abs(offset) <= 512)) { + throw new HttpError(400, 'invalid_drag_offset', 'invalid desktop drag offset'); + } + command = `drag ${dx} ${dy}`; + } + try { + return sendJson(response, 200, { ok: await desktopDrag?.send(command) === true }); + } catch { + return sendJson(response, 200, { ok: false }); + } + } if (path === '/api/pets') { requireMethod(method, ['GET', 'POST']); if (method === 'GET') { @@ -174,7 +288,8 @@ export async function start(context) { disposing ??= (async () => { context.signal.removeEventListener('abort', onAbort); server.closeAllConnections(); - await close(server); + quota.dispose(); + await Promise.all([close(server), desktopDrag?.dispose(), completions.flush()]); logger.info('pet.runtime.disposed'); })(); return disposing; @@ -236,6 +351,59 @@ function notFound() { return new HttpError(404, 'not_found', 'not found'); } +/** @param {Req} request */ +function requireLocalOrigin(request) { + const host = request.headers.host || ''; + const origin = `http://${host}`; + if (!/^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/iu.test(host) || + request.headers['sec-fetch-site'] !== 'same-origin' || + (request.headers.origin && request.headers.origin !== origin)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + return origin; +} + +/** @param {unknown} path @returns {path is string} */ +function isLocalAbsolutePath(path) { + if (typeof path !== 'string' || !isAbsolute(path)) return false; + return process.platform === 'win32' ? /^[a-z]:[/\\][^:\0]*$/iu.test(path) : !path.startsWith('//') && !path.includes('\0'); +} + +/** @param {URLSearchParams} params */ +async function resolveSessionAsset(params) { + const id = params.get('session') || ''; + const node = params.get('node') || ''; + const path = params.get('file') || ''; + if (!/^[\w.:-]{1,128}$/u.test(id) || (node ? path || !/^[\w-]{1,128}$/u.test(node) : path.length > 2048 || !isLocalAbsolutePath(path))) throw notFound(); + // Only the indexed delivery supplies the file path and its permitted workspace. + const asset = await readDesktopAsset(id, { nodeId: node, path }); + if (!asset || !isLocalAbsolutePath(asset.path) || !isLocalAbsolutePath(asset.workspace)) throw notFound(); + const format = deliveryFormat(asset.path); + if (!format || (node && format.kind !== 'image')) throw notFound(); + const [file, workspace] = await Promise.all([realpath(asset.path), realpath(asset.workspace)]).catch(() => []); + if (!file || !workspace || !isLocalAbsolutePath(file) || !isLocalAbsolutePath(workspace)) throw notFound(); + const child = relative(workspace, file); + if (!child || child === '..' || child.startsWith('..' + sep) || isAbsolute(child)) throw notFound(); + return { file, format, name: asset.path.split(/[/\\]/u).at(-1) }; +} + +/** @param {Res} response @param {URLSearchParams} params */ +async function serveSessionAsset(response, params) { + const { file, format } = await resolveSessionAsset(params); + return sendFile(response, file, format.mime, format.kind); +} + +/** @param {import('node:fs/promises').FileHandle} file @param {string} type */ +async function hasRasterSignature(file, type) { + const head = Buffer.alloc(12); + const { bytesRead } = await file.read(head, 0, head.length, 0); + if (bytesRead < head.length) return false; + if (type === 'image/jpeg') return head.subarray(0, 3).toString('hex') === 'ffd8ff'; + if (type === 'image/png') return head.subarray(0, 8).toString('hex') === '89504e470d0a1a0a'; + if (type === 'image/gif') return /^GIF8[79]a$/u.test(head.toString('ascii', 0, 6)); + return head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP'; +} + /** @param {unknown} error */ function errnoCode(error) { return error && typeof error === 'object' && 'code' in error ? String(error.code) : 'unknown'; @@ -263,8 +431,8 @@ function sendError(response, status, code, message, headers) { sendJson(response, status, { error: code, message }, headers); } -/** @param {Res} response @param {string} path @param {string} contentType */ -async function sendFile(response, path, contentType) { +/** @param {Res} response @param {string} path @param {string} contentType @param {string} [preview] */ +async function sendFile(response, path, contentType, preview) { let handle; try { handle = await open(path, 'r'); @@ -274,11 +442,14 @@ async function sendFile(response, path, contentType) { try { const st = await handle.stat(); if (!st.isFile()) throw notFound(); + if (preview === 'image' && (st.size > IMAGE_LIMIT || !await hasRasterSignature(handle, contentType))) throw notFound(); + if (preview && preview !== 'image' && st.size > TEXT_PREVIEW_LIMIT) throw notFound(); response.writeHead(200, { 'content-type': contentType, 'content-length': String(st.size), - 'cache-control': 'no-cache', + 'cache-control': preview ? 'private, no-store' : 'no-cache', 'x-content-type-options': 'nosniff', + ...(preview ? { 'cross-origin-resource-policy': 'same-origin' } : {}), }); const stream = handle.createReadStream({ autoClose: false }); try { diff --git a/sources/minimax-ai/minimax-pet/.minimax-plugin/plugin.json b/sources/minimax-ai/minimax-pet/.minimax-plugin/plugin.json index 49536175..21454997 100644 --- a/sources/minimax-ai/minimax-pet/.minimax-plugin/plugin.json +++ b/sources/minimax-ai/minimax-pet/.minimax-plugin/plugin.json @@ -2,8 +2,8 @@ "schemaVersion": 1, "name": "minimax-pet", "displayName": "MiniMax Pet", - "version": "0.9.5", - "description": "轻量桌宠,聚合主窗口可见会话的任务状态、需要回答的提醒和最新结果,支持外观切换及图集导入。", + "version": "0.10.0", + "description": "桌宠读取 MiniMax Code 内置会话,显示实时回复、任务进度和 MiniMax 订阅额度,支持外观切换及图集导入。", "author": "MiniMax", "icon": "icon.png", "category": "Other", diff --git a/sources/minimax-ai/minimax-pet/PROVENANCE.md b/sources/minimax-ai/minimax-pet/PROVENANCE.md index f6fb038c..2fcc46b4 100644 --- a/sources/minimax-ai/minimax-pet/PROVENANCE.md +++ b/sources/minimax-ai/minimax-pet/PROVENANCE.md @@ -1,6 +1,6 @@ # Source and distribution -Author: MiniMax ([MiniMax-AI](https://github.com/MiniMax-AI)). This is the 0.7.0 open-source edition of the MiniMax Pet MiniApp. It uses public MiniApp page APIs and contains no Host implementation. Public documentation, dependency URLs, and license notices have been prepared for this repository; private development references and acceptance records are not part of the package. +Author: MiniMax ([MiniMax-AI](https://github.com/MiniMax-AI)). This is the 0.10.0 open-source edition of the MiniMax Pet MiniApp. It uses public MiniApp page APIs and contains no Host implementation. Public documentation, dependency URLs, and license notices have been prepared for this repository; private development references and acceptance records are not part of the package. ## Layout diff --git a/sources/minimax-ai/minimax-pet/README.md b/sources/minimax-ai/minimax-pet/README.md index fde7f2a4..4e4a737a 100644 --- a/sources/minimax-ai/minimax-pet/README.md +++ b/sources/minimax-ai/minimax-pet/README.md @@ -2,93 +2,33 @@ English | [简体中文](README.zh-CN.md) -A lightweight desktop companion for MiniMax Code, by **MiniMax**. It shows visible conversation activity, answer-needed reminders and recent results without creating another chat. The interface is available in Simplified Chinese and English. +MiniMax Pet **0.10.0** is a desktop companion for MiniMax Code. Hover over the pet or focus its shortcuts to open chats, check MiniMax subscription limits, or review task activity. -## Features - -- **Appearance:** preview and select pets, import compatible pet JSON and spritesheets, and remove imported pets. -- **Tasks:** recent reminders, visible user conversations, and a scrollable latest reply rendered as Markdown. Desktop cards preview up to five lines. Clicking a card keeps the pet visible; observed `ask_user` calls show “需要你回答” (needs your answer). -- **Open the conversation:** on MiniMax Code 3.1.11 or later, a task's detail, in the panel and on the desktop, has a **打开对话** (open conversation) button, labelled **去回答** (go answer) while the task needs an answer. It brings the MiniMax Code main window forward on that conversation. Older clients do not show the button. -- **Language:** the panel and desktop copy follow the MiniMax Code interface language on 3.1.11 or later, or the system language when the client does not report one, and can be pinned in **Settings**. Older clients fall back to the system language. -- **Settings:** pet size, interface language, how long desktop cards stay, page-local reminder dismissal and mute, connection status, and reconnect. -- **Desktop window:** a draggable transparent pet with compact notification cards. Return it to the main panel to use the three tabs. -- **Theme:** on MiniMax Code 3.1.11 or later the panel and desktop cards follow the client's light or dark theme; older clients follow the system setting. - -The pet does not run Agent turns, create independent chats, write to chat inputs, comment on every session, stop tasks, or answer questionnaires. Selecting a task only reads its details; the main window switches only when you click **打开对话** or **去回答**. - -Version **0.9.0** adds two settings. **Task notifications** sets how many seconds a desktop card stays after a task finishes or fails, entered as a number and saved on the device; the default is 10 and **0** keeps the card until you close it. A card hiding never marks the task read, cards that need your answer never hide, and pointing at or focusing the cards pauses the countdown. **Language** follows the MiniMax Code interface language by default and can be pinned to 简体中文 or English; the whole panel and desktop copy switch, while conversation titles and replies stay as the Agent wrote them. - -Version **0.9.0** also gives the desktop window one fixed size, tall enough for the open card. Earlier versions grew the window when a card opened, which moved it on screen and made the pet jump for a frame; now opening or closing a card only shows or hides it. The area above the pet is transparent and passes clicks through to whatever is behind it. - -Version **0.9.2** keeps the desktop window at its intended size while dragging by sending the configured size with each move, rather than carrying forward unexpected native bounds. The desktop task card is centered and capped at 264 CSS pixels; it can still fit narrower windows with the existing 8-pixel side gutters. Permissions and dependencies are unchanged. - -Version **0.9.3** moves the desktop pet using the Host-confirmed window position and the pointer's offset from the grab point. The page waits for each move to finish before using another pointer sample. If you release while a move is pending, the window stays at the last position accepted by the Host. - -Version **0.9.5** adds “潮音 · MiniMax 老师” (Chao Yin) as an optional community pet with nine animations and 16 look directions. - -Version **0.9.4** keeps the pet reachable when you choose **放到桌面**. It tries the saved position, then fits the window to the usable area of the screen it actually lands on. A valid position on another display stays put; when the window is taller than the available area, the pet stays at the bottom rather than being hidden below the screen. - -Version **0.8.1** fixes the desktop card: the title truncates to one line, only the reply scrolls, and the actions stay pinned, so a long title or reply no longer pushes 返回任务 / 打开对话 out of the card. Expanding the card also grows the window instead of squeezing the reply into one line. - -Version **0.8.0** aligns the panel with the MiniMax Code design language: 24px page margins and section gaps, 14px/22px body copy with 12px/18px supporting text, 32px minimum control height, 12px cards and 8px controls, 0.5px borders on desktop overlays, and press/focus states. The desktop pet keeps its 280px layout with the same tokens. - -Version **0.7.0** renders each task's latest reply as Markdown: headings, emphasis, lists, task lists, fenced code, tables, quotes and links, with raw HTML shown as inert text and images as a label instead of a remote request. Notification cards and reminder previews stay plain text. Parsing uses a vendored bundle of unified, remark-parse and remark-gfm (MIT) built by `npm run build:markdown`; the page never builds an HTML string from model output. The bundle makes no network request and runs entirely in the page. - -Version **0.6.0** removes the **打招呼** (wave) and **跳一下** (jump) actions from the menu and the appearance page, and removes the original-chat draft with its voice input; the package no longer requests the microphone. It adds **打开对话** / **去回答** and the client theme. The supported baseline stays MiniMax Code 3.1.6: both additions are feature-detected and need no new access. +- **Chats:** choose a project to see its unarchived desktop chats, then read the latest reply and live activity. Continue a chat in the main window with its original tools, or send a draft to the pet's bound chat after Host confirmation. Choose **+** to compose a new draft and hand it to MiniMax Code via the clipboard. Paste and send it in the main window to create the desktop chat. +- **Tasks:** the bell opens a stack above the pet. Click the stack to expand the cards, or use the arrow on a card to open its chat. Active cards show progress such as tool activity. The stop shortcut takes you to the running chat, where you can stop it. Completed cards animate in and out and dismiss individually after five seconds. An unread completion stays in the bell count across restarts until you view its reply. +- **Deliveries:** view image thumbnails in chat and open images, Markdown, and text files in a larger preview on Windows with Microsoft Edge. Closing the preview returns you to the same chat. Other formats can be viewed in the main window. +- **Quota:** the ring shows the five-hour remaining percentage for the signed-in MiniMax account. The details show the five-hour and weekly limits. +- **Appearance:** choose a bundled pet or import an atlas. The mint robot remains the default. The five included appearances are the mint robot, MiniMax Code 章鱼娘, 麦芽糖, MMX 章鱼娘, and 潮音 · MiniMax 老师 (Chao Yin). The pet can blink and briefly follow the nearby pointer when its atlas supports these poses. Language, theme, pet size, and error-card timing are available in the panel. See [artwork and attribution](ARTWORK.md). ## Install and open -1. Copy the entire `plugins/minimax-ai/minimax-pet/` directory, including `.minimax-plugin`, into `/plugins/minimax-pet/`. The default data directory is `~/.minimax`; use your configured directory if different. The `minimax-ai` author directory is not part of the installed path. -2. Restart MiniMax Code and confirm the plugin is enabled. -3. Open “MiniMax Pet” from the MiniApp list, or ask the Agent “打开 MiniMax Pet”. -4. Choose **放到桌面** to show the desktop pet. - -To update, close the app and exit the client before replacing the complete package. Keep backups outside the client's plugins directory. Imported pets and preferences are stored separately in the Host-assigned plugin data directory. - -Earlier local prototypes use a different plugin ID. The Host gives `minimax-pet` its own data directory; importing the new package does not automatically move an older plugin's pets or preferences. Keep any existing installation/data until you have exported what you need. +1. Copy the entire `plugins/minimax-ai/minimax-pet/` folder, including `.minimax-plugin`, to `/plugins/minimax-pet/`. The default data directory is `~/.minimax`. +2. Open MiniMax Pet from MiniMax Code and choose **Put on desktop** from the pet panel. Use the appearance, task, and settings tabs in the panel to configure it. ## Tested environment -- MiniMax Code **3.1.6 or later** is the supported baseline. On 2026-10-26, the official [mainland China](https://filecdn.minimax.chat/public/minimax-agent-prod/release/latest-mac.yml) and [Global](https://file.cdn.minimax.io/public/minimax-agent-prod/release/latest-mac.yml) production update feeds both listed 3.1.6. The corresponding release implementation was checked for the required APIs. This establishes a released API baseline, not GUI acceptance of this plugin on that release. -- Task monitoring uses `agent.sessions`, `agent.session`, `agent.observe`, and `agent.cancel` with the `session.read` grant. Runtime capability and permission checks remain in place; missing APIs or disabled access are reported as unavailable. -- **打开对话** / **去回答** uses `host.navigation.open` and the theme uses `host.ui.subscribe`, both added in MiniMax Code **3.1.11**; on 2026-11-10 the macOS and Windows installers of 3.1.11 answered on both production CDNs. Both calls were checked against the MiniMax Code source: opening a conversation the Mini App already holds needs no `hostAccess` and no extra grant, must start inside a click, and brings the main window forward. -- An earlier UI version was exercised on macOS in a MiniMax Code development build: three tabs, wide/narrow layouts, task reading, real session/ask activity, import/delete, and desktop round trips. Version 0.6.0 has Node/DOM tests (including the open and theme paths against a simulated Host), an isolated HTTP smoke test, and a browser check of the panel layout outside the Host. -- The default atlas is checked by actual PNG decoding, frame coverage and deterministic rebuild tests. The separate octopus icon is checked by PNG decoding and visual review. On 2026-10-26, the packaged Skill was exercised with a real Agent in the macOS development build to create, validate, preview and import a custom v2 pet; all nine animation previews and the four cardinal mouse-look directions were checked. This does not replace released-client acceptance. -- Version 0.9.0 has Node/DOM tests for the card timer, the preference round trip and the copy of both languages (every key the page uses must exist in both), plus a browser check of the panel and desktop window in both languages against a simulated Host. Not verified for 0.9.0: the language the real client reports on any given install, and both languages inside a real MiniMax Code window. -- Version 0.9.2 was checked in MiniMax Code **3.1.19.232** on Windows 11 x64 (build 26200, 150% display scaling). With the task card open, four automated pointer drags moved the real window without cumulative width or height growth. A physical mouse and other display configurations were not tested for this fix. -- The drag behavior was exercised with a physical mouse in a local comparison build on MiniMax Inside Code **3.1.19.169**, Windows 11 (build 26300), and a 4K display. Version 0.9.3 has regression tests for input before and after the Host applies a pending move. Desktop testing of the final 0.9.3 package remains open. -- A pre-rebase build of the pop-out fix was checked in MiniMax Code **3.1.19.232** on Windows 11 x64 (build 26200, 150% display scaling). The old saved position clipped the pet at the top of the screen; the patched app brought it fully inside the work area and saved the corrected position. Secondary and disconnected displays were exercised in automated tests, not on physical displays. -- Not verified for 0.6.0: opening a conversation or following the theme inside a real MiniMax Code 3.1.11+ window (panel or desktop pet), any Windows GUI, and released-client installation or GUI acceptance on 3.1.6. Automated tests use synthetic data and do not prove those paths. +- The manifest's API baseline is MiniMax Code **3.1.6**. Chat navigation and Host theme/language detection use APIs available from **3.1.11**. Desktop selection and deliveries also depend on the current local desktop database and a Host Node runtime with `node:sqlite`. +- The 0.10.0 package was checked on Windows with Node.js 26 using synthetic session, quota, and preview data. A local precursor was exercised in the Windows desktop client. This exact version has not been reinstalled for live account or GUI acceptance. macOS and Linux floating windows were not re-tested. +- The earlier Windows drag fix and Chao Yin atlas were checked with MiniMax Code **3.1.19.232** on Windows 11 x64. Independent preview windows are available on Windows with Edge. ## Data & access -- **Conversation data:** requests only `session.read`. Reads visible user-conversation metadata, status and a selected conversation's latest reply through the public Host API. It does not read the Host database, logs, configuration, credentials or private files. Conversation state and reminders stay in page memory. -- **Observations:** one global observer aggregates visible task lifecycle events. Up to three detailed observers follow active tasks and detect new ask tool events. A completed/removed task releases its detailed slot; another task enters only after the previous subscription settles. The initial snapshot contains up to 50 recent visible conversations; observed tasks remain while the Host confirms visibility. -- **Coverage limits:** observers are tail-only. They cannot reconstruct questionnaires opened before subscribing or during a disconnect. More than three active tasks means only three receive detailed ask coverage. No observed ask does not prove no pending question. Historical idle tasks are not presented as newly completed. -- **Local files:** the Node service serves packaged assets and stores preferences and user-imported JSON/WebP/PNG spritesheets under opaque `context.dataDir`. Imports, replacement recovery and deletion are limited to that plugin data. Browser storage is used only to migrate old view preferences. -- **Rendered replies:** the latest reply is parsed as Markdown by the vendored parser and rebuilt as DOM nodes under the page's own stylesheet. Raw HTML in a reply is displayed as literal text, never executed or inserted as markup; links show their target on hover and are not opened; images are not fetched and appear as a text label. -- **Host navigation:** only when you click **打开对话** or **去回答**, the page calls `host.navigation.open({ id: 'session', sessionId, source: 'local' })` for a conversation it already lists through `session.read`. It does not declare `hostAccess` and never reads which page of MiniMax Code you are on. It writes nothing to chat inputs and sends no message. -- **Display preferences:** `host.ui.subscribe` reports the client theme and interface language; the page applies the theme and, while the language setting is **Follow MiniMax Code**, the language. Choosing 简体中文 or English overrides it. The preference is stored with the other settings in the plugin data directory. No grant is involved. -- **Network:** the plugin has no hard-coded external runtime endpoint; its own HTTP requests use its assigned loopback origin. -- **Microphone, camera and notifications:** not used and not declared. -- **Processes and Agent turns:** the Host starts one Node process. The plugin spawns no additional runtime process, launches no shell command, offers no MCP server, and never calls `agent.run`. - -## Agent Skill - -The `minimax-pet` Skill opens the app and guides the current Agent through creating custom pet artwork. It includes exact v1/v2 dimensions, animation and look layouts, alpha and metadata requirements, and a self-contained Node PNG validation tool. Files stay in the user workspace until import is confirmed; this does not add automatic Agent runs to the MiniApp. - -## Bundled artwork - -Four pets are bundled. The default is the MiniMax Pet mint robot, whose atlas can be regenerated with Node.js from the source directory. The second is “MiniMax Code 章鱼娘” (`minimax-tako`), a pink-haired octopus girl generated with MiniMax image generation and assembled into the v2 atlas, and the third is 麦芽糖 (`octopus-girl-v2`). The fourth is “MMX 章鱼娘” (`mmx-octopus`), a contributed character that ships the v1 atlas: all nine animation rows and no look directions. The purple octopus plugin icon is a separate imagegen asset and is preserved when regenerating the atlas. See [ARTWORK.md](ARTWORK.md). - -Version **0.5.10** also includes **Maiyatang (麦芽糖)**, an optional coral-pink chibi octopus girl. Select her in **外观 → 选择宠物**; the mint robot remains the default. She has all nine animation states and sixteen look poses in the existing v2 format. Her Chinese self-introduction appears under the preview. She uses the existing player timing, including the slow six-frame idle cycle, without new permissions or runtime behavior. The atlas was validated and imported through the local plugin UI on Linux; this does not establish bundled-install or desktop-window acceptance on released clients. See [ARTWORK.md](ARTWORK.md) for the AI-generation workflow and contributor license. - -## Development - -The complete editable source is at `sources/minimax-ai/minimax-pet/`. The installable package is self-contained at `plugins/minimax-ai/minimax-pet/`. See [PROVENANCE.md](PROVENANCE.md) for build and byte-comparison steps; developer notes and tests stay outside the distributed runtime payload. - -## License +- **Conversations:** `session.read` lists visible chats, reads selected replies, and observes task and tool activity. One aggregate observer watches recent chats, with up to three detailed live observers. The plugin does not run Agent turns or call tools. `message.append` hands a draft to the pet's own chat after the Host asks for confirmation. New drafts are written to the clipboard only on submission. `host.navigation.open` jumps to a known chat or project, and `host.ui.subscribe` follows theme and language. The plugin does not read the current Host page. +- **Desktop metadata and deliveries:** the Node service opens `v2/sqlite/runtime-state.sqlite` read-only under `MINIMAX_DATA_DIR`, `MINIS_MAX_DATA_DIR`, `MAVIS_DATA_DIR`, or `~/.minimax`. It uses project visibility, archive status and delivery metadata. The file layout and schema are not public Host APIs. A delivery must be indexed for a visible desktop chat, have a supported type, and resolve inside that chat's workspace. The preview serves the file locally. Markdown is rendered as DOM nodes, and reply HTML is displayed as text. +- **Quota:** the Node service looks for `auth/**/auth.json` under the configured MiniMax data root (`MINIS_MAX_DATA_DIR`, `MAVIS_DATA_DIR`, `MINIMAX_DATA_DIR`, `DATA_DIR`, or `~/.minimax`). It sends the account bearer token only to the MiniMax services at `agent.minimax.cn` and `www.minimaxi.com` to query the subscription. The page receives status, plan tier, remaining quota, and reset times. +- **Storage and processes:** preferences, imported atlases, unread session IDs, titles and short previews, read markers, and the Edge preview profile stay under `context.dataDir`. The page talks to the Node service over the Host-assigned loopback origin. Windows uses `powershell.exe -NoProfile -NonInteractive -EncodedCommand` for the bundled native drag helper, which stops with the plugin. It opens `msedge.exe` in app mode using a separate profile when you request a preview. Close the preview to close that window. +- **Devices:** the plugin uses no microphone, camera, or system notifications. -Original code, documentation, the robot, minimax-tako pet and icon: [MIT](LICENSE), Copyright 2026 MiniMax. Maiyatang artwork: MIT, Copyright 2026 Fectivnfy112357. The minimax-tako atlas was generated with MiniMax image generation. The default atlas is generated from editable geometric drawing code; the octopus icon and Maiyatang were generated with imagegen from supplied visual references. See [ARTWORK.md](ARTWORK.md). No externally sourced pet spritesheet is bundled. User-imported artwork keeps its own license. +## Development and license -`miniapp/client/vendor/markdown.mjs` bundles 59 MIT-licensed packages from the unified, remark-parse and remark-gfm dependency trees. Each package keeps its own copyright notice in `miniapp/client/vendor/markdown.LICENSE.txt`, which `npm run build:markdown` regenerates from the packages esbuild actually includes. +The `minimax-pet` Skill includes the v1/v2 atlas format and a Node.js validation tool. See [PROVENANCE.md](PROVENANCE.md) for package and development checks, [ARTWORK.md](ARTWORK.md) for artwork credits, and [LICENSE](LICENSE) for the MIT terms. diff --git a/sources/minimax-ai/minimax-pet/README.zh-CN.md b/sources/minimax-ai/minimax-pet/README.zh-CN.md index fcb087cb..39ca3a7a 100644 --- a/sources/minimax-ai/minimax-pet/README.zh-CN.md +++ b/sources/minimax-ai/minimax-pet/README.zh-CN.md @@ -2,80 +2,33 @@ [English](README.md) | 简体中文 -作者:**MiniMax**。围绕主窗口可见会话提供轻量陪伴、任务状态与通知,界面提供“外观/任务/设置”三个页签。 +MiniMax Pet **0.10.0** 是 MiniMax Code 的桌宠。鼠标移到桌宠附近或用键盘聚焦快捷栏,即可打开会话、查看 MiniMax 订阅额度或浏览任务动态。 -## 使用 +- **会话** 先选项目,再从桌面端未归档的会话中查看最新回复和实时进度。可回到主窗口继续使用原会话的工具。给与桌宠绑定的会话写草稿时,由宿主确认交接。点 **+** 可以在桌宠写新会话草稿并交给主窗口,粘贴并发送后创建桌面会话。 +- **任务** 点铃铛查看桌宠头顶的卡片叠层,再点叠层展开。运行中的卡片会显示调用工具等进度。点箭头可打开对应会话,停止快捷键会定位到主窗口的运行中会话。每条完成提醒有弹出和收起动画,显示五秒后独立收起。未查看记录会在重开桌宠后保留,查看对应回复后再消除。 +- **交付物** 会话内显示图片缩略图。Windows 安装了 Microsoft Edge 时可在独立窗口查看大图、Markdown 和文本。关掉预览即可回到刚才的会话。其他格式可以回主窗口查看。 +- **额度** 圆环展示 MiniMax 订阅五小时剩余额度,展开后同时显示五小时和每周的用量周期。 +- **外观** 支持选择内置桌宠或导入图集。内置薄荷机器人、MiniMax Code 章鱼娘、麦芽糖、MMX 章鱼娘和「潮音 · MiniMax 老师」,默认是薄荷机器人。支持相应姿势的图集可眨眼和短暂看向附近指针。面板可调整尺寸、语言、主题跟随和异常提醒时长。详见[素材及署名](ARTWORK.md)。 -将仓库 `plugins/minimax-ai/minimax-pet/` 完整复制到 `/plugins/minimax-pet/`,包括隐藏的 `.minimax-plugin`;默认 `` 为 `~/.minimax`,自定义数据目录时采用实际配置。不要复制外层作者目录。重启 MiniMax Code、确认插件启用后,从 MiniApp 列表打开“MiniMax Pet”,或对 Agent 说“打开 MiniMax Pet”。点击“放到桌面”显示透明桌宠窗口。 +## 安装和打开 -外观页支持选择、导入预览和删除已导入宠物;任务页显示提醒、全部可见任务和按 Markdown 渲染的最近回复;设置页提供大小、语言、通知时长、提醒管理和重连。 +1. 将整个 `plugins/minimax-ai/minimax-pet/` 目录(含 `.minimax-plugin`)复制到 `/plugins/minimax-pet/`。默认数据目录为 `~/.minimax`。 +2. 在 MiniMax Code 打开 MiniMax Pet,从面板选择「放到桌面」。在面板的「外观」「任务」和「设置」中配置桌宠。 -面板和桌面文案在 MiniMax Code 3.1.11 及以上跟随客户端界面语言;客户端不报告语言时跟随系统语言,也可以在设置页固定为简体中文或 English。旧版本客户端跟随系统语言。桌面通知最多预览五行,点击后可滚动读完整内容,桌宠保持可见。观察到 ask 时显示“需要你回答”。 +## 测试环境 -在 MiniMax Code 3.1.11 及以上版本,面板和桌面上的任务详情都有“打开对话”按钮,任务需要回答时显示为“去回答”;点一下会把 MiniMax Code 主窗口切到这个对话。面板和桌面卡片的明暗也跟随 MiniMax Code 的主题。旧版本客户端不显示该按钮,明暗跟随系统设置。 +- 插件清单的接口基线为 MiniMax Code **3.1.6**。会话跳转及主题、语言跟随使用 **3.1.11** 起提供的接口。桌面会话筛选和交付物依赖当前桌面数据库结构,以及带 `node:sqlite` 的宿主运行时。 +- 0.10.0 在 Windows 与 Node.js 26 上使用模拟会话、额度和预览数据验证。此版本的本地前身在 Windows 桌面端试用过。本次打包版尚未重新安装验收真实账户和桌面交互,也未重新测试 macOS 或 Linux 悬浮窗。 +- 较早的拖动修复和「潮音」图集已在 Windows 11 x64 与 MiniMax Code **3.1.19.232** 上验证。独立预览窗需要 Windows 和 Edge。 -**0.5.10** 新增可选内置宠物 **麦芽糖**,是一位珊瑚粉触手长发的 Q 版全身章鱼娘。在“外观 → 选择宠物”中选择她,预览下方会显示她的自述;薄荷色机器人仍为默认宠物。麦芽糖采用现有 v2 图集,包含九种动作和十六个视线方向,沿用六帧、6.6 秒一轮的慢速待机,不新增权限或改变播放器。图集已通过校验,并在 Linux 的本地插件界面完成导入和选择;这不代表正式客户端的 bundled 安装或透明桌面窗口已验收。AI 创作流程和贡献者许可见[素材说明](ARTWORK.md)。 +## 数据与访问 -**0.5.11** 新增可选内置宠物 **MMX 章鱼娘**,是一位橙发、白背心、棕格纹短裙的 Q 版全身章鱼娘。在“外观 → 选择宠物”中选择她即可;薄荷色机器人仍为默认宠物。她采用 v1 图集,包含九种动作,不含十六个视线方向,因此鼠标跟随对她不生效;沿用六帧、6.6 秒一轮的慢速待机,不新增权限或改变播放器。图集已通过校验。创作流程和贡献者许可见[素材说明](ARTWORK.md)。 - -**0.9.0** 新增两项设置。“任务通知”用数字框设置桌面卡片在任务完成或异常后显示多少秒,默认 10 秒,填 0 表示一直显示到手动关闭;设置保存在本机。卡片自动收起不会把任务标记为已读,需要你回答的卡片不会自动收起,鼠标悬停或焦点停留时会暂停计时。“语言”默认跟随 MiniMax Code 的界面语言,也可以固定为简体中文或 English;面板和桌面文案整体切换,对话标题和回复保持 Agent 原文。 - -**0.9.0** 把桌面窗口固定成一个尺寸,本来就放得下展开的卡片。之前点开卡片会把窗口撑高,窗口在屏幕上跟着移动,桌宠会跳一下;现在开合卡片只显示或隐藏,不动窗口。桌宠上方是透明区域,点击会穿透到底下的窗口。 - -**0.9.2** 拖拽时同时发送坐标与当前缩放对应的窗口尺寸,不再沿用宿主异常放大的尺寸。桌面任务卡居中,宽度上限为 264 CSS 像素;窗口较窄时仍会缩小并保留两侧各 8 像素的留白。权限和依赖不变。 - -**0.9.3** 根据宿主确认的窗口位置和指针相对抓取点的偏移移动桌宠。每次移动结束后,才使用新的指针事件。如果在宿主应答前松手,窗口停在宿主最后接受的位置。 - -**0.9.5** 新增社区桌宠外观「潮音 · MiniMax 老师」,可在外观设置中选用,包含 9 种动作和 16 个注视方向。 - -**0.9.4** 修复点击“放到桌面”后宠物可能落到屏幕外的问题。先尝试恢复上次的位置,再按窗口实际落在哪块屏幕校正;副屏上的合法位置不会被移回主屏。如果窗口比可用区域更高,优先让窗口底部的宠物留在屏幕上。 - -**0.8.1** 修复桌面卡片:标题单行截断,只有回复区滚动,底部操作固定在卡片内;长标题或长回复不再把「返回任务 / 打开对话」顶出卡片。展开卡片时窗口同步变高,回复不会被压成一行。 - -**0.8.0** 按 MiniMax Code 的设计语言对齐面板:24px 页边距与区块间距、14px/22px 正文与 12px/18px 辅助文字、控件最小高度 32px、卡片 12px 与控件 8px 圆角、桌面浮层 0.5px 描边,并补齐按下与焦点状态。桌面宠物保持 280px 布局,沿用同一套 token。 - -**0.7.0** 把任务最近回复按 Markdown 渲染:标题、强调、列表、任务清单、代码块、表格、引用和链接;回复里的原始 HTML 只作为文本显示,图片显示为文字标签而不发起网络请求。通知卡片和提醒预览仍为纯文本。解析使用 `npm run build:markdown` 打包的 unified + remark-parse + remark-gfm(MIT);页面不会把模型输出拼成 HTML 字符串。 - -**0.6.0** 删除了菜单和外观页里的“打招呼”“跳一下”,删除了原属聊天草稿及其语音输入,不再申请麦克风权限;新增“打开对话/去回答”和主题跟随。支持基线仍为 MiniMax Code 3.1.6:两项新功能都先检测客户端能力,不需要新增权限。 - -旧的本地原型使用不同插件 ID。`minimax-pet` 会有独立的 Host 数据目录,安装本包不会自动搬迁旧插件的宠物和偏好;需要的素材先导出,保留旧安装和数据。 - -## 环境与兼容 - -本包支持 MiniMax Code **3.1.6 及以上版本**。2026-10-26 核对的[中国大陆](https://filecdn.minimax.chat/public/minimax-agent-prod/release/latest-mac.yml)与 [Global](https://file.cdn.minimax.io/public/minimax-agent-prod/release/latest-mac.yml) 正式更新清单均为 3.1.6,并已核对同版本发行实现包含所需接口。这确认了正式发布的 API 基线,不代表本插件已在该正式客户端完成 GUI 验收。 - -任务监控使用 `agent.sessions/session/observe/cancel`,需要 `session.read` 授权。保留运行时能力和权限检查,缺少接口或关闭授权时显示不可用。“打开对话/去回答”使用 `host.navigation.open`,主题跟随使用 `host.ui.subscribe`,两者都从 MiniMax Code **3.1.11** 起提供;2026-11-10 已确认 3.1.11 的 macOS 与 Windows 安装包在两个正式 CDN 上均可下载。两项调用已对照 MiniMax Code 源码核对:打开插件已持有的会话不需要 `hostAccess` 或其他授权,必须在点击中发起,并会把主窗口带到前台。 - -更早的 UI 版本已在 macOS 开发版验收三页签、窄宽布局、真实任务与 ask、导入删除和桌面切换;0.6.0 运行 Node/DOM 测试(含模拟 Host 下的打开对话与主题路径)、隔离 HTTP smoke,并在 Host 之外用浏览器检查了面板布局。默认图集通过 PNG 解码、动画帧覆盖与确定性重建检查;独立的章鱼图标通过 PNG 解码和视觉检查。2026-10-26,已用 macOS 开发版中的真实 Agent 调用随包 Skill,完成自定义 v2 宠物的生成、校验、预览和导入,并检查九种动作预览与鼠标上/右/下/左四向注视。0.6.0 尚未在真实的 MiniMax Code 3.1.11+ 窗口(面板或桌面宠物)中验收打开对话和主题跟随,也未验收 Windows GUI、正式客户端安装或 3.1.6 正式版 GUI;合成数据测试不能证明这些路径。 - -0.9.2 已在 Windows 11 x64(构建 26200,屏幕缩放 150%)的 MiniMax Code **3.1.19.232** 中测试。任务卡展开时通过自动化指针连续拖拽四次,真实窗口发生位移,宽高未逐次累加。此修复未测试物理鼠标及其他显示配置。 - -本地对照构建已在 Windows 11(构建 26300)、4K 显示器和 MiniMax Inside Code **3.1.19.169** 下用物理鼠标测试。0.9.3 的回归测试覆盖宿主应用窗口移动前后到达的指针事件。0.9.3 正式打包版本仍待桌面验收。 - -弹出修复在本次 rebase 前已用 Windows 11 x64(构建 26200,屏幕缩放 150%)和 MiniMax Code **3.1.19.232** 测试。旧保存位置会让宠物在屏幕上沿被裁切,修复版把宠物完整移进工作区并保存校正位置。副屏及屏幕断开场景只做了自动化测试,未连接实际副屏测试。 - -## 数据与能力边界 - -只申请 `session.read`,读取 Host 对本插件可见的用户会话状态和所选会话最新回复,不直接读取 Host 数据库、日志、配置或凭据。状态和提醒只在页面内存中,关闭或静音不修改 Host 的任务或未读事实。 - -全局观察聚合可见任务,初始快照至多 50 条;本连接已观察到、Host 仍确认可见的任务会继续保留。另三个详细观察名额监听活跃会话的 ask,任务结束或移除后取消,等待旧订阅真正结束再补位。详细观察是 tail-only,不能补回订阅前或断线期间的问卷;超过三个活跃任务时,只覆盖其中三个的详细事件。没有观察到 ask 不等于没有待答问卷。 - -偏好和用户导入素材写入独立的 `context.dataDir`;导入替换有中断恢复,删除限于本插件数据。不创建独立聊天、不写入聊天输入框、不逐会话点评、不自动调用模型、不发送或停止用户会话、不代答问卷。 - -回复由随包 vendor 的解析器转为 Markdown 结构,再在页面里用 DOM 节点重建:原始 HTML 只按文本显示,不会插入页面或执行;链接只显示地址不打开;图片不请求,只显示文字标签。 - -只有在你点击“打开对话”或“去回答”时,页面才调用 `host.navigation.open({ id: 'session', sessionId, source: 'local' })`,目标是已通过 `session.read` 列出的会话。未声明 `hostAccess`,不读取你在 MiniMax Code 里停留的页面。`host.ui.subscribe` 只用来读取并应用主题,返回的语言不使用,无需授权。不使用也不声明麦克风、摄像头或系统通知。插件本身没有硬编码的外部服务地址,只使用分配的 loopback 源,不启动额外子进程或 shell。 - -## Agent Skill - -随包的 `minimax-pet` Skill 既能打开插件,也能指导当前 Agent 制作、校验和导入自定义宠物。格式文档列出 v1/v2 的精确尺寸、逐帧布局、透明背景、视线方向和 `pet.json`,并附带无外部依赖的 PNG 校验脚本。生成文件先放在用户工作区,再通过界面确认导入;MiniApp 不自行启动模型。 +- **会话** 用 `session.read` 列出可见会话,读取所选回复并监听任务及工具进度。全局监听聚合近期会话,最多同时详细监听三个任务。插件不会发起 Agent 回合或调用工具。`message.append` 经宿主确认后把草稿交给绑定的会话,新会话草稿仅在提交时写入剪贴板。`host.navigation.open` 跳转到已知会话或项目,`host.ui.subscribe` 获取主题和语言,桌宠不读取宿主当前页面。 +- **桌面数据和交付物** 在 `MINIMAX_DATA_DIR`、`MINIS_MAX_DATA_DIR`、`MAVIS_DATA_DIR` 或 `~/.minimax` 下只读打开 `v2/sqlite/runtime-state.sqlite`,检查项目是否在侧栏、会话是否归档以及交付物的索引。这个目录结构和数据表依赖客户端实现。只有可见会话中已记录、格式受支持且真实路径在会话工作区内的文件可在本地预览。回复中的 HTML 按文字显示。 +- **额度** Node 在配置的 MiniMax 数据目录(`MINIS_MAX_DATA_DIR`、`MAVIS_DATA_DIR`、`MINIMAX_DATA_DIR`、`DATA_DIR` 或 `~/.minimax`)查找 `auth/**/auth.json`,只向 MiniMax 自己的 `agent.minimax.cn` 和 `www.minimaxi.com` 发送账号令牌查询订阅。页面仅收到状态、套餐级别、剩余额度和重置时间。 +- **存储和进程** 偏好、导入图集、未读会话标识、标题和短预览、已读标记及 Edge 预览配置放在 `context.dataDir`。页面通过宿主分配的回环地址连接 Node。Windows 用 `powershell.exe -NoProfile -NonInteractive -EncodedCommand` 执行内置的拖动辅助代码,插件停止时关闭辅助进程。主动打开预览时以独立配置在 `msedge.exe` 的应用窗口中显示。 +- **设备** 不使用麦克风、摄像头和系统通知。 ## 开发与许可 -保留源码/分发双目录,构建与完整字节对比步骤见 [PROVENANCE.md](PROVENANCE.md)。原创代码、文档、两只内置宠物和图标均按 [MIT](LICENSE) 开源,作者为 MiniMax。默认的薄荷色机器人图集由可编辑的几何绘图代码生成;第二只内置宠物“MiniMax Code 章鱼娘”(`minimax-tako`)粉发、戴眼镜、酒红触手,由 MiniMax 图像生成根据用户提供的参考图绘制后拼成 v2 图集,无法用命令重新生成;紫色章鱼图标由 imagegen 根据用户提供的视觉参考生成,重新生成图集不会覆盖图标。详见[素材说明](ARTWORK.md);参考图和外部宠物图集不随包分发,用户自行导入的素材保留其各自许可。 - -`miniapp/client/vendor/markdown.mjs` 打包了 unified、remark-parse、remark-gfm 依赖树里 59 个 MIT 许可的包,各自的版权声明保留在 `miniapp/client/vendor/markdown.LICENSE.txt`,该文件由 `npm run build:markdown` 按 esbuild 实际打包的包清单生成。 - -麦芽糖素材由 Fectivnfy112357 贡献,同样采用 MIT 许可。麦芽糖通过 MiniMax 章鱼娘工坊工作流创作,使用 OpenAI imagegen 生成,再裁切、等比缩放和组装为透明图集;重新生成默认图集不会覆盖她。 - -MMX 章鱼娘素材由 antianqi 贡献,同样采用 MIT 许可。她通过本机部署的开源扩散模型出图与出视频,再由本地脚本抽帧、抠透明、落格拼成 v1 图集,无法用命令重新生成;重新生成默认图集不会覆盖她。 +随包的 `minimax-pet` Skill 包含 v1/v2 图集格式和 Node.js 校验工具。打包与检查见 [PROVENANCE.md](PROVENANCE.md),素材署名见 [ARTWORK.md](ARTWORK.md),许可见 [LICENSE](LICENSE)。 diff --git a/sources/minimax-ai/minimax-pet/dev/blink.test.mjs b/sources/minimax-ai/minimax-pet/dev/blink.test.mjs new file mode 100644 index 00000000..d0cc2a50 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/blink.test.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { SpritePlayer } from '../miniapp/client/pet-player.js'; + +test('the installed Chao Yin atlas closes and opens its lids in about 145 ms without changing gaze frame', (t) => { + const previous = globalThis.document; + globalThis.document = { hidden: false, addEventListener() {}, removeEventListener() {} }; + t.after(() => { globalThis.document = previous; }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + const overlay = { setAttribute() {}, remove() {}, style: {} }; + const player = new SpritePlayer({ style: {}, append() {}, ownerDocument: { createElement: () => overlay } }); + player.setPet({ id: 'chao-yin-soundwave-teacher-smooth', version: 2, spriteUrl: '/fixture.png' }); + assert.equal(player._durations().slice(3).reduce((sum, value) => sum + value), 145); + player.look(90); + const frame = player.frame; + t.mock.timers.tick(3900); + assert.equal(overlay.hidden, false); + for (const ms of [42, 55, 48]) t.mock.timers.tick(ms); + assert.equal(overlay.hidden, true); + assert.deepEqual(player.frame, frame); + player.destroy(); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/compact-pet-view.test.mjs b/sources/minimax-ai/minimax-pet/dev/compact-pet-view.test.mjs index 1135ab23..c46aaadd 100644 --- a/sources/minimax-ai/minimax-pet/dev/compact-pet-view.test.mjs +++ b/sources/minimax-ai/minimax-pet/dev/compact-pet-view.test.mjs @@ -28,12 +28,12 @@ function harness(t, callbacks = {}) { return { dom, container, calls, view, button, update }; } -domTest('default is task notifications with no independent chat, form, draft or generic Host entry', (t) => { +domTest('default opens task notifications with the chat forms hidden', (t) => { const h = harness(t, { onSubmit: () => assert.fail('No free request'), onDraftChange: () => assert.fail('No free draft') }); assert.equal(h.view.opened, false); assert.equal(h.container.hidden, true); h.update({ draft: '旧的自由问答草稿', agentSnapshot: { text: '旧的独立聊天回复' } }); h.view.open(); assert.equal(h.view.opened, true); assert.equal(h.view.view, 'tasks'); - assert.equal(h.container.querySelector('textarea,input,form,[role=tab],h1,h2,fieldset'), null); + assert.ok([...h.container.querySelectorAll('textarea, input, form')].every((node) => node.closest('[hidden]'))); assert.deepEqual([...h.container.querySelectorAll('.compact-tasks .compact-footer button:not([hidden])')].map((node) => node.textContent), ['全部任务']); assert.equal(h.container.textContent.includes('旧的独立聊天回复'), false); for (const label of ['发送', '提问', '新对话', '主窗口', '点评这条会话', '查看点评详情', '停止点评']) assert.equal(h.button(label), undefined); @@ -222,11 +222,11 @@ domTest('legacy review state and callback arguments never create an entry or ren const h = harness(t, { onReviewTask: noCall, onCancelReview: noCall, onOpenReview: noCall }); h.update({ taskSelection: selection(1), reviewSnapshot: { target: { sessionId: 'task-1', title: '任务 1' }, text: '旧点评结果', busy: true, canOpen: true, canCancel: true } }); h.view.open(); - assert.equal(h.container.querySelector('[class*=review]'), null); + assert.ok([...h.container.querySelectorAll('[class]')].every((node) => ![...node.classList].some((name) => /(?:^|-)review(?:-|$)/u.test(name)))); assert.equal(h.container.textContent.includes('点评'), false); assert.equal(h.container.textContent.includes('旧点评结果'), false); assert.equal(h.view.open('review'), false); assert.equal(h.view.view, 'tasks'); h.view.open('detail'); - assert.equal(h.container.textContent.includes('点评'), false); assert.equal(h.container.querySelector('input,textarea,form'), null); + assert.equal(h.container.textContent.includes('点评'), false); assert.ok([...h.container.querySelectorAll('textarea, input, form')].every((node) => node.closest('[hidden]'))); assert.deepEqual(h.calls, []); }); @@ -234,7 +234,8 @@ domTest('close callbacks are explicit and reopening defaults to tasks without hi const h = harness(t); h.update({ taskSelection: selection(1) }); h.view.open('detail'); h.view.close(); assert.equal(h.view.opened, false); assert.deepEqual(h.calls, []); h.view.open(); assert.equal(h.view.view, 'tasks'); h.container.querySelector('.compact-close').click(); - assert.equal(h.view.opened, false); assert.deepEqual(h.calls, [['close']]); + assert.deepEqual(h.calls, [['close']]); + h.view.close(); assert.equal(h.view.opened, false); h.view.open(); assert.equal(h.view.opened, true); assert.equal(h.container.parentNode, h.dom.window.document.body); }); @@ -308,7 +309,10 @@ domTest('a markdown reply renders as structure in the detail, previews stay flat assert.equal(node.querySelector('strong').textContent, '留存'); assert.equal(node.querySelectorAll('.md-li').length, 2); assert.equal(node.querySelector('.md-pre code').textContent, 'const x = 1'); + h.view.open('tasks'); + assert.match(h.container.querySelector('.compact-task-preview').textContent, /留存 41%/u); assert.equal(h.container.querySelector('.compact-task-preview').textContent.includes('**'), false); + h.view.open('detail'); h.update({ taskSelection: { ...selection(1), session: { ...task(1), needsAnswer: true } } }); assert.equal(node.textContent, '需要你回答'); assert.equal(node.querySelector('.md-heading'), null); @@ -334,10 +338,13 @@ domTest('the desktop task card caps its width and keeps its side gutters', async // jsdom checks which declarations apply; it does not calculate layout dimensions. const style = dom.window.getComputedStyle(card); - assert.equal(style.maxWidth, '264px'); - assert.equal(style.marginInline, 'auto'); - assert.equal(style.left, '8px'); - assert.equal(style.right, '8px'); + assert.equal(style.width, '100%'); + assert.equal(style.gridArea, '1 / 1'); + assert.equal(card.parentElement.classList.contains('desk-lower'), true); + assert.match(css, /\.desk-lower\s*\{[^}]*width:\s*min\(100%,\s*264px\)/u); + const desk = dom.window.getComputedStyle(document.getElementById('desk')); + assert.equal(desk.paddingLeft, '8px'); + assert.equal(desk.paddingRight, '8px'); assert.equal(style.boxSizing, 'border-box'); }); diff --git a/sources/minimax-ai/minimax-pet/dev/completion-store.test.mjs b/sources/minimax-ai/minimax-pet/dev/completion-store.test.mjs new file mode 100644 index 00000000..ba7a8903 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/completion-store.test.mjs @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { createCompletionInbox } from '../miniapp/client/completion-inbox.mjs'; +import { createCompletionStore } from '../miniapp/node/completion-store.mjs'; + +const row = (sessionId, turnId, updatedAtMs) => ({ sessionId, turnId, updatedAtMs, title: sessionId, text: 'preview' }); + +test('unread survives restart and reading one turn never clears a later turn', async (t) => { + const directory = await mkdtemp(join(tmpdir(), 'pet-inbox-test-')); + t.after(() => rm(directory, { force: true, recursive: true })); + let store = createCompletionStore(directory); + await Promise.all([ + store.apply({ action: 'complete', row: row('a', 'turn-a', 1) }), + store.apply({ action: 'complete', row: row('b', 'turn-b', 2) }), + ]); + store = createCompletionStore(directory); + const inbox = createCompletionInbox(); + inbox.restore(await store.get()); + assert.deepEqual(inbox.rows.map((item) => item.sessionId), ['b', 'a']); + assert.equal(inbox.view('a', 'stale-turn'), undefined); + assert.equal(inbox.count, 2); + await store.apply({ action: 'complete', row: row('a', 'later', 3) }); + await store.apply({ action: 'view', sessionId: 'a', turnId: 'turn-a' }); + assert.equal((await store.get()).find((item) => item.sessionId === 'a').viewed, false); + await store.apply({ action: 'view', sessionId: 'a', turnId: 'later' }); + store = createCompletionStore(directory); + const after = createCompletionInbox(); + after.restore(await store.get()); + assert.deepEqual(after.rows.map((item) => item.sessionId), ['b']); + assert.equal((await store.get()).find((item) => item.sessionId === 'a').text, ''); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/desk-interactivity.test.mjs b/sources/minimax-ai/minimax-pet/dev/desk-interactivity.test.mjs index 4fc96555..f411ccd2 100644 --- a/sources/minimax-ai/minimax-pet/dev/desk-interactivity.test.mjs +++ b/sources/minimax-ai/minimax-pet/dev/desk-interactivity.test.mjs @@ -122,129 +122,81 @@ test('the card never resizes the window, and the fixed height always fits it', a } }); -function dragHarness(scale, screenMode = 'local') { - const updates = []; - const directions = []; - let nativeBounds = { x: -100, y: 160 }; - let pending; - const app = { mode: 'window', workbenchOpen: true, pet: {}, winPos: nativeBounds, oneShotToken: 0 }; - const state = () => ({ mode: 'window', window: nativeBounds }); +function dragHarness({ nativeStarted = true } = {}) { + const commands = [], directions = [], states = [], panels = [], errors = []; + const app = { mode: 'window', workbenchOpen: true, pet: {}, oneShotToken: 0 }; const context = vm.createContext({ - app, prefs: { scale }, DRAG_THRESHOLD: 4, DIRECTION_HYSTERESIS: 12, + app, DRAG_THRESHOLD: 4, DIRECTION_HYSTERESIS: 12, disposed: false, els: { sprite: { setPointerCapture() {}, hasPointerCapture: () => false, classList: { add() {}, remove() {} } } }, win: { - getState: async () => state(), - update: (patch) => { - assert.equal(pending, undefined, 'only one move reaches the Host at a time'); - updates.push({ ...patch }); - return new Promise((resolve, reject) => { pending = { patch, resolve, reject }; }); - }, + getState: async () => ({ mode: 'window', window: { x: -65, y: 178 } }), + update: () => assert.fail('native dragging must not write Host geometry'), }, - console: { warn() {}, debug() {} }, errCode: (error) => error.message, logError: () => () => {}, - callBridge: (run) => Promise.resolve(run()), - onWindowState: ({ window }) => { app.winPos = { x: window.x, y: window.y }; }, + requestDesktopDrag: async (action, offset) => { + commands.push(offset ? { action, ...offset } : { action }); + return nativeStarted; + }, + callBridge: (run) => Promise.resolve(run()), onWindowState: (state) => states.push(state), player: { play: async (direction) => { directions.push(direction); } }, - noteInteraction() {}, stopLook() {}, hideQuickbar() {}, refreshInteractivity() {}, - desiredAnimation: () => ({ state: 'idle' }), playOneShot() {}, openWorkbench() {}, + noteInteraction() {}, stopLook() {}, renderDeskShortcuts() {}, refreshInteractivity() {}, + desiredAnimation: () => ({ state: 'idle' }), applyActivity() {}, animationGate: null, + logError: () => (error) => assert.fail(error), t: (key) => key, + showTransient: (text) => errors.push(text), openWorkbench: (view) => panels.push(view), + }); + vm.runInContext(`${slice('function onSpritePointerDown(', 'function showTransient(')} + globalThis.api = { onSpritePointerDown, onSpritePointerMove, finishDrag, cancelDrag };`, context); + const pointer = (dx, dy) => ({ + pointerId: 1, button: 0, preventDefault() {}, clientX: 50 + dx, clientY: 70 + dy, + screenX: -50 + dx, }); - vm.runInContext(`${slice('const DESK_WIDTH', '// Saved positions')}\n${slice('function onSpritePointerDown(', 'function cancelDrag(')} - globalThis.api = { onSpritePointerDown, onSpritePointerMove, finishDrag };`, context); - const pointer = (dx, dy) => { - const x = -50 + dx; - const y = 230 + dy; - const clientX = x - nativeBounds.x; - const clientY = y - nativeBounds.y; - return { pointerId: 1, button: 0, preventDefault() {}, clientX, clientY, - screenX: screenMode === 'local' ? clientX : x, screenY: screenMode === 'local' ? clientY : y }; - }; context.api.onSpritePointerDown(pointer(0, 0)); - const apply = () => { nativeBounds = { ...pending.patch }; }; - async function settle(reject = false) { - const request = pending; - if (!reject) apply(); - pending = undefined; - if (reject) request.reject(new Error('not_permitted')); - else request.resolve(state()); - await app.dragMove; - } - return { app, updates, directions, apply, settle, + return { + app, commands, directions, states, panels, errors, cancel: context.api.cancelDrag, move: (dx, dy) => context.api.onSpritePointerMove(pointer(dx, dy)), - release: (dx, dy) => context.api.finishDrag(pointer(dx, dy), false) }; + release: (dx, dy) => context.api.finishDrag(pointer(dx, dy), false), + }; } -test('desktop drag gives the Host absolute position and the same size on every move', async () => { - // A position-only request was followed by growing native bounds on Windows. The page must - // keep requesting the designed size, not feed back whatever bounds the Host last reported. - for (const [scale, height] of [[0.5, 436], [0.75, 488], [1, 540]]) { - const h = dragHarness(scale); - h.move(1, 1); // Below the click/drag threshold. - assert.deepEqual(h.updates, []); - h.move(35, 18); - await h.settle(); - h.app.winBounds = { width: 975, height: 1090 }; - h.move(-22, -10); - await h.settle(); - assert.deepEqual(h.updates, [ - { x: -65, y: 178, width: 280, height }, - { x: -122, y: 150, width: 280, height }, - ]); - assert.equal(h.app.workbenchOpen, true); - } +test('desktop drag starts once at the grab threshold and never sends repeated geometry', async () => { + const h = dragHarness(); + h.move(1, 1); + assert.deepEqual(h.commands, []); + h.move(35, 18); + h.move(60, 18); + h.move(-22, -10); + h.release(-22, -10); + await Promise.resolve(); + assert.deepEqual(h.commands, [{ action: 'drag', dx: 35, dy: 18 }]); + assert.deepEqual(h.directions, ['running-right', 'running-left']); + assert.deepEqual(h.states, [{ mode: 'window', window: { x: -65, y: 178 } }]); + assert.equal(h.app.drag, null); + assert.deepEqual(h.panels, []); }); -test('a drag cannot send its size while an intentional scale change owns the window', () => { - const h = dragHarness(0.5); +test('a size change blocks drag movement and stops a running native drag', async () => { + const h = dragHarness(); h.app.scaleChanging = true; h.move(35, 18); - assert.deepEqual(h.updates, []); + assert.deepEqual(h.commands, []); + h.app.scaleChanging = false; + h.move(35, 18); + await h.cancel(); + assert.deepEqual(h.commands, [{ action: 'drag', dx: 35, dy: 18 }, { action: 'stop' }]); + assert.equal(h.app.drag, null); + assert.equal(h.app.dragging, false); }); -for (const screenMode of ['local', 'absolute']) { - test(`a held pointer does not resend the same position (${screenMode} screenX)`, async () => { - const h = dragHarness(0.75, screenMode); - h.move(30, 20); - await h.settle(); - h.move(30, 20); - h.move(30, 20); - assert.deepEqual(h.updates, [{ x: -70, y: 180, width: 280, height: 488 }]); - assert.deepEqual(h.directions, ['running-right']); - }); -} - -for (const applied of [false, true]) { - const phase = applied ? 'after the Host moves but before its reply' : 'before the Host moves'; - test(`a pointer move ${phase} is not replayed against a different origin`, async () => { - const h = dragHarness(0.75); - h.move(30, 0); - if (applied) h.apply(); - h.move(60, 0); - await h.settle(); - assert.deepEqual(h.updates.map(({ x }) => x), [-70]); - h.move(60, 0); - await h.settle(); - assert.deepEqual(h.updates.map(({ x }) => x), [-70, -40]); - }); - - test(`releasing ${phase} keeps the last Host-confirmed target`, async () => { - const h = dragHarness(0.75); - h.move(30, 0); - if (applied) h.apply(); - h.release(60, 0); - await h.settle(); - assert.deepEqual(h.updates.map(({ x }) => x), [-70]); - assert.deepEqual(h.app.winPos, { x: -70, y: 160 }); - assert.equal(h.app.drag, null); - }); -} +test('clicking the sprite opens chat without starting a native drag', () => { + const h = dragHarness(); + h.move(1, 1); + h.release(1, 1); + assert.deepEqual(h.commands, []); + assert.deepEqual(h.panels, ['chat']); +}); -test('a rejected move keeps the confirmed origin for the final release', async () => { - const h = dragHarness(0.75); - h.move(30, 0); - await h.settle(); - h.move(60, 0); - await h.settle(true); - h.release(10, 0); - await h.settle(); - assert.deepEqual(h.updates.map(({ x }) => x), [-70, -40, -90]); - assert.deepEqual(h.directions, ['running-right', 'running-left']); +test('failed native drag startup is reported during the gesture', async () => { + const h = dragHarness({ nativeStarted: false }); + h.move(35, 18); + await Promise.resolve(); + assert.deepEqual(h.errors, ['mode.positionFailed']); }); diff --git a/sources/minimax-ai/minimax-pet/dev/desktop-catalog.test.mjs b/sources/minimax-ai/minimax-pet/dev/desktop-catalog.test.mjs new file mode 100644 index 00000000..27937ff1 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/desktop-catalog.test.mjs @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import test from 'node:test'; +import { readDesktopAsset, readDesktopCatalog } from '../miniapp/node/desktop-catalog.mjs'; + +async function createCatalog(t) { + const root = await mkdtemp(join(tmpdir(), 'pet-catalog-test-')); + t.after(() => rm(root, { force: true, recursive: true })); + const location = join(root, 'v2', 'sqlite'); + await mkdir(location, { recursive: true }); + const db = new DatabaseSync(join(location, 'runtime-state.sqlite')); + db.exec(` + CREATE TABLE local_runtime_projects (project_id INTEGER, workspace_dir TEXT, display_name TEXT, hidden INTEGER, + project_kind TEXT, listed_at_ms INTEGER, pinned INTEGER, order_index INTEGER, recent_at_ms INTEGER, extra_data_json TEXT); + INSERT INTO local_runtime_projects VALUES (1,'D:/project','Listed',0,'workspace',1,0,1,1,'{}'), + (2,'C:/unlisted','Unlisted',0,'workspace',NULL,0,2,2,'{}'), + (3,'C:/removed','Removed',0,'workspace',1,0,3,3,'{"sidebarRemoval":{"atMs":1,"boundaryIds":[]}}'), + (4,NULL,NULL,0,'default',1,0,4,4,'{}'); + CREATE TABLE local_runtime_sessions (session_id TEXT, project_id INTEGER, archived INTEGER, visibility TEXT, + session_kind TEXT, parent_session_id TEXT, origin_cron_id TEXT, extra_data_json TEXT, updated_at_ms INTEGER, is_default_workspace INTEGER); + INSERT INTO local_runtime_sessions VALUES ('desktop',1,0,'visible','conversation',NULL,NULL,'{}',1,0), + ('archived',1,1,'visible','conversation',NULL,NULL,'{}',2,0), + ('hidden',1,0,'hidden','conversation',NULL,NULL,'{}',3,0), + ('private',1,0,'visible','conversation',NULL,NULL,'{"miniAppOrigin":{}}',4,0), + ('child',1,0,'visible','conversation','desktop',NULL,'{}',5,0), + ('unlisted',2,0,'visible','conversation',NULL,NULL,'{}',6,0), + ('removed',3,0,'visible','conversation',NULL,NULL,'{}',7,0), + ('default',4,0,'visible','conversation',NULL,NULL,'{}',8,1), + ('incorrect-default',4,0,'visible','conversation',NULL,NULL,'{}',9,0); + ALTER TABLE local_runtime_sessions ADD COLUMN workspace_dir TEXT; + CREATE TABLE local_runtime_session_assets (session_id TEXT, path TEXT, role TEXT, source_tag TEXT, + asset_type TEXT, data_json TEXT, updated_at_ms INTEGER); + INSERT INTO local_runtime_session_assets VALUES + ('desktop','D:/project/image.jpg','assistant','deliver-assets','image','{"nodeId":"123"}',1), + ('archived','D:/project/archive.jpg','assistant','deliver-assets','image','{"nodeId":"123"}',1), + ('removed','C:/removed/image.jpg','assistant','deliver-assets','image','{"nodeId":"123"}',1), + ('desktop','D:/project/input.jpg','user','deliver-assets','image','{"nodeId":"124"}',1), + ('desktop','D:/project/report.md','assistant','deliver-assets','file','{}',1); + `); + db.close(); + return root; +} + +test('desktop catalog omits archived, hidden, private, child, and unlisted project sessions', async (t) => { + const root = await createCatalog(t); + const { sessions, projects } = await readDesktopCatalog([root]); + assert.deepEqual(sessions, [{ id: 'default', projectId: '4' }, { id: 'desktop', projectId: '1' }]); + assert.deepEqual(projects, [{ id: '1', path: 'D:/project', name: 'Listed' }, { id: '4', path: '', name: '' }]); +}); + +test('image delivery lookup requires a matching visible desktop session and assistant image', async (t) => { + const root = await createCatalog(t); + const image = await readDesktopAsset('desktop', { nodeId: '123' }, [root]); + assert.equal(image?.path, 'D:/project/image.jpg'); + assert.equal(image?.workspace, 'D:/project'); + for (const id of ['archived', 'removed', 'default']) { + assert.equal(await readDesktopAsset(id, { nodeId: '123' }, [root]), null); + } + assert.equal(await readDesktopAsset('desktop', { nodeId: '124' }, [root]), null); +}); + +test('file deliveries match only a registered path in the selected session', async (t) => { + const root = await createCatalog(t); + const file = await readDesktopAsset('desktop', { path: 'D:\\project\\report.md' }, [root]); + assert.equal(file?.path, 'D:/project/report.md'); + assert.equal(await readDesktopAsset('archived', { path: 'D:/project/report.md' }, [root]), null); + assert.equal(await readDesktopAsset('desktop', { path: 'D:/project/input.jpg' }, [root]), null); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/desktop-notices-expanded.png b/sources/minimax-ai/minimax-pet/dev/desktop-notices-expanded.png new file mode 100644 index 00000000..bb390e44 Binary files /dev/null and b/sources/minimax-ai/minimax-pet/dev/desktop-notices-expanded.png differ diff --git a/sources/minimax-ai/minimax-pet/dev/desktop-notices-stacked.png b/sources/minimax-ai/minimax-pet/dev/desktop-notices-stacked.png new file mode 100644 index 00000000..5f90472c Binary files /dev/null and b/sources/minimax-ai/minimax-pet/dev/desktop-notices-stacked.png differ diff --git a/sources/minimax-ai/minimax-pet/dev/minimax-quota.test.mjs b/sources/minimax-ai/minimax-pet/dev/minimax-quota.test.mjs new file mode 100644 index 00000000..9fabeb1d --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/minimax-quota.test.mjs @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createMiniMaxQuota, quotaWindows } from '../miniapp/node/minimax-quota.mjs'; + +const model = { + model_name: 'general', + current_interval_remaining_percent: 0, + current_weekly_total_count: 500, + current_weekly_usage_count: 230, + remains_time: 60_000, +}; + +test('shows the MiniMax main pool with a real zero and an independent weekly balance', () => { + const windows = quotaWindows({ model_remains: [{ ...model, model_name: 'other', current_interval_remaining_percent: 80 }, model] }); + assert.deepEqual(windows.map(({ id, remaining }) => [id, remaining]), [['interval', 0], ['weekly', 46]]); + assert.ok(windows[0].resetAt > Date.now()); + assert.equal(windows[1].resetAt, null); + assert.deepEqual(quotaWindows({ model_remains: [{ model_name: 'general', current_interval_remaining_percent: null }] }), []); +}); + +test('coalesces account reads and returns only tier and quota windows', async () => { + const calls = []; + const quota = createMiniMaxQuota({ + readToken: async () => 'fixture-token', + fetch: async (url, options) => { + calls.push(url.origin); + assert.equal(options.headers.Authorization, 'Bearer fixture-token'); + return { ok: true, json: async () => calls.length === 1 + ? { op_group_id: 'private-group', token_plan_tier: 'Max' } + : { model_remains: [model] } }; + }, + }); + try { + const [first, cached] = await Promise.all([quota.get(), quota.get()]); + assert.equal(first, cached); + assert.equal(first.tier, 'Max'); + assert.deepEqual(calls, ['https://agent.minimax.cn', 'https://www.minimaxi.com']); + assert.doesNotMatch(JSON.stringify(first), /fixture-token|private-group/); + } finally { quota.dispose(); } +}); diff --git a/sources/minimax-ai/minimax-pet/dev/native-progress.test.mjs b/sources/minimax-ai/minimax-pet/dev/native-progress.test.mjs new file mode 100644 index 00000000..df28749d --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/native-progress.test.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createAskObserver } from '../miniapp/client/ask-observer.mjs'; + +test('observes the selected idle chat before a turn and filters old or foreign progress', (t) => { + const subscriptions = new Map(); + const events = []; + const agent = { + observe(target, { onEvent }) { + return new Promise((resolve) => subscriptions.set(target.sessionId, { onEvent, resolve, requestId: target.requestId })); + }, + cancel(requestId) { + [...subscriptions.values()].find((item) => item.requestId === requestId)?.resolve(); + }, + }; + const observer = createAskObserver({ agent, onProgress: (event) => events.push(event) }); + t.after(() => observer.dispose()); + observer.update({ availability: 'ready', selectedSessionId: 'selected', trackSelected: true, + sessions: [{ sessionId: 'selected', status: 'idle', observedTurnId: 'old' }] }); + assert.equal(observer.getState().runningCount, 0); + assert.deepEqual(observer.getState().watchingIds, ['selected']); + const listener = subscriptions.get('selected').onEvent; + const push = (type, fields = {}) => listener({ type, sessionId: 'selected', turnId: 'next', ...fields }); + push('turn.started'); + push('text.delta', { text: 'active reply' }); + push('tool.started', { name: 'Shell' }); + push('tool.finished', { name: 'Shell', ok: true }); + push('message.committed', { text: 'final reply' }); + push('text.delta', { sessionId: 'other', text: 'foreign' }); + push('text.delta', { turnId: 'old', text: 'late' }); + push('turn.finished', { status: 'finished' }); + push('text.delta', { text: 'late after finish' }); + assert.deepEqual(events.map((event) => event.type), + ['turn.started', 'text.delta', 'tool.started', 'tool.finished', 'message.committed', 'turn.finished']); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/notice-timing.test.mjs b/sources/minimax-ai/minimax-pet/dev/notice-timing.test.mjs new file mode 100644 index 00000000..7b92d1e8 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/notice-timing.test.mjs @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { noticeRemaining, visibleNotices } from '../miniapp/client/pet-presentation.mjs'; + +test('each completed round has its own five-second window regardless of the error setting or hover pause', () => { + const first = { sessionId: 'a', reminderKey: 'a:1', displayStatus: 'completed' }; + const second = { sessionId: 'b', reminderKey: 'b:1', displayStatus: 'completed' }; + const shownAt = new Map([['a:1', 1000], ['b:1', 2200]]); + const options = { shownAt, timeoutSeconds: 30, pausedAt: 3600 }; + assert.deepEqual(visibleNotices([first, second], { ...options, now: 5999 }), [first, second]); + assert.deepEqual(visibleNotices([first, second], { ...options, now: 6000 }), [second]); + assert.equal(noticeRemaining(second, { ...options, now: 6000 }), 1200); + assert.deepEqual(visibleNotices([first, second], { ...options, now: 7200 }), []); + assert.equal(noticeRemaining({ ...first, reminderKey: 'a:2' }, { ...options, now: 7200 }), 5000); +}); + +test('an error can still pause and an ask stays until handled', () => { + const error = { sessionId: 'a', reminderKey: 'a:1', displayStatus: 'error' }; + const ask = { sessionId: 'b', reminderKey: 'b:1', displayStatus: 'running', needsAnswer: true }; + const options = { shownAt: new Map([['a:1', 1000], ['b:1', 1000]]), now: 15_000, timeoutSeconds: 10 }; + assert.deepEqual(visibleNotices([error, ask], options), [ask]); + assert.equal(noticeRemaining(error, { ...options, pausedAt: 4000 }), 7000); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/presentation.test.mjs b/sources/minimax-ai/minimax-pet/dev/presentation.test.mjs index 5e62a6ee..cfd40f01 100644 --- a/sources/minimax-ai/minimax-pet/dev/presentation.test.mjs +++ b/sources/minimax-ai/minimax-pet/dev/presentation.test.mjs @@ -38,8 +38,8 @@ test('the aggregate status text includes every category and keeps local completi const notice = (n, extra = {}) => ({ sessionId: `s-${n}`, title: `任务 ${n}`, displayStatus: 'completed', ...extra }); -test('a notification hides after its timeout and an answer request never does', () => { - const items = [notice(1), notice(2, { needsAnswer: true })]; +test('an error notification follows its setting and an answer request stays visible', () => { + const items = [notice(1, { displayStatus: 'error' }), notice(2, { needsAnswer: true })]; const shownAt = new Map([['s-1', 1000], ['s-2', 1000]]); assert.deepEqual(visibleNotices(items, { shownAt, now: 5000, timeoutSeconds: 10 }).map((i) => i.sessionId), ['s-1', 's-2']); assert.deepEqual(visibleNotices(items, { shownAt, now: 11_000, timeoutSeconds: 10 }).map((i) => i.sessionId), ['s-2']); @@ -47,7 +47,7 @@ test('a notification hides after its timeout and an answer request never does', }); test('an unknown start counts as just shown and remaining time shrinks to zero', () => { - const items = [notice(1), notice(2, { needsAnswer: true })]; + const items = [notice(1, { displayStatus: 'error' }), notice(2, { needsAnswer: true })]; assert.equal(visibleNotices(items, { shownAt: new Map(), now: 1e9, timeoutSeconds: 3 }).length, 2); assert.equal(noticeRemaining(items[0], { shownAt: new Map(), now: 0, timeoutSeconds: 30 }), 30_000); const shownAt = new Map([['s-1', 0]]); diff --git a/sources/minimax-ai/minimax-pet/dev/preview-window.test.mjs b/sources/minimax-ai/minimax-pet/dev/preview-window.test.mjs new file mode 100644 index 00000000..f5313cc1 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/dev/preview-window.test.mjs @@ -0,0 +1,10 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { previewWindowBounds } from '../miniapp/node/preview-window.mjs'; + +test('the preview is centered at half the work-area width and height, including on a second monitor', () => { + assert.deepEqual(previewWindowBounds({ x: 0, y: 0, width: 1920, height: 1080 }), + { x: 480, y: 270, width: 960, height: 540 }); + assert.deepEqual(previewWindowBounds({ x: -1600, y: 40, width: 1600, height: 900 }), + { x: -1200, y: 265, width: 800, height: 450 }); +}); diff --git a/sources/minimax-ai/minimax-pet/dev/scale-update.test.mjs b/sources/minimax-ai/minimax-pet/dev/scale-update.test.mjs index d4b8166e..0b4759ff 100644 --- a/sources/minimax-ai/minimax-pet/dev/scale-update.test.mjs +++ b/sources/minimax-ai/minimax-pet/dev/scale-update.test.mjs @@ -5,7 +5,7 @@ import test from 'node:test'; const source = await readFile(new URL('../miniapp/client/pet-app.js', import.meta.url), 'utf8'); const handler = source.slice(source.indexOf('function setScale(value)'), source.indexOf('// Import', source.indexOf('function setScale(value)'))); -const sizing = source.slice(source.indexOf('const DESK_WIDTH = 280;'), source.indexOf('// Saved positions')); +const sizing = source.slice(source.indexOf('const DESK_WIDTH = 280;'), source.indexOf('let notificationPreviews')); const deferred = () => { let resolve; const promise = new Promise((yes) => { resolve = yes; }); return { promise, resolve }; }; function harness(overrides = {}) { const calls = [], prefs = { scale: 1 }, app = { mode: 'window', workbenchOpen: false, menuOpen: false }; @@ -31,10 +31,10 @@ function harness(overrides = {}) { test('a desktop size change resizes the window, then fits it, before applying the scale', async () => { const h = harness(); h.app.workbenchOpen = true; await h.setScale(0.5); - // 436 = the fixed window height for the small pet, so the open card always fits. + // 526 = the fixed window height for the small pet, so the open card always fits. // Snapshotted through JSON: the patch object is built inside the sandbox realm. assert.deepEqual(JSON.parse(JSON.stringify(h.calls)), [ - ['close'], ['update', { width: 280, height: 436 }], ['state', 436], + ['close'], ['update', { width: 280, height: 526 }], ['state', 526], ['fit'], ['scale', 0.5], ['save', 0.5], ]); }); diff --git a/sources/minimax-ai/minimax-pet/dev/window-position.test.mjs b/sources/minimax-ai/minimax-pet/dev/window-position.test.mjs index 61008d80..b91976b0 100644 --- a/sources/minimax-ai/minimax-pet/dev/window-position.test.mjs +++ b/sources/minimax-ai/minimax-pet/dev/window-position.test.mjs @@ -133,7 +133,7 @@ async function popOut({ origin, saved = null, workArea = { availLeft: 0, availTo const calls = [], notices = [], savedPositions = []; const prefs = { scale: 0.5, windowPosition: saved }; const app = { mode: 'inline', positionRestoreToken: 0 }; - const bounds = { x: origin.x, y: origin.y, width: 280, height: 436, clickThrough: true }; + const bounds = { x: origin.x, y: origin.y, width: 280, height: 526, clickThrough: true }; const state = () => ({ mode: 'window', window: { ...bounds } }); const win = { getState: async () => state(), @@ -159,21 +159,21 @@ async function popOut({ origin, saved = null, workArea = { availLeft: 0, availTo test('pop-out fits an off-screen Host default even without a saved position', async () => { const h = await popOut({ origin: { x: 1090, y: 846 } }); - // 1019 is the reproduced work-area bottom; 436 is the small pet's designed height. - assert.deepEqual(h.calls, [{ clickThrough: false }, { x: 1090, y: 583, width: 280, height: 436 }]); + // 1019 is the reproduced work-area bottom; 526 is the small pet's designed height. + assert.deepEqual(h.calls, [{ clickThrough: false }, { x: 1090, y: 493, width: 280, height: 526 }]); assert.equal(h.app.restoringPosition, false); assert.deepEqual(h.savedPositions, [{ x: 1090, y: 679 }], 'persist only the corrected bottom anchor'); }); test('pop-out fits a partially visible saved position above the display', async () => { const h = await popOut({ origin: { x: 200, y: 200 }, saved: { x: 1093, y: -322 } }); - assert.equal(h.calls[1].y, -418, 'the stored bottom anchor resolves to the old off-screen origin'); - assert.deepEqual(h.calls.at(-1), { x: 1093, y: 0, width: 280, height: 436 }); - assert.deepEqual(h.savedPositions, [{ x: 1093, y: 96 }]); + assert.equal(h.calls[1].y, -508, 'the stored bottom anchor resolves to the old off-screen origin'); + assert.deepEqual(h.calls.at(-1), { x: 1093, y: 0, width: 280, height: 526 }); + assert.deepEqual(h.savedPositions, [{ x: 1093, y: 186 }]); }); test('pop-out keeps a valid saved position on a display left of the primary one', async () => { - const h = await popOut({ origin: { x: 200, y: 200 }, saved: { x: -1000, y: 146 }, workArea: (bounds) => ({ + const h = await popOut({ origin: { x: 200, y: 200 }, saved: { x: -1000, y: 236 }, workArea: (bounds) => ({ get availLeft() { return bounds.x < 0 ? -1920 : 0; }, availTop: 0, availWidth: 1920, availHeight: 1080, }) }); assert.equal(h.calls.length, 2, 'a valid position should not be moved again'); @@ -184,13 +184,13 @@ test('pop-out keeps a valid saved position on a display left of the primary one' test('pop-out recovers from a rejected position on a disconnected display', async () => { const h = await popOut({ origin: { x: 1090, y: 846 }, saved: { x: 50000, y: 100 } }); - assert.deepEqual(h.calls.at(-1), { x: 1090, y: 583, width: 280, height: 436 }); + assert.deepEqual(h.calls.at(-1), { x: 1090, y: 493, width: 280, height: 526 }); assert.deepEqual(h.notices, [], 'the fallback fit succeeded'); }); test('pop-out keeps the sprite at the bottom on a display shorter than the window', async () => { const h = await popOut({ origin: { x: 30, y: 50 }, workArea: { availLeft: 0, availTop: 0, availWidth: 260, availHeight: 400 } }); - assert.deepEqual(h.calls.at(-1), { x: -10, y: -36, width: 280, height: 436 }); + assert.deepEqual(h.calls.at(-1), { x: -10, y: -126, width: 280, height: 526 }); assert.equal(h.app.winBounds.y + h.app.winBounds.height, 400); assert.deepEqual(h.notices, []); }); diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/activity.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/activity.mjs index c9a617dc..fc682f4d 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/activity.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/activity.mjs @@ -15,11 +15,13 @@ export function normalizeSession(raw, { detail = false } = {}) { if (detail) { if (typeof raw.error?.message === 'string') session.error = raw.error.message; if (typeof raw.lastAssistantText === 'string') session.lastAssistantText = raw.lastAssistantText; + } else if (typeof raw.workspaceDir === 'string') { + session.projectPath = raw.isDefaultWorkspace ? '' : raw.workspaceDir; } return session; } -export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, now = Date.now, makeRequestId = () => `pet-observe-${globalThis.crypto.randomUUID()}` }) { +export function createActivitySource({ agent, onChange, onSettled, refreshCatalog, allowSession = () => true, pollIntervalMs = 5000, pollingEnabled = true, now = Date.now, makeRequestId = () => `pet-observe-${globalThis.crypto.randomUUID()}` }) { let generation = 0; let sequence = 0; let detailSequence = 0; @@ -103,7 +105,7 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n async function readDetail(epoch = generation) { const id = state.selectedSessionId; const ticket = ++detailSequence; - if (!id || !current(epoch)) return; + if (!id || !current(epoch) || !allowSession(id)) return; // A background refresh of the same visible task must not replace its long // reply with a short loading placeholder, which collapses native scrollTop. // Selection changes and visibility/error paths still clear the old detail. @@ -153,7 +155,8 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n removedAt.delete(event.sessionId); const previous = rows.get(event.sessionId); const status = outcome === 'finished' ? 'idle' : outcome; - rows.set(event.sessionId, { sessionId: event.sessionId, title: typeof event.title === 'string' && event.title ? event.title.slice(0, 1000) : previous?.title || t('desk.untitled'), status, updatedAtMs: now(), liveCompleted: outcome === 'finished' }); + rows.set(event.sessionId, { ...previous, sessionId: event.sessionId, title: typeof event.title === 'string' && event.title ? event.title.slice(0, 1000) : previous?.title || t('desk.untitled'), status, updatedAtMs: now(), liveCompleted: outcome === 'finished' }); + if (event.type === 'turn.finished') onSettled?.(event); emit({}); if (state.selectedSessionId === event.sessionId) void readDetail(epoch); } @@ -205,7 +208,7 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n const [result, originRaw] = await Promise.all([agent.sessions(), agent.session().catch((error) => { if (codeOf(error) === 'session_not_found') return null; throw error; - })]); + }), refreshCatalog?.()]); if (!current(epoch)) return; if (!result || !Array.isArray(result.sessions)) throw invalid(); const incoming = result.sessions.map((raw) => normalizeSession(raw)); @@ -213,14 +216,14 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n const origin = originRaw ? normalizeSession(originRaw) : null; if (origin && !incoming.some((s) => s.sessionId === origin.sessionId)) incoming.push(origin); const incomingIds = new Set(incoming.map((row) => row.sessionId)); - const outsideIds = [...rows.keys()].filter((id) => !incomingIds.has(id) && activity.get(id)?.retainOutsideList); + const outsideIds = [...rows.keys()].filter((id) => !incomingIds.has(id) && allowSession(id) && activity.get(id)?.retainOutsideList); const outside = await readOutsideList(outsideIds, epoch); if (!current(epoch)) return; const next = new Map(); for (const row of incoming) { if ((removedAt.get(row.sessionId) ?? 0) > before) continue; const previous = rows.get(row.sessionId); - next.set(row.sessionId, eventSequence(row.sessionId) > before && previous ? previous : mergeSnapshot(row)); + next.set(row.sessionId, eventSequence(row.sessionId) > before && previous ? { ...row, ...previous } : mergeSnapshot(row)); } for (const [id, checked] of outside) { if (!rows.has(id)) continue; @@ -273,8 +276,20 @@ export function createActivitySource({ agent, onChange, pollIntervalMs = 5000, n inFlight = operation; return operation.promise; } + function syncTimer() { + clearInterval(timer); + timer = started && !disposed && pollingEnabled && pollIntervalMs > 0 + ? setInterval(() => { void refresh(); }, pollIntervalMs) : null; + } + return { - start() { if (started || disposed) return inFlight?.promise ?? Promise.resolve(); started = true; emit({}); if (pollIntervalMs > 0) timer = setInterval(() => { void refresh(); }, pollIntervalMs); return refresh(); }, + start() { if (started || disposed) return inFlight?.promise ?? Promise.resolve(); started = true; emit({}); syncTimer(); return refresh(); }, + setPollingEnabled(enabled) { + if (disposed || pollingEnabled === enabled) return; + pollingEnabled = enabled; + syncTimer(); + if (started && enabled) void refresh(); + }, refresh, selectSession(id) { if (state.availability !== 'ready' || !rows.has(id)) throw Object.assign(new Error('session_not_found'), { code: 'session_not_found' }); diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs index a4e77470..a7fa778f 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/ask-observer.mjs @@ -4,13 +4,14 @@ let requestSequence = 0; const idOf = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null; const turnOf = (row) => idOf(row?.observedTurnId); -export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDelayMs = 120 }) { +export function createAskObserver({ agent, onChange, onProgress, maxSubscriptions = 3, askDelayMs = 120 }) { // The fourth Host observer slot belongs to the global lifecycle subscription. const limit = Number.isSafeInteger(maxSubscriptions) ? Math.min(3, Math.max(0, maxSubscriptions)) : 3; const delay = Number.isFinite(askDelayMs) ? Math.max(0, askDelayMs) : 120; const watches = new Map(), retiring = new Set(), failed = new Map(); - let disposed = false, ready = false, running = new Map(), selectedId = null; + let disposed = false, ready = false, running = new Map(), selectedId = null, pinned = null; let queued = false, emitted = null; + const tracked = (id) => running.get(id) || (pinned?.sessionId === id ? pinned : null); function getState() { return { @@ -60,7 +61,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (disposed || !ready) return; const desired = []; const add = (id) => { - const row = running.get(id); + const row = tracked(id); if (row && desired.length < limit && !desired.includes(id) && !failedFor(row)) desired.push(id); }; // Never evict a question just because another session became selected. @@ -72,7 +73,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe for (const watch of [...watches.values()]) if (!desired.includes(watch.id)) retire(watch); for (const id of desired) { if (watches.has(id) || watches.size + retiring.size >= limit) continue; - start(running.get(id)); + start(tracked(id)); } notify(); } @@ -89,11 +90,12 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (!turnId || watch.retiredTurns.has(turnId)) return; if (event.type === 'turn.started') { if (watch.turnId === turnId && watch.terminal) return; - enterTurn(watch, turnId); notify(); return; + enterTurn(watch, turnId); onProgress?.(event); notify(); return; } - if (!['tool.started', 'tool.finished', 'turn.finished'].includes(event.type)) return; + if (!['tool.started', 'tool.finished', 'turn.finished', 'text.delta', 'message.committed'].includes(event.type)) return; if (!watch.turnId) enterTurn(watch, turnId); if (watch.turnId !== turnId || watch.terminal) return; + onProgress?.(event); if (event.type === 'turn.finished') { watch.terminal = true; clearAsk(watch); notify(); return; } @@ -124,7 +126,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe if (wasCurrent) { watches.delete(watch.id); clearAsk(watch); // Do not retry a failing stream on every 5s snapshot of the same turn. - const turnIds = new Set([watch.turnId, turnOf(running.get(watch.id))].filter(Boolean)); + const turnIds = new Set([watch.turnId, turnOf(tracked(watch.id))].filter(Boolean)); failed.set(watch.id, { turnIds }); } if (!disposed) reconcile(); @@ -137,8 +139,10 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe && typeof agent?.observe === 'function' && typeof agent?.cancel === 'function'; selectedId = idOf(snapshot.selectedSessionId); running = new Map(); + pinned = null; if (nextReady) for (const row of Array.isArray(snapshot.sessions) ? snapshot.sessions : []) { if (idOf(row?.sessionId) && row.status === 'running') running.set(row.sessionId, row); + if (snapshot.trackSelected && selectedId && row?.sessionId === selectedId) pinned = row; } if (!nextReady) { ready = false; failed.clear(); @@ -147,11 +151,11 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe } ready = true; for (const [id, entry] of failed) { - const row = running.get(id), turnId = turnOf(row); + const row = tracked(id), turnId = turnOf(row); if (!row || (turnId && !entry.turnIds.has(turnId))) failed.delete(id); } for (const watch of [...watches.values()]) { - const row = running.get(watch.id); + const row = tracked(watch.id); if (!row) { retire(watch); continue; } const turnId = turnOf(row); if (turnId && !watch.retiredTurns.has(turnId)) enterTurn(watch, turnId); @@ -161,7 +165,7 @@ export function createAskObserver({ agent, onChange, maxSubscriptions = 3, askDe getState, dispose() { if (disposed) return; - disposed = true; ready = false; running.clear(); failed.clear(); + disposed = true; ready = false; pinned = null; running.clear(); failed.clear(); for (const watch of [...watches.values()]) retire(watch); }, }; diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs new file mode 100644 index 00000000..2bf19c4a --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/compact-chat.mjs @@ -0,0 +1,304 @@ +import { t } from './i18n.mjs'; +import { renderMarkdown } from './markdown.mjs'; + +export function createCompactChat({ document: doc, onSelect, onOpen, onAppend, onOpenProject, onOpenDelivery }) { + const element = (tag, className, parent) => { + const node = doc.createElement(tag); + node.className = className; + parent?.append(node); + return node; + }; + const root = element('section', 'compact-chat'); + const projectRow = element('div', 'chat-inline-project', root); + const projectLabel = element('label', '', projectRow); + projectLabel.htmlFor = 'pet-chat-project'; + const projectPicker = element('select', '', projectRow); + projectPicker.id = 'pet-chat-project'; + const selector = element('div', 'chat-sessions', root); + const picker = element('button', 'chat-picker', selector); + picker.type = 'button'; + picker.setAttribute('aria-expanded', 'false'); + picker.setAttribute('aria-controls', 'pet-chat-projects'); + const pickerLabel = element('span', 'chat-picker-label', picker); + const chevron = element('span', 'chat-picker-chevron', picker); + chevron.setAttribute('aria-hidden', 'true'); + const create = element('button', 'compact-button chat-new', selector); + create.type = 'button'; create.textContent = '+'; + const newForm = element('form', 'chat-inline-compose'); + const newInput = element('textarea', 'chat-input', newForm); + newInput.rows = 1; + newInput.maxLength = 100_000; + const handoff = element('button', 'compact-button chat-inline-send', newForm); + handoff.type = 'submit'; + handoff.textContent = '↗'; + selector.insertBefore(newForm, create); + const newHint = element('p', 'compact-hint chat-status', root); + newHint.setAttribute('role', 'status'); + const projectList = element('div', 'chat-project-list', root); + projectList.id = 'pet-chat-projects'; + projectList.hidden = true; + const content = element('div', 'chat-content', root); + const preview = element('div', 'chat-preview md', content); + const actions = element('div', 'chat-actions', content); + const open = element('button', 'compact-button chat-open', actions); + open.type = 'button'; + const form = element('form', 'chat-composer', content); + const draft = element('textarea', 'chat-input', form); + draft.rows = 1; + draft.maxLength = 100_000; + const submit = element('button', 'compact-button chat-draft-submit', form); + submit.type = 'submit'; + const status = element('p', 'compact-hint chat-status', content); + status.setAttribute('role', 'status'); + content.hidden = true; + let current = {}, busy = false, notice, optionsKey = '', replyId = '', visible = false, disposed = false; + let pickerOpen = false, rowButtons = [], rowRequest = 0, composing = false; + let projectKey, chosenProject, newNotice; + let callbacks = { select: onSelect, open: onOpen, append: onAppend }; + + function projectId() { + return chosenProject || current.projects?.find((project) => !project.path)?.id; + } + + function paintProjectPicker(projects) { + const options = projects.map((project) => ({ id: project.id, name: project.name || + project.path.replace(/[/\\]+$/u, '').split(/[/\\]/u).at(-1) || t('chat.noProject') })); + const key = JSON.stringify(options); + if (key !== projectKey) { + projectKey = key; + projectPicker.replaceChildren(...options.map(({ id, name }) => { + const option = doc.createElement('option'); option.value = id; option.textContent = name; return option; + })); + } + if (!projects.some((project) => project.id === chosenProject)) chosenProject = undefined; + projectPicker.value = projectId() || ''; + projectRow.hidden = !projects.length; + projectPicker.disabled = busy; + } + + function paintSessions(sessions, id) { + const key = JSON.stringify([t('chat.untitled'), t('chat.empty'), t('status.running'), id, sessions.map((row) => + [row.sessionId, row.title, row.status])]); + if (optionsKey === key) return; + optionsKey = key; + const focused = doc.activeElement?.dataset.sessionId; + const scroll = projectList.scrollTop; + const fragment = doc.createDocumentFragment(); + rowButtons = []; + for (const row of sessions) { + const button = element('button', 'chat-session-row', fragment); + button.type = 'button'; + button.dataset.sessionId = row.sessionId; + const title = element('span', 'chat-session-label', button); + title.textContent = row.title || t('chat.untitled'); + title.title = title.textContent; + if (row.status === 'running') { + const state = element('span', 'chat-session-running', button); + state.setAttribute('aria-label', t('status.running')); + } + if (row.sessionId === id) { + button.setAttribute('aria-current', 'true'); + const check = element('span', 'chat-session-check', button); + check.textContent = '✓'; + check.setAttribute('aria-hidden', 'true'); + } + rowButtons.push(button); + } + if (!rowButtons.length) element('p', 'chat-empty', fragment).textContent = t('chat.empty'); + projectList.replaceChildren(fragment); + projectList.scrollTop = scroll; + if (focused) rowButtons.find((button) => button.dataset.sessionId === focused)?.focus({ preventScroll: true }); + } + + function paint() { + if (!visible || disposed) return; + const { sessions = [], projects = [], availability, loading, error, originId } = current; + const ready = availability === 'ready'; + paintProjectPicker(projects); + const project = projectId(); + const matches = project ? sessions.filter((row) => row.projectId === project) : []; + const session = matches.find((row) => row.sessionId === current.id); + const id = session?.sessionId; + const detail = id ? current.detail : null; + if (!ready || composing) pickerOpen = false; + const label = session?.title || t('chat.choose'); + pickerLabel.textContent = label; + pickerLabel.title = label; + picker.dataset.selected = id || ''; + picker.setAttribute('aria-expanded', String(pickerOpen)); + projectList.hidden = !pickerOpen; + if (pickerOpen) paintSessions(matches, id); + picker.hidden = composing; + picker.disabled = !ready || busy; + selector.classList.toggle('is-composing', composing); + create.disabled = busy || !composing && (!onOpenProject || !project); + create.textContent = composing ? '‹' : '+'; + create.title = t(composing ? 'chat.inline.back' : 'chat.inline.new'); + create.setAttribute('aria-label', create.title); + newForm.hidden = !composing; + newInput.disabled = busy; + handoff.disabled = busy || !project || !newInput.value.trim(); + newHint.hidden = !composing || !newNotice?.text; + newHint.textContent = newNotice?.text || ''; + newHint.dataset.kind = newNotice?.kind || 'info'; + open.hidden = !ready || !id || !callbacks.open; + open.disabled = busy; + open.textContent = session?.needsAnswer ? t('tasks.goAnswer') : t('chat.openNative'); + const canAppend = ready && id && id === originId && callbacks.append; + form.hidden = !canAppend; + draft.disabled = busy; + submit.disabled = busy || !draft.value.trim(); + const text = id && detail?.sessionId === id ? detail.lastAssistantText : ''; + preview.hidden = !text; + if (replyId !== id) { replyId = id; preview.scrollTop = 0; } + renderMarkdown(preview, text || '', { sessionId: ready ? id : undefined, onOpenDelivery }); + const hint = notice?.text || (!ready ? t(availability === 'connecting' ? 'availability.connectingShort' : 'chat.hostUnavailable') + : error ? t('desk.replyFailed', { code: error }) + : loading && !text ? t('desk.loading') + : id && !text ? t('desk.replyEmpty') : ''); + status.textContent = hint; + status.dataset.kind = notice?.kind || (error ? 'error' : 'info'); + status.hidden = !hint; + content.hidden = composing || pickerOpen || (preview.hidden && open.hidden && form.hidden && status.hidden); + } + + function setPickerOpen(opened, focus = false) { + if (pickerOpen === opened) return; + pickerOpen = opened; + paint(); + if (pickerOpen && !doc.defaultView.matchMedia('(prefers-reduced-motion: reduce)').matches) { + projectList.animate?.([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], + { duration: 145, easing: 'ease-out' }); + } + if (focus) picker.focus({ preventScroll: true }); + } + + function selectRow(id) { + setPickerOpen(false, true); + if (id === current.id) return; + const request = ++rowRequest; + notice = null; + Promise.resolve().then(() => callbacks.select?.(id)).catch((error) => { + if (disposed || request !== rowRequest) return; + notice = { kind: 'error', text: t('chat.actionError', { code: error?.code || 'result_unknown' }) }; + paint(); + }); + } + + // Calling the bridge directly in the gesture preserves short-lived user activation. + function perform(action, value) { + if (!action || busy || disposed) return; + busy = true; notice = null; + let pending; + try { pending = action(value); } catch (error) { pending = Promise.reject(error); } + paint(); + Promise.resolve(pending).then((result) => { + notice = result; + if (action === callbacks.append && result?.kind === 'ok' && draft.value === value) draft.value = ''; + }, (error) => { + notice = { kind: 'error', text: t('chat.actionError', { code: error?.code || error?.message || 'result_unknown' }) }; + }).finally(() => { busy = false; paint(); }); + } + picker.addEventListener('click', () => setPickerOpen(!pickerOpen)); + picker.addEventListener('keydown', (event) => { + if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return; + event.preventDefault(); + setPickerOpen(true); + const target = rowButtons.find((button) => button.dataset.sessionId === current.id) || + (event.key === 'ArrowUp' ? rowButtons.at(-1) : rowButtons[0]); + target?.focus(); + }); + projectList.addEventListener('click', (event) => { + const id = event.target.closest('.chat-session-row')?.dataset.sessionId; + if (id) selectRow(id); + }); + projectList.addEventListener('keydown', (event) => { + const index = rowButtons.indexOf(doc.activeElement); + if (index < 0) return; + const target = event.key === 'Home' ? 0 : event.key === 'End' ? rowButtons.length - 1 : + event.key === 'ArrowDown' ? Math.min(rowButtons.length - 1, index + 1) : event.key === 'ArrowUp' ? Math.max(0, index - 1) : null; + if (target === null) return; + event.preventDefault(); + rowButtons[target].focus(); + }); + root.addEventListener('keydown', (event) => { + if (event.key !== 'Escape' || !pickerOpen) return; + event.preventDefault(); + event.stopPropagation(); + setPickerOpen(false, true); + }); + const outside = (event) => { + if (pickerOpen && !picker.contains(event.target) && !projectList.contains(event.target) && !projectRow.contains(event.target)) setPickerOpen(false); + }; + doc.addEventListener('pointerdown', outside); + create.addEventListener('click', () => { + setPickerOpen(false); + composing = !composing; + newNotice = null; + paint(); + (composing ? newInput : picker).focus({ preventScroll: true }); + }); + projectPicker.addEventListener('change', () => { chosenProject = projectPicker.value; newNotice = null; paint(); }); + newInput.addEventListener('input', () => { handoff.disabled = busy || !projectId() || !newInput.value.trim(); }); + newForm.addEventListener('submit', (event) => { + event.preventDefault(); + if (handoff.disabled || !composing) return; + const value = newInput.value.trim(), project = projectId(); + if (!value || !project || !onOpenProject) return; + busy = true; + let copy, navigation; + try { copy = doc.defaultView.navigator.clipboard.writeText(value); } + catch (error) { copy = Promise.reject(error); } + try { navigation = onOpenProject(project); } + catch (error) { navigation = Promise.reject(error); } + paint(); + void Promise.allSettled([copy, navigation]).then(([copied, opened]) => { + if (disposed) return; + if (opened.status === 'rejected' || opened.value?.kind !== 'ok') { + newNotice = { kind: 'error', text: opened.value?.text || t('chat.project.unavailable') }; + } else if (copied.status === 'rejected') { + newNotice = { kind: 'error', text: t('chat.project.copyFailed') }; + } else newNotice = { kind: 'info', text: t('chat.project.draftCopied') }; + busy = false; + paint(); + }); + }); + open.addEventListener('click', () => perform(callbacks.open, current.id)); + draft.addEventListener('input', () => { submit.disabled = busy || !draft.value.trim(); }); + form.addEventListener('submit', (event) => { + event.preventDefault(); + if (!form.hidden && draft.value.trim()) perform(callbacks.append, draft.value); + }); + + return { + root, + viewing(id) { return visible && !composing && !pickerOpen && current.id === id && !preview.hidden; }, + suspend() { visible = false; pickerOpen = false; }, + setVisible(value) { + const entering = value && !visible; + visible = value; + root.hidden = !value; + if (!value) pickerOpen = false; + if (entering) paint(); + }, + update(snapshot) { + if (snapshot.id !== current.id) notice = null; + current = snapshot; + paint(); + }, + translate() { + projectList.setAttribute('aria-label', t('chat.choose')); + preview.setAttribute('aria-label', t('chat.latest')); + draft.placeholder = t('chat.draft'); + draft.setAttribute('aria-label', t('chat.draft')); + submit.textContent = t('chat.append'); + projectLabel.textContent = t('chat.project.label'); + newInput.placeholder = t('chat.inline.placeholder'); + newInput.setAttribute('aria-label', newInput.placeholder); + handoff.title = t('chat.project.handoff'); + handoff.setAttribute('aria-label', handoff.title); + paint(); + }, + dispose() { disposed = true; callbacks = {}; doc.removeEventListener('pointerdown', outside); root.remove(); }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs index 9a573130..e1eb8a11 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/compact-pet-view.mjs @@ -1,5 +1,6 @@ import { markdownToPlainText, renderMarkdown, resetMarkdown } from './markdown.mjs'; -import { t } from './i18n.mjs'; +import { getLanguage, t } from './i18n.mjs'; +import { createCompactChat } from './compact-chat.mjs'; const STATUS_KEYS = { running: 'desk.statusRunning', error: 'status.error', completed: 'status.completed', aborted: 'status.aborted', idle: 'status.idle', needs_answer: 'status.needsAnswer' }; const statusLabel = (status) => (STATUS_KEYS[status] ? t(STATUS_KEYS[status]) : t('desk.toView')); @@ -13,15 +14,50 @@ export const taskStatus = (row) => row?.needsAnswer === true ? 'needs_answer' /** Task notifications and their complete replies stay beside the pet. */ export function createCompactPetView({ - container, onClose, onSelectTask, onOpenSession, + container, getAnchor, onClose, onSelectTask, onOpenSession, onChangeView, onSelectChat, onAppendDraft, onOpenProject, onOpenDelivery, quota, }) { if (!container?.ownerDocument) throw new TypeError('A compact pet container is required.'); const doc = container.ownerDocument; const hadRootClass = container.classList.contains('compact-pet-card'); container.classList.add('compact-pet-card'); + container.hidden = true; let disposed = false, opened = false, view = 'tasks', reminders = { items: [] }; - let allSessions = null, taskSelection = {}, detailBackView = 'tasks'; + let allSessions = null, taskSelection = {}, detailBackView = 'tasks', originId = null; + let notificationSelection = null; + let chatSessions = [], projects = []; let paintedDetailId = null, openToken = 0; + let language; + let panelMotion; + const restFrame = { clipPath: 'inset(0 0 0 0 round 12px)' }; + + function reveal(show, animate = true) { + const liveStyle = panelMotion ? doc.defaultView.getComputedStyle(container) : null; + const interrupted = liveStyle && { clipPath: liveStyle.clipPath }; + panelMotion?.cancel(); + panelMotion = undefined; + container.inert = !show; + if (show) container.hidden = false; + if (!animate || !container.animate || doc.defaultView.matchMedia('(prefers-reduced-motion: reduce)').matches) { + container.hidden = !show; + return; + } + const anchor = getAnchor?.() || { width: 84, height: 42 }; + const side = Math.max(0, (container.offsetWidth - anchor.width) / 2); + const bottom = Math.max(0, container.offsetHeight - anchor.height); + const narrow = { clipPath: `inset(0 ${side}px ${bottom}px ${side}px round 12px)` }; + const wide = { clipPath: `inset(0 0 ${bottom}px 0 round 12px)`, offset: .45 }; + const frames = interrupted ? [interrupted, show ? restFrame : narrow] : + show ? [narrow, wide, restFrame] : [restFrame, wide, narrow]; + const motion = container.animate(frames, + { duration: show ? 220 : 155, easing: 'cubic-bezier(.2,.65,.25,1)', fill: 'both' }); + panelMotion = motion; + motion.onfinish = () => { + if (panelMotion !== motion) return; + panelMotion = undefined; + container.hidden = !show; + motion.cancel(); + }; + } const rows = new Map(); const setText = (node, value) => { const next = String(value ?? ''); if (node.textContent !== next) node.textContent = next; }; const element = (tag, className, text) => { @@ -38,11 +74,16 @@ export function createCompactPetView({ return node; }; const selection = () => { - const id = textOf(taskSelection.selectedSessionId); + const source = view === 'detail' && notificationSelection ? notificationSelection : taskSelection; + const id = textOf(source.selectedSessionId); return { id, - session: id && taskSelection.session?.sessionId === id ? taskSelection.session : null, - detail: id && taskSelection.detail?.sessionId === id ? taskSelection.detail : null, - available: taskSelection.availability === 'ready', + session: id && source.session?.sessionId === id ? source.session : null, + detail: id && source.detail?.sessionId === id ? source.detail : null, + available: source.availability === 'ready', + steps: source.steps || [], + loading: source.detailLoading, + error: source.detailError, + canOpenHost: source.canOpenHost !== false, }; }; const call = async (callback, ...args) => { @@ -55,9 +96,15 @@ export function createCompactPetView({ const state = element('span', 'compact-state'); state.setAttribute('role', 'status'); const closeButton = button('×', 'compact-close', () => { if (disposed) return; - api.close(); void call(onClose); + if (onClose) void call(onClose); + else api.close(); }); - header.append(state, closeButton); + const switchView = button('', 'compact-switch', () => { + const next = view === 'chat' ? 'tasks' : 'chat'; + if (onChangeView) void call(onChangeView, next); + else api.open(next); + }); + header.append(state, switchView, closeButton); const tasksPane = element('div', 'compact-tasks compact-body'); const taskList = element('ul', 'compact-task-list'); @@ -74,17 +121,18 @@ export function createCompactPetView({ // Only the reply scrolls; the title and the actions stay pinned so a long title or a // long reply can never push the buttons out of the 280px card. const detailBody = element('div', 'compact-detail-body'); + const detailSteps = element('ul', 'compact-detail-steps'); const detailReply = element('div', 'compact-detail-reply md'); detailReply.tabIndex = 0; - detailBody.append(detailReply); + detailBody.append(detailSteps, detailReply); const detailFooter = element('div', 'compact-footer'); const back = button('', 'compact-detail-back compact-link', () => api.open(detailBackView)); const openHint = element('p', 'compact-hint'); openHint.setAttribute('role', 'status'); openHint.hidden = true; const setHint = (text, kind = 'info') => { setText(openHint, text); openHint.dataset.kind = kind; openHint.hidden = !openHint.textContent; }; // The Host checks user activation, so the callback must run synchronously inside this click. const openSession = button(t('tasks.open'), 'compact-open', () => { - const { id } = selection(); - if (disposed || !id || typeof onOpenSession !== 'function') return; + const { id, canOpenHost } = selection(); + if (disposed || !id || !canOpenHost || typeof onOpenSession !== 'function') return; const token = ++openToken; openSession.disabled = true; setHint(t('desk.openHint')); void call(onOpenSession, id).then((result) => { @@ -96,7 +144,11 @@ export function createCompactPetView({ }); detailFooter.append(back, openSession); detailPane.append(detailHead, detailBody, detailFooter, openHint); - container.append(header, tasksPane, detailPane); + const chat = createCompactChat({ + document: doc, onSelect: onSelectChat, onOpen: onOpenSession, onAppend: onAppendDraft, onOpenProject, onOpenDelivery, + }); + container.append(header, tasksPane, detailPane, chat.root); + if (quota) container.append(quota.panel); function paintTasks() { const reminderItems = Array.isArray(reminders?.items) ? reminders.items : Array.isArray(reminders) ? reminders : []; @@ -134,7 +186,7 @@ export function createCompactPetView({ } function paintDetail() { - const { id, session, detail, available } = selection(); + const { id, session, detail, available, steps, loading, error, canOpenHost } = selection(); const needsAnswer = available && session?.needsAnswer === true; const status = taskStatus(session) || taskStatus(detail); setText(detailTitle, textOf(session?.title) || textOf(detail?.title) || t('desk.reply')); @@ -145,25 +197,29 @@ export function createCompactPetView({ else if (needsAnswer) text = t('status.needsAnswer'); // A background refresh keeps the matching reply mounted; a short loading // placeholder would shrink its scroll range and reset a reader's position. - else if (taskSelection.detailLoading && !detail) text = t('desk.loading'); - else if (taskSelection.detailError) text = t('desk.replyFailed', { code: failureCode(taskSelection.detailError) }); + else if (loading && !detail) text = t('desk.loading'); + else if (error) text = t('desk.replyFailed', { code: failureCode(error) }); else if (!id) text = t('desk.chooseTask'); else if (!detail) text = t('desk.loading'); else text = (detail.status === 'error' && textOf(detail.error)) || textOf(detail.lastAssistantText) || t('desk.replyEmpty'); // Status copy stays plain text; an actual reply is markdown. renderMarkdown keeps // the DOM when the text is unchanged and restores the scroll offset when a // streaming reply replaces it. - if (needsAnswer || !available || taskSelection.detailLoading && !detail) { + if (needsAnswer || !available || loading && !detail) { if (detailReply.dataset.mdSource !== text) { resetMarkdown(detailReply); setText(detailReply, text); } } else { - renderMarkdown(detailReply, text); + renderMarkdown(detailReply, text, { sessionId: available && canOpenHost ? id : undefined, onOpenDelivery }); + } + if (steps.length !== detailSteps.children.length || steps.some((label, index) => detailSteps.children[index].textContent !== label)) { + detailSteps.replaceChildren(...steps.map((label) => element('li', '', label))); } - detailPane.setAttribute('aria-busy', String(available && !needsAnswer && taskSelection.detailLoading === true)); + detailSteps.hidden = steps.length === 0; + detailPane.setAttribute('aria-busy', String(available && !needsAnswer && loading === true)); if (paintedDetailId !== id) { detailReply.scrollTop = 0; detailBody.scrollTop = 0; paintedDetailId = id; openToken++; openSession.disabled = false; setHint(''); } - openSession.hidden = typeof onOpenSession !== 'function' || !available || !id; + openSession.hidden = typeof onOpenSession !== 'function' || !available || !canOpenHost || !id; setText(openSession, needsAnswer ? t('tasks.goAnswer') : t('tasks.open')); openSession.setAttribute('aria-label', t('desk.openAria', { action: needsAnswer ? t('tasks.goAnswer') : t('tasks.open'), @@ -172,37 +228,74 @@ export function createCompactPetView({ } function paint() { - if (disposed) return; + if (disposed || !opened) return; // Labels follow the interface language, which the page resolves after this view exists. closeButton.setAttribute('aria-label', t('desk.closePanel')); detailReply.setAttribute('aria-label', t('desk.replyAria')); setText(allTasks, t('tasks.all')); setText(back, t('tasks.back')); - container.hidden = !opened; tasksPane.hidden = !['tasks', 'allTasks'].includes(view); detailPane.hidden = view !== 'detail'; - setText(state, view === 'tasks' ? t('desk.panelState.tasks') : view === 'allTasks' ? t('desk.panelState.allTasks') : t('desk.panelState.detail')); - paintTasks(); paintDetail(); + const chatting = view === 'chat'; + setText(state, chatting ? t('chat.title') : view === 'tasks' ? t('desk.panelState.tasks') : view === 'allTasks' ? t('desk.panelState.allTasks') : t('desk.panelState.detail')); + setText(switchView, chatting ? t('app.tabTasks') : t('chat.title')); + if (language !== getLanguage()) { + language = getLanguage(); + chat.translate(); + quota?.translate(); + } + if (quota) quota.panel.hidden = !chatting; + if (chatting) { + const { id, session, detail } = selection(); + const allowed = chatSessions.some((row) => row.sessionId === id); + chat.update({ sessions: chatSessions, id: allowed ? id : '', session: allowed ? session : null, detail: allowed ? detail : null, originId, projects, availability: taskSelection.availability, + loading: taskSelection.detailLoading, error: taskSelection.detailError }); + } + chat.setVisible(chatting); + if (view === 'detail') paintDetail(); + else if (!chatting) paintTasks(); } const api = { get opened() { return opened && !disposed; }, get view() { return view; }, + get progressSlot() { return header; }, + viewing(id) { + return opened && (view === 'chat' ? chat.viewing(id) : view === 'detail' && + selection().id === id && Boolean(selection().available && selection().detail)); + }, update(next = {}) { if (disposed) return; reminders = next.reminders || { items: [] }; allSessions = Array.isArray(next.allSessions) ? next.allSessions : null; + chatSessions = next.chatSessions || []; + projects = next.projects || []; taskSelection = next.taskSelection || {}; + notificationSelection = next.notificationSelection || null; + originId = next.originId || null; paint(); }, open(next = 'tasks') { - if (disposed || !['tasks', 'allTasks', 'detail'].includes(next)) return false; + if (disposed || !['tasks', 'allTasks', 'detail', 'chat'].includes(next)) return false; if (next === 'detail' && ['tasks', 'allTasks'].includes(view)) detailBackView = view; - view = next; opened = true; paint(); return true; + const entering = !opened; + view = next; + opened = true; + paint(); + if (entering) reveal(true); + return true; + }, + close({ animate = true } = {}) { + if (disposed || (!opened && (animate || container.hidden))) return; + opened = false; + // Freeze the last layout while the panel exits. Reset the picker for the next open. + chat.suspend(); + reveal(false, animate); }, - close() { if (!disposed) { opened = false; paint(); } }, dispose() { if (disposed) return; disposed = true; opened = false; + panelMotion?.cancel(); panelMotion = undefined; + chat.dispose(); for (const unbind of callbacks) unbind(); header.remove(); tasksPane.remove(); detailPane.remove(); rows.clear(); container.hidden = true; diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs new file mode 100644 index 00000000..cfc474b6 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/completion-inbox.mjs @@ -0,0 +1,42 @@ +export function completionRecord(raw) { + const { sessionId, turnId, title, text, updatedAtMs, viewed } = raw ?? {}; + if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || + typeof turnId !== 'string' || !turnId || turnId.length > 256 || + !Number.isSafeInteger(updatedAtMs) || updatedAtMs < 0) return null; + return { sessionId, turnId, title: typeof title === 'string' ? title.slice(0, 350) : '', + text: viewed !== true && typeof text === 'string' ? text.slice(0, 6000) : '', updatedAtMs, viewed: viewed === true }; +} + +export function createCompletionInbox({ onChange } = {}) { + const latest = new Map(); + const unread = () => [...latest.values()].filter((row) => !row.viewed); + return { + complete(row, { viewed = false } = {}) { + const record = completionRecord({ ...row, viewed }); + if (!record) return; + const current = latest.get(record.sessionId); + if (current && (current.turnId === record.turnId || current.updatedAtMs > record.updatedAtMs)) return; + latest.set(record.sessionId, record); + onChange?.({ action: 'complete', row: record }); + }, + view(sessionId, turnId) { + const row = latest.get(sessionId); + if (!row || row.viewed || turnId && row.turnId !== turnId) return undefined; + latest.set(sessionId, { ...row, text: '', viewed: true }); + onChange?.({ action: 'view', sessionId, turnId: row.turnId }); + return row; + }, + restore(records) { + for (const raw of records) { + const row = completionRecord(raw); + if (!row) continue; + const current = latest.get(row.sessionId); + if (!current || current.updatedAtMs < row.updatedAtMs || + (current.turnId === row.turnId && row.viewed && !current.viewed)) latest.set(row.sessionId, row); + } + }, + get count() { return unread().length; }, + get rows() { return unread().sort((a, b) => b.updatedAtMs - a.updatedAtMs); }, + clear() { latest.clear(); }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs new file mode 100644 index 00000000..9132cde5 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-formats.mjs @@ -0,0 +1,17 @@ +const rasterTypes = new Map([ + ['png', 'image/png'], ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'], + ['webp', 'image/webp'], ['gif', 'image/gif'], +]); +const textTypes = new Set([ + 'txt', 'csv', 'tsv', 'json', 'xml', 'yaml', 'yml', 'toml', 'sql', 'js', 'mjs', + 'cjs', 'ts', 'tsx', 'jsx', 'py', 'ps1', 'sh', 'java', 'html', 'css', 'log', +]); + +export function deliveryFormat(path) { + const extension = /\.([a-z0-9]+)$/iu.exec(path)?.[1].toLowerCase(); + const mime = rasterTypes.get(extension); + if (mime) return { kind: 'image', mime }; + if (['md', 'markdown'].includes(extension)) return { kind: 'markdown', mime: 'text/plain; charset=utf-8' }; + if (textTypes.has(extension)) return { kind: 'text', mime: 'text/plain; charset=utf-8' }; + return null; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html new file mode 100644 index 00000000..9ea166cb --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.html @@ -0,0 +1,23 @@ + + + + + + + MiniMax Pet + + + + +
+
+

+ +
+
+

正在加载…

+
+
+
+ + diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs new file mode 100644 index 00000000..b5052967 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/delivery-preview.mjs @@ -0,0 +1,68 @@ +import { setLanguage, t } from './i18n.mjs'; +import { renderMarkdown } from './markdown.mjs'; + +const title = document.querySelector('h1'); +const scale = document.querySelector('.delivery-preview-scale'); +const body = document.querySelector('.delivery-preview-body'); +const status = document.querySelector('.delivery-preview-status'); +const content = document.querySelector('.delivery-preview-content'); +const previewPath = location.pathname; + +async function checkedResponse(resource) { + const response = await fetch(`${previewPath}/${resource}`); + if (!response.ok) throw new Error('preview_unavailable'); + return response; +} + +function showError() { + content.replaceChildren(); + status.textContent = t('delivery.unavailable'); + status.hidden = false; +} + +scale.addEventListener('click', () => { + const original = content.classList.toggle('is-original'); + scale.textContent = t(original ? 'delivery.fit' : 'delivery.original'); + scale.setAttribute('aria-pressed', String(original)); + body.scrollLeft = original ? (body.scrollWidth - body.clientWidth) / 2 : 0; + body.scrollTop = original ? (body.scrollHeight - body.clientHeight) / 2 : 0; +}); + +window.addEventListener('keydown', (event) => { + if (event.key === 'Escape') window.close(); +}); + +async function loadPreview() { + const { title: caption, kind, language, theme } = await (await checkedResponse('info')).json(); + setLanguage(language); + document.documentElement.lang = language; + if (theme) document.documentElement.dataset.theme = theme; + title.textContent = caption; + title.title = caption; + document.title = caption; + status.textContent = t('desk.loading'); + content.dataset.kind = kind; + if (kind === 'image') { + const image = document.createElement('img'); + image.alt = caption; + image.addEventListener('load', () => { + status.hidden = true; + scale.textContent = t('delivery.original'); + scale.hidden = false; + }, { once: true }); + image.addEventListener('error', showError, { once: true }); + content.append(image); + image.src = `${previewPath}/content`; + return; + } + const text = await (await checkedResponse('content')).text(); + status.hidden = true; + if (kind === 'markdown') renderMarkdown(content, text); + else { + const pre = document.createElement('pre'); + pre.textContent = text; + content.append(pre); + } +} + +void loadPreview().catch(showError); diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/i18n.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/i18n.mjs index 18ed5be4..ff06b44a 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/i18n.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/i18n.mjs @@ -135,11 +135,11 @@ export const MESSAGES = Object.freeze({ 'settings.languageFollows': '语言跟随 MiniMax Code(当前 {{language}})。', 'settings.languageSet': '界面语言已切换为 {{language}}。', 'settings.notice': '任务通知', - 'settings.noticeHint': '完成或异常后,桌面卡片显示多少秒后自动收起;填 0 表示一直显示,直到手动关闭。收起不会把任务标记为已读。', - 'settings.noticeField': '显示时长', + 'settings.noticeHint': '完成提醒自动显示 5 秒,收起后可从铃铛查看。异常提醒的时长可调整,填 0 表示手动关闭。', + 'settings.noticeField': '异常提醒时长', 'settings.secondsUnit': '秒', - 'settings.noticeSaved': '桌面卡片显示 {{seconds}} 秒后收起。', - 'settings.noticeNever': '桌面卡片会一直显示到手动关闭。', + 'settings.noticeSaved': '异常提醒在 {{seconds}} 秒后收起。', + 'settings.noticeNever': '异常提醒会一直显示到手动关闭。', 'settings.noticeInvalid': '请输入 0 到 {{max}} 之间的整数秒。', 'settings.reminders': '本次提醒', 'settings.remindersHint': '静音的任务可在这里恢复;重新打开桌宠后恢复默认提醒。', @@ -277,8 +277,56 @@ export const MESSAGES = Object.freeze({ 'markdown.image': '[图片{{alt}}]', 'markdown.truncated': '…(内容过长,已截断显示)', 'markdown.imageAlt': ':{{alt}}', + 'markdown.imageUnavailable': '图片暂不可用', + 'delivery.file': '交付物', + 'delivery.openImage': '查看大图:{{title}}', + 'delivery.original': '原始大小', + 'delivery.fit': '适应窗口', + 'delivery.unavailable': '暂时无法预览,请在主窗口查看交付物。', + 'delivery.windowFailed': '预览窗口未能打开,请在主窗口查看交付物。', // Common + 'chat.title': '会话', + 'chat.choose': '选择会话', + 'chat.noProject': '未选择项目', + 'chat.empty': '暂无可选会话', + 'chat.untitled': '未命名会话', + 'chat.inline.new': '编写桌面会话草稿', + 'chat.inline.back': '返回会话列表', + 'chat.inline.placeholder': '开始新聊天…', + 'chat.project.label': '项目', + 'chat.project.handoff': '复制草稿并打开主窗口', + 'chat.project.draftCopied': '草稿已复制,请在桌面端新建并粘贴发送。', + 'chat.project.copyFailed': '自动复制失败,请手动复制这条草稿。', + 'chat.project.unavailable': '暂时无法打开桌面会话入口。', + 'live.unreadCount': '{{count}} 个已完成会话未查看', + 'chat.openNative': '在主窗口继续', + 'chat.latest': '最新一条回复', + 'chat.draft': '给此会话写草稿', + 'chat.append': '交给主窗口', + 'chat.draftAdded': '草稿已交给主窗口,请在那里发送。', + 'chat.draftUnknown': '请先检查主窗口里的草稿。', + 'chat.hostUnavailable': '宿主会话暂不可用', + 'chat.actionError': '操作失败({{code}})', + 'chat.quota.label': 'MiniMax 订阅额度', + 'live.show': '会话进度', + 'live.expandTasks': '展开 {{count}} 个会话', + 'live.jumpTask': '跳转到会话:{{title}}', + 'live.stopInHost': '在主窗口停止任务:{{title}}', + 'live.command.working': '正在执行命令', + 'live.command.done': '已执行命令', + 'live.command.error': '命令执行失败', + 'live.tool.working': '正在调用 {{name}}', + 'live.tool.done': '已执行 {{name}}', + 'live.tool.error': '{{name}} 执行失败', + 'chat.quota.interval': '5 小时', + 'chat.quota.weekly': '本周', + 'chat.quota.loading': '读取额度…', + 'chat.quota.signedOut': '额度需登录', + 'chat.quota.unavailable': '无可显示的额度', + 'chat.quota.error': '额度暂不可用', + 'chat.quota.stale': '待刷新', + 'chat.quota.reset': '{{date}} 重置', 'common.ok': '知道了', 'common.cancelled': '已取消', }, @@ -405,11 +453,11 @@ export const MESSAGES = Object.freeze({ 'settings.languageFollows': 'Language follows MiniMax Code (currently {{language}}).', 'settings.languageSet': 'Interface language set to {{language}}.', 'settings.notice': 'Task notifications', - 'settings.noticeHint': 'How long a desktop card stays after a task finishes or fails. Use 0 to keep it until you close it. Hiding a card does not mark the task as read.', - 'settings.noticeField': 'Show for', + 'settings.noticeHint': 'Completion notices tuck away after 5 seconds and remain in the bell. Set an error notice duration of 0 to keep errors until dismissed.', + 'settings.noticeField': 'Error notice duration', 'settings.secondsUnit': 'sec', - 'settings.noticeSaved': 'Desktop cards hide after {{seconds}} seconds.', - 'settings.noticeNever': 'Desktop cards stay until you close them.', + 'settings.noticeSaved': 'Error notices hide after {{seconds}} seconds.', + 'settings.noticeNever': 'Error notices stay until dismissed.', 'settings.noticeInvalid': 'Enter a whole number of seconds from 0 to {{max}}.', 'settings.reminders': 'This session’s reminders', 'settings.remindersHint': 'Restore muted tasks here; reopening the pet restores the default reminders.', @@ -543,7 +591,55 @@ export const MESSAGES = Object.freeze({ 'markdown.image': '[Image{{alt}}]', 'markdown.truncated': '… (too long; truncated)', 'markdown.imageAlt': ': {{alt}}', + 'markdown.imageUnavailable': 'Image unavailable', + 'delivery.file': 'Deliverable', + 'delivery.openImage': 'View full image: {{title}}', + 'delivery.original': 'Actual size', + 'delivery.fit': 'Fit to window', + 'delivery.unavailable': 'Preview unavailable. Open the deliverable in the main window.', + 'delivery.windowFailed': 'Couldn’t open the preview window. Open the deliverable in the main window.', + 'chat.title': 'Chat', + 'chat.choose': 'Choose a chat', + 'chat.noProject': 'No project', + 'chat.empty': 'No chats available', + 'chat.untitled': 'Untitled chat', + 'chat.inline.new': 'Draft a desktop chat', + 'chat.inline.back': 'Back to chats', + 'chat.inline.placeholder': 'Start a new chat…', + 'chat.project.label': 'Project', + 'chat.project.handoff': 'Copy draft and open the main window', + 'chat.project.draftCopied': 'Draft copied. Start a desktop chat, then paste and send.', + 'chat.project.copyFailed': 'Copying failed. You can copy the draft manually.', + 'chat.project.unavailable': 'Unable to open the desktop chat view.', + 'live.unreadCount': '{{count}} completed chats to review', + 'chat.openNative': 'Continue in MiniMax Code', + 'chat.latest': 'Latest reply', + 'chat.draft': 'Draft for this chat', + 'chat.append': 'Hand off draft', + 'chat.draftAdded': 'Draft added. Send it from MiniMax Code.', + 'chat.draftUnknown': 'Check the draft in MiniMax Code first.', + 'chat.hostUnavailable': 'Desktop chats are unavailable', + 'chat.actionError': 'Request failed ({{code}})', + 'chat.quota.label': 'MiniMax subscription quota', + 'live.show': 'Show chat progress', + 'live.expandTasks': 'Expand {{count}} chats', + 'live.jumpTask': 'Go to chat: {{title}}', + 'live.stopInHost': 'Stop in the main window: {{title}}', + 'live.command.working': 'Running command', + 'live.command.done': 'Command executed', + 'live.command.error': 'Command failed', + 'live.tool.working': 'Using {{name}}', + 'live.tool.done': 'Finished {{name}}', + 'live.tool.error': '{{name}} failed', + 'chat.quota.interval': '5 hours', + 'chat.quota.weekly': 'Weekly', + 'chat.quota.loading': 'Loading quota…', + 'chat.quota.signedOut': 'Sign in for quota', + 'chat.quota.unavailable': 'No quota available', + 'chat.quota.error': 'Quota unavailable', + 'chat.quota.stale': 'Updating', + 'chat.quota.reset': 'Resets {{date}}', 'common.ok': 'OK', 'common.cancelled': 'Cancelled', }, diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/index.html b/sources/minimax-ai/minimax-pet/miniapp/client/index.html index 416c7f92..a3b64f59 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/index.html +++ b/sources/minimax-ai/minimax-pet/miniapp/client/index.html @@ -181,7 +181,7 @@

任务连接

版本与帮助
-

MiniMax Pet 0.9.4

+

MiniMax Pet 0.10.0

@@ -201,19 +201,31 @@

任务连接

diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs new file mode 100644 index 00000000..0aa56603 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/live-progress.mjs @@ -0,0 +1,106 @@ +import { t } from './i18n.mjs'; +import { createCompletionInbox } from './completion-inbox.mjs'; + +const textOf = (value) => typeof value === 'string' ? value : ''; +const commandTool = /(?:^|[_.:-])(?:bash|shell|terminal|powershell|command|exec|runshellcommand|run_shell_command|run_command|execute_command)(?:$|[_.:-])/i; +const MAX_TEXT = 24_000; +const joinText = (committed, delta) => [committed, delta].filter(Boolean).join('\n\n'); + +function toolLabel(event) { + const action = event.type === 'tool.started' ? 'working' : event.ok ? 'done' : 'error'; + return commandTool.test(event.name) ? t(`live.command.${action}`) : t(`live.tool.${action}`, { name: event.name }); +} + +export function createLiveProgress({ button, onChange, isVisibleSession }) { + const badge = button.querySelector('.desk-bell-badge'); + const conversations = new Map(); + let writes = Promise.resolve(); + const inbox = createCompletionInbox({ onChange(change) { + writes = writes.catch(() => {}).then(async () => { + const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(change), keepalive: true }; + for (let attempt = 0; attempt < 3; attempt++) { + try { + if ((await fetch('/api/completions', options)).ok) return; + } catch { /* Retry a transient connection failure below. */ } + await new Promise((resolve) => setTimeout(resolve, 200 * (attempt + 1))); + } + console.warn('[pet] completion_store_write_failed'); + }); + } }); + let running = false, active = false, disposed = false, timer = null; + const unread = () => inbox.rows.filter((row) => isVisibleSession(row.sessionId)); + + function paint() { + if (disposed) return; + const count = unread().length; + button.hidden = !active || (!count && !running); + button.title = count ? t('live.unreadCount', { count }) : t('live.show'); + button.setAttribute('aria-label', button.title); + badge.hidden = count === 0; + badge.textContent = count > 99 ? '99+' : String(count); + } + function schedule() { + if (disposed) return; + paint(); + if (timer === null) timer = setTimeout(() => { timer = null; if (!disposed) onChange?.(); }, 85); + } + + function receive(event) { + if (disposed || !event?.sessionId || !event.turnId) return; + if (!['turn.started', 'turn.finished', 'tool.started', 'tool.finished', 'text.delta', 'message.committed'].includes(event.type)) return; + let progress = conversations.get(event.sessionId); + if (!progress || progress.turnId !== event.turnId) { + progress = { turnId: event.turnId, steps: [], committed: '', delta: '' }; + conversations.delete(event.sessionId); + conversations.set(event.sessionId, progress); + if (conversations.size > 4) conversations.delete(conversations.keys().next().value); + } + if (event.type === 'text.delta') progress.delta = (progress.delta + textOf(event.text)).slice(-MAX_TEXT); + else if (event.type === 'message.committed') { + progress.committed = joinText(progress.committed, textOf(event.text)).slice(-MAX_TEXT); + progress.delta = ''; + } else if (event.type === 'tool.started' || event.type === 'tool.finished') { + const name = textOf(event.name).slice(0, 120); + if (!name) return; + const previous = progress.steps.at(-1); + if (event.type === 'tool.finished' && previous?.type === 'tool.started' && previous.name === name) progress.steps.pop(); + progress.steps.push({ type: event.type, name, ok: event.ok === true }); + if (progress.steps.length > 6) progress.steps.shift(); + } else if (event.type === 'turn.finished') { + if (textOf(event.text)) { progress.committed = event.text.slice(-MAX_TEXT); progress.delta = ''; } + } + if (timer === null) timer = setTimeout(() => { timer = null; if (!disposed) onChange?.(); }, 85); + } + + async function refresh() { + try { + const response = await fetch('/api/completions', { cache: 'no-store' }); + if (!response.ok) return; + const { records } = await response.json(); + if (!disposed && Array.isArray(records)) { inbox.restore(records); schedule(); } + } catch { /* The in-memory inbox can still receive new completions. */ } + } + + void refresh(); + return { + receive, refresh, + get unread() { return unread(); }, + progress(sessionId) { + const progress = conversations.get(sessionId); + return progress && { turnId: progress.turnId, text: joinText(progress.committed, progress.delta), steps: progress.steps.map(toolLabel) }; + }, + complete(row, viewed = false) { + const progress = conversations.get(row.sessionId); + inbox.complete({ ...row, text: row.text || (progress ? joinText(progress.committed, progress.delta) : '') }, { viewed }); + schedule(); + }, + viewed(sessionId, turnId) { if (inbox.view(sessionId, turnId)) schedule(); }, + update(hasRunning, show) { + running = hasRunning; active = show; + paint(); + }, + clear() { conversations.clear(); schedule(); }, + translate: paint, + dispose() { disposed = true; clearTimeout(timer); conversations.clear(); inbox.clear(); }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/markdown.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/markdown.mjs index cb2f1771..ba00aefb 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/markdown.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/markdown.mjs @@ -4,6 +4,7 @@ // createTextNode, so model output can never inject markup. import { parseMarkdown } from './vendor/markdown.mjs'; import { t } from './i18n.mjs'; +import { deliveryFormat } from './delivery-formats.mjs'; // A reply is at most a few thousand characters in practice. Keep a ceiling so one // pathological response cannot stall the page, and bound the parse cache. @@ -119,7 +120,83 @@ function appendInline(doc, parent, children) { // Block nodes // --------------------------------------------------------------------------- -function blockNode(doc, node) { +function deliveryItems(value) { + const block = /^\s*\s*([\s\S]*?)<\/deliver-assets>\s*$/iu.exec(value); + if (!block) return []; + const items = []; + for (const [, attributes] of block[1].matchAll(/]|"[^"]*"|'[^']*')*)\/>/giu)) { + const fields = new Map(); + for (const [, name, double, single] of attributes.matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gu)) { + fields.set(name.toLowerCase(), double ?? single); + } + const path = fields.get('src') || ''; + const name = path.split(/[/\\]/u).at(-1) || ''; + const caption = (fields.get('caption') || '').trim(); + const nodeId = fields.get('node_id') || ''; + const kind = deliveryFormat(path)?.kind || (fields.get('type')?.toLowerCase() === 'image' && nodeId ? 'image' : ''); + items.push({ path, name, caption, nodeId, kind }); + } + return items; +} + +function imageLabel(caption) { + return t('markdown.image', { alt: caption ? t('markdown.imageAlt', { alt: caption }) : '' }); +} + +function renderDeliveries(doc, items, { sessionId, onOpenDelivery }) { + const group = doc.createElement('div'); + group.className = 'md-delivery'; + for (const { nodeId, name, path, caption, kind } of items) { + const title = caption || name || (kind === 'image' ? imageLabel('') : t('delivery.file')); + const params = new URLSearchParams({ session: sessionId || '' }); + if (kind === 'image' && /^[\w-]{1,128}$/u.test(nodeId)) params.set('node', nodeId); + else if (path) params.set('file', path); + const url = '/api/session-asset?' + params; + const previewable = Boolean(kind && sessionId && onOpenDelivery && (params.has('node') || params.has('file'))); + const open = () => onOpenDelivery({ asset: Object.fromEntries(params), title }); + if (kind === 'image' && previewable) { + const figure = doc.createElement('figure'); + const label = doc.createElement('figcaption'); + label.textContent = title; + const button = doc.createElement('button'); + button.type = 'button'; + button.className = 'md-delivery-thumbnail'; + button.setAttribute('aria-label', t('delivery.openImage', { title })); + button.addEventListener('click', open); + const image = doc.createElement('img'); + image.alt = title; + image.loading = 'lazy'; + image.decoding = 'async'; + image.addEventListener('error', () => { + button.remove(); + label.append(doc.createTextNode(` · ${t('markdown.imageUnavailable')}`)); + }, { once: true }); + image.src = url; + button.append(image); + figure.append(button, label); + group.append(figure); + continue; + } + const file = doc.createElement(previewable ? 'button' : 'div'); + file.className = 'md-delivery-file'; + if (previewable) { + file.type = 'button'; + file.addEventListener('click', open); + } + const label = doc.createElement('span'); + label.textContent = title; + file.append(label); + if (name && name !== title) { + const filename = doc.createElement('small'); + filename.textContent = name; + file.append(filename); + } + group.append(file); + } + return group; +} + +function blockNode(doc, node, context) { switch (node.type) { case 'paragraph': { const p = doc.createElement('p'); @@ -150,7 +227,7 @@ function blockNode(doc, node) { li.classList.add('md-task'); li.dataset.checked = String(item.checked); } - appendBlocks(doc, li, item.children, { tight: !item.spread }); + appendBlocks(doc, li, item.children, { tight: !item.spread, context }); list.append(li); } return list; @@ -167,7 +244,7 @@ function blockNode(doc, node) { case 'blockquote': { const quote = doc.createElement('blockquote'); quote.className = 'md-quote'; - appendBlocks(doc, quote, node.children, {}); + appendBlocks(doc, quote, node.children, { context }); return quote; } case 'thematicBreak': { @@ -201,8 +278,9 @@ function blockNode(doc, node) { return wrap; } case 'html': { - // Raw HTML is shown as its literal source, never parsed: the author meant it - // to be a block, so dropping it silently would hide half the reply. + const items = deliveryItems(node.value); + if (items.length) return renderDeliveries(doc, items, context); + // Other HTML stays literal text. const p = doc.createElement('p'); p.className = 'md-p md-raw'; p.textContent = typeof node.value === 'string' ? node.value : ''; @@ -217,7 +295,7 @@ function blockNode(doc, node) { // degrade to their text rather than disappearing. const container = doc.createElement('div'); container.className = 'md-block'; - appendBlocks(doc, container, node.children, {}); + appendBlocks(doc, container, node.children, { context }); if (!container.childNodes.length) container.textContent = inlineText(node); return container; } @@ -246,10 +324,10 @@ function tableRow(doc, row, cellTag, align = []) { return tr; } -function appendBlocks(doc, parent, children, { tight = false } = {}) { +function appendBlocks(doc, parent, children, { tight = false, context } = {}) { for (const child of Array.isArray(children) ? children : []) { if (!child || child.type === 'footnoteDefinition') continue; - const node = blockNode(doc, child); + const node = blockNode(doc, child, context); // A list item that holds only paragraphs becomes plain inline content when the // list is tight, matching how markdown renders without paragraph spacing. if (tight && child.type === 'paragraph' && node.classList?.contains('md-p')) { @@ -271,15 +349,15 @@ function appendBlocks(doc, parent, children, { tight = false } = {}) { * A reply that is still streaming changes on every poll, so the reader's scroll * position is captured and restored around the replace. */ -export function renderMarkdown(target, text) { +export function renderMarkdown(target, text, context = {}) { const source = typeof text === 'string' ? text : ''; - const key = sourceKey(source); + const key = `${context.sessionId || ''}:${sourceKey(source)}`; if (target.dataset.mdSource === key) return false; const doc = target.ownerDocument; const fragment = doc.createDocumentFragment(); for (const child of tree(source).children) { if (!child || child.type === 'footnoteDefinition') continue; - const node = blockNode(doc, child); + const node = blockNode(doc, child, context); if (node) fragment.append(node); } const keepTop = target.scrollTop; @@ -332,8 +410,11 @@ function blockText(node, depth = 0) { return typeof node.value === 'string' ? node.value : ''; case 'thematicBreak': return '—'; - case 'html': - return typeof node.value === 'string' ? node.value : ''; + case 'html': { + const items = deliveryItems(node.value); + return items.length ? items.map(({ kind, caption, name }) => kind === 'image' + ? imageLabel(caption || name) : caption || name || t('delivery.file')).join(' · ') : typeof node.value === 'string' ? node.value : ''; + } case 'list': { const items = Array.isArray(node.children) ? node.children : []; return items.map((item, index) => { diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/pet-app.js b/sources/minimax-ai/minimax-pet/miniapp/client/pet-app.js index f65d3d74..5eae5376 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/pet-app.js +++ b/sources/minimax-ai/minimax-pet/miniapp/client/pet-app.js @@ -2,9 +2,11 @@ import { STATUS_ANIM, createActivitySource } from './activity.mjs'; import { DEFAULT_PREFERENCES, MAX_NOTICE_TIMEOUT_SECONDS, loadPreferences, preferenceRequest } from './preferences.mjs'; import { restoreWindowPosition, fitWindowToScreen } from './window-position.mjs'; -import { aggregateText, notificationItems, noticeRemaining, notificationText, visibleNotices, createAnimationGate } from './pet-presentation.mjs'; +import { aggregateText, notificationItems, noticeKey, noticeRemaining, notificationText, visibleNotices, createAnimationGate } from './pet-presentation.mjs'; import { createReminderStore } from './activity-reminders.mjs'; import { createCompactPetView, taskStatus } from './compact-pet-view.mjs'; +import { createPetQuota } from './pet-quota.mjs'; +import { createLiveProgress } from './live-progress.mjs'; import { createNotificationPreviews } from './notification-previews.mjs'; import { createAskObserver } from './ask-observer.mjs'; import { createPanelNavigation } from './panel-navigation.mjs'; @@ -36,6 +38,11 @@ const THUMB_SCALE = 0.375; const DRAG_THRESHOLD = 4; const DIRECTION_HYSTERESIS = 12; const LOOK_DEAD_ZONE = 1; +const LOOK_MARGIN = 12; +const WINDOWS_DESKTOP = /^win/i.test(navigator.userAgentData?.platform ?? navigator.platform ?? ''); +let desktopDragWarm; +let desktopDragReady = false; +let deskPointerFrame = null; // --------------------------------------------------------------------------- // Small helpers @@ -79,6 +86,7 @@ const params = new URLSearchParams(location.search); const host = window.mcode?.miniapp ?? null; const win = host?.window ?? null; const agent = host?.agent ?? null; +const hostMessage = host?.message ?? null; const hostNavigation = host?.host?.navigation ?? null; const canOpenSession = typeof hostNavigation?.open === 'function'; const explicitDemo = params.get('demo') === '1'; @@ -144,19 +152,17 @@ const app = { ctFailures: 0, pointer: null, drag: null, - dragMove: null, dragging: false, menuOpen: false, menuView: 'root', menuAnchor: { x: 0, y: 0 }, menuCloseTimer: null, - quickbarTimer: null, transient: null, transientTimer: null, - bubbleSessionId: null, oneShot: false, oneShotToken: 0, looking: false, + workbenchNodded: false, }; const importState = { @@ -246,23 +252,47 @@ const els = { bubbleTitle: $('bubble-title'), bubbleText: $('bubble-text'), notificationStack: $('notification-stack'), + noticeList: $('pet-notice-list'), quickbar: $('quickbar'), - quickTasks: $('quick-tasks'), - quickMenu: $('quick-menu'), + quickChat: $('quick-chat'), + quickQuota: $('quick-quota'), + quotaRing: $('quick-quota-ring'), + quickBell: $('quick-bell'), menu: $('menu'), }; let animationGate = null; let workbenchView = null; +let previewBlurDeadline = 0; +let bellView = ''; +let petNod; +let shortcutHideTimer; +let shortcutSize = { width: 84, height: 42 }; +let completionSequence = 0; +let desktopCatalog; + +async function refreshDesktopCatalog() { + try { + const response = await fetch('/api/desktop-catalog', { cache: 'no-store' }); + if (!response.ok) throw new Error('desktop_catalog_unavailable'); + const { sessions, projects } = await response.json(); + const bySession = new Map(); + const firstSession = new Map(); + for (const row of sessions) { + bySession.set(row.id, row.projectId); + if (!firstSession.has(row.projectId)) firstSession.set(row.projectId, row.id); + } + desktopCatalog = { bySession, firstSession, projects }; + } catch { desktopCatalog = undefined; } +} +let petQuota = null; +let liveProgress = null; +let notificationTask = null; const reminders = createReminderStore(); -// The desktop window is one fixed size that already fits the open card. Toggling the card -// by resizing the native window moves its origin and repaints the old layout at the new -// top-left, so the pet visibly jumped up (and left, while the card was wider). Keeping the -// geometry constant removes that class of flicker entirely; the area above the pet is -// transparent and forwards clicks. +// Keep room for the panel below the pet and task notifications above it. +// Both panels open inside the existing bounds without moving the sprite. const DESK_WIDTH = 280; -const deskHeight = (scale) => Math.max(380, Math.ceil(208 * scale) + 332); -// Saved positions are the top-left a 280x340 window would have had, so they keep working -// after the window grows: the bottom edge is what must stay fixed on screen. +const deskHeight = (scale) => Math.ceil(208 * scale) + 422; +// Positions use the bottom-right anchor of the native window. const LEGACY_DESK_HEIGHT = 340; const savedTopLeft = (position, height) => ({ x: position.x, y: position.y + LEGACY_DESK_HEIGHT - height }); let notificationPreviews = null; @@ -316,13 +346,39 @@ function availabilityText() { } function applyActivity() { - renderActivityUI(); - renderBubble(); - renderMenuIfOpen(); - if (!app.pet || app.oneShot || app.dragging) return; + renderVisibleActivity(); + if (!app.pet || app.dragging || petNod) return; + if (app.workbenchOpen && !app.workbenchNodded && player.supportsLook && !reducedMotion.matches && !document.hidden) { + app.oneShotToken++; + app.oneShot = false; + player.look(180); + app.looking = app.workbenchNodded = true; + petNod = els.sprite.animate([{ transform: 'none' }, { transform: 'translateY(2px) scaleY(.985)', offset: .55 }, + { transform: 'none' }], { duration: 175, easing: 'ease-out' }); + petNod.onfinish = () => { + petNod = undefined; + applyActivity(); + }; + return; + } + if (app.oneShot) return; const desired = desiredAnimation(); - if (!['idle', 'running', 'waving'].includes(desired.state)) stopLook(); animationGate?.apply(desired.state, desired.key, { loop: app.source === 'demo' }); + followPointer(); +} + +function renderVisibleActivity() { + if (document.hidden) return; + if (app.mode === 'window') { + renderDeskShortcuts(); + renderSpriteActivityLabel(); + syncNotificationPreviews(); + renderBubble(); + renderMenuIfOpen(); + if (app.workbenchOpen) renderCompactView(); + } else { + renderActivityUI(); + } } function playOneShot(state) { @@ -344,10 +400,27 @@ async function initActivitySource() { if (disposed) return; syncObservedAsks(); applyActivity(); + }, onProgress: (event) => { + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.receive(event); } }); disposers.push(() => askObserver.dispose()); activitySource = createActivitySource({ agent, + refreshCatalog: refreshDesktopCatalog, + allowSession: (id) => Boolean(desktopCatalog?.bySession.has(id)), + onSettled: (event) => { + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.receive(event); + if (event.status === 'finished') { + const row = app.sessions.find((item) => item.sessionId === event.sessionId); + const completion = { sessionId: event.sessionId, turnId: event.turnId || row?.observedTurnId || `observed-${++completionSequence}`, + title: event.title || row?.title, text: typeof event.text === 'string' ? event.text : '', updatedAtMs: Date.now() }; + if (desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.complete(completion); + else void refreshDesktopCatalog().then(() => { + if (!disposed && desktopCatalog?.bySession.has(event.sessionId)) liveProgress?.complete(completion); + }); + } + }, + pollingEnabled: !document.hidden, onChange(snapshot) { Object.assign(app, { availability: snapshot.availability, sessionsError: snapshot.error, @@ -355,22 +428,40 @@ async function initActivitySource() { selectedSessionId: snapshot.selectedSessionId, detail: snapshot.detail, detailLoading: snapshot.detailLoading, detailError: snapshot.detailError, }); - askObserver.update({ availability: snapshot.availability, sessions: snapshot.sessions, selectedSessionId: snapshot.selectedSessionId }); + if (snapshot.availability === 'not_permitted') liveProgress?.clear(); + syncAskWatches(); syncObservedAsks(); - renderHeader(); + if (app.mode !== 'window' && !document.hidden) renderHeader(); applyActivity(); }, }); disposers.push(() => activitySource.dispose()); + listen(document, 'visibilitychange', () => { + activitySource.setPollingEnabled(!document.hidden); + petQuota?.setActive(app.mode === 'window' && !document.hidden); + if (document.hidden) stopNoticeTimer(); + else { + void liveProgress?.refresh(); + if (app.mode !== 'window') renderHeader(); + applyActivity(); + } + }); void activitySource.start(); } function syncObservedAsks() { const ids = new Set(askObserver?.getState().needsAnswerIds ?? []); - app.sessions = app.rawSessions.map((row) => ({ ...row, needsAnswer: row.status === 'running' && ids.has(row.sessionId) })); + app.sessions = app.rawSessions.filter((row) => desktopCatalog?.bySession.has(row.sessionId)) + .map((row) => ({ ...row, needsAnswer: row.status === 'running' && ids.has(row.sessionId) })); reminders.update(app.sessions); } +function syncAskWatches() { + const eligible = app.rawSessions.filter((row) => desktopCatalog?.bySession.has(row.sessionId)); + askObserver?.update({ availability: app.availability, sessions: eligible, trackSelected: app.mode === 'window', + selectedSessionId: app.selectedSessionId || eligible.find((row) => row.status === 'running')?.sessionId }); +} + function setDemoStatus(status) { if (!Object.hasOwn(STATUS_ANIM, status)) return; app.demoStatus = status; @@ -440,21 +531,40 @@ function describeOpenError(code) { /** Must be called synchronously from a click or key handler: the Host checks user activation. */ function openSessionInHost(sessionId) { + return openInHost({ id: 'session', sessionId, source: 'local' }); +} + +function openInHost(target) { if (!canOpenSession) return Promise.resolve({ kind: 'error', text: t('tasks.openNoApi') }); - return callBridge(() => hostNavigation.open({ id: 'session', sessionId, source: 'local' })).then( + return callBridge(() => hostNavigation.open(target)).then( (result) => { - if (result?.status === 'opened') return { kind: 'ok', text: t('tasks.openOpened') }; + if (result?.status === 'opened') return { kind: 'ok', text: target.id === 'session' ? t('tasks.openOpened') : '' }; if (result?.reason === 'user_cancelled') return { kind: 'info', text: t('tasks.openCancelled') }; return { kind: 'info', text: t('tasks.openSuperseded') }; }, (error) => { const code = errCode(error); - console.warn('[pet] open_session_failed:', code, error); + console.warn('[pet] open_host_target_failed:', code, error); return { kind: 'error', text: describeOpenError(code) }; }, ); } +function appendDraftToHost(text) { + if (app.availability !== 'ready' || !app.selectedSessionId || app.selectedSessionId !== app.originSession?.sessionId) { + return { kind: 'error', text: t('tasks.openTargetUnavailable') }; + } + return callBridge(() => hostMessage.append(text)).then( + () => ({ kind: 'ok', text: t('chat.draftAdded') }), + (error) => { + const code = errCode(error); + if (code === 'user_cancelled') return { kind: 'info', text: t('common.cancelled') }; + if (code === 'result_unknown') return { kind: 'error', text: t('chat.draftUnknown') }; + return { kind: 'error', text: t('chat.actionError', { code }) }; + }, + ); +} + function openSelectedSession() { const sessionId = app.selectedSessionId; if (!sessionId) return; @@ -479,6 +589,8 @@ function applyLanguage(tag) { root.lang = next; applyStaticText(); document.title = t('app.title'); + petQuota?.translate(); + liveProgress?.translate(); renderAll(); renderNoticeTimeout(); return next; @@ -621,7 +733,7 @@ function onWindowState(state) { }); return; } - if (!app.restoringPosition) rememberPosition(); + if (!app.restoringPosition && !app.dragging) rememberPosition(); } if (state.mode !== app.mode) applyMode(state.mode); } @@ -644,10 +756,15 @@ function applyMode(mode) { const leavingWindow = app.mode === 'window' && mode !== 'window'; if (leavingWindow) { app.hovered = false; animationGate?.invalidate(); } app.mode = mode; + bellView = ''; + previewBlurDeadline = 0; + notificationTask = null; + syncAskWatches(); app.workbenchOpen = false; + app.workbenchNodded = false; app.compacting = false; app.workbenchRevision++; - workbenchView?.close(); + workbenchView?.close({ animate: false }); root.classList.remove('workbench-open'); if (mode !== 'window') { app.positionRestoreToken++; app.restoringPosition = false; app.awaitingPointer = false; } root.classList.toggle('mode-window', mode === 'window'); @@ -657,15 +774,16 @@ function applyMode(mode) { els.desk.hidden = mode !== 'window'; closeMenu(); - hideQuickbar(); cancelDrag(); stopLook(); + renderDeskShortcuts(); app.pointer = null; clearForwardingWatchdog(); app.ctSafeHold = false; if (leavingWindow) app.clickThrough = null; if (mode === 'window') { + warmDesktopDrag(); els.deskPetSlot.append(els.sprite); els.sprite.tabIndex = 0; els.sprite.setAttribute('role', 'button'); @@ -742,7 +860,7 @@ function isOverPet(x, y) { function isOverOverlay(x, y) { return [els.bubble, els.notificationStack, els.quickbar, els.menu, els.workbench].some( - (el) => !el.hidden && pointInRect(el.getBoundingClientRect(), x, y), + (el) => !el.hidden && !el.inert && pointInRect(el.getBoundingClientRect(), x, y), ); } @@ -755,7 +873,7 @@ function refreshInteractivity() { const interactive = app.dragging || app.menuOpen || - (p ? isOverPet(p.x, p.y) || isOverOverlay(p.x, p.y) : app.workbenchOpen); + (p ? isOverPet(p.x, p.y) || isOverOverlay(p.x, p.y) : app.workbenchOpen || Boolean(bellView)); setClickThrough(!interactive); } @@ -838,20 +956,35 @@ function onDocumentMouseMove(e) { if (app.restoringPosition) return; app.awaitingPointer = false; noteForwardedMove(e); - if (!app.dragging && !insideDesk(e.clientX, e.clientY)) { - onPointerLeave(); + if (app.dragging) { + app.pointer = { x: e.clientX, y: e.clientY }; return; } app.pointer = { x: e.clientX, y: e.clientY }; - refreshInteractivity(); - trackMenuHover(e.clientX, e.clientY); - updateLook(e.clientX, e.clientY); + if (deskPointerFrame !== null) return; + deskPointerFrame = requestAnimationFrame(() => { + deskPointerFrame = null; + const point = app.pointer; + if (disposed || app.mode !== 'window' || app.dragging || !point) return; + if (!insideDesk(point.x, point.y)) { + onPointerLeave(); + return; + } + syncQuickbar(); + refreshInteractivity(); + trackMenuHover(point.x, point.y); + followPointer(); + }); } function onPointerLeave() { if (app.mode !== 'window') return; + if (deskPointerFrame !== null) cancelAnimationFrame(deskPointerFrame); + deskPointerFrame = null; app.pointer = null; - stopLook(); + app.hovered = false; + syncQuickbar(); + followPointer(); refreshInteractivity(); // stays interactive while menu/drag force it if (app.menuOpen) armMenuClose(); } @@ -860,25 +993,26 @@ function onPointerLeave() { // Look direction (v2) + idle liveliness // --------------------------------------------------------------------------- -function updateLook(x, y) { - if (!app.pet || !player.supportsLook) return; +function followPointer() { + if (petNod || !app.pet || !player.supportsLook) return; + const point = app.pointer; if ( + !point || app.mode !== 'window' || - app.hovered || app.dragging || app.menuOpen || app.oneShot || - app.workbenchOpen || reducedMotion.matches || - !['idle', 'running', 'waving'].includes(activityAnim()) + document.hidden ) { stopLook(); return; } const r = els.sprite.getBoundingClientRect(); - const dx = x - (r.left + r.width / 2); - const dy = y - (r.top + r.height / 2); - if (Math.hypot(dx, dy) <= LOOK_DEAD_ZONE) { + const dx = point.x - (r.left + r.width / 2); + const dy = point.y - (r.top + r.height / 2); + if (Math.abs(dx) > r.width / 2 + LOOK_MARGIN || Math.abs(dy) > r.height / 2 + LOOK_MARGIN || + Math.hypot(dx, dy) <= LOOK_DEAD_ZONE) { stopLook(); return; } @@ -889,6 +1023,8 @@ function updateLook(x, y) { } function stopLook() { + petNod?.cancel(); + petNod = undefined; if (!app.looking) return; app.looking = false; player?.look(null); @@ -902,6 +1038,26 @@ function noteInteraction() { // Dragging // --------------------------------------------------------------------------- +async function requestDesktopDrag(action, offset = {}) { + try { + const response = await fetch('/api/desktop-drag', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ action, ...offset }), + keepalive: action === 'stop', + }); + return response.ok && (await response.json()).ok === true; + } catch { + return false; + } +} + +function warmDesktopDrag() { + if (!WINDOWS_DESKTOP || desktopDragReady || desktopDragWarm) return; + desktopDragWarm = requestDesktopDrag('warm').then((ready) => { desktopDragReady = ready; }) + .finally(() => { desktopDragWarm = null; }); +} + function onSpritePointerDown(e) { if (app.mode !== 'window' || app.restoringPosition || app.scaleChanging || e.button !== 0 || !app.pet) return; noteInteraction(); @@ -912,7 +1068,7 @@ function onSpritePointerDown(e) { } catch (error) { console.warn('[pet] pointer_capture_failed:', errCode(error), error); } - const startX = app.winPos?.x ?? e.clientX; + const startX = e.screenX; app.drag = { pointerId: e.pointerId, grabX: e.clientX, @@ -926,10 +1082,7 @@ function onSpritePointerDown(e) { function onSpritePointerMove(e) { const d = app.drag; - // While the Host is moving the window, client coordinates may be relative to either origin. - // Resume from the next pointer event after the Host confirms the new bounds. - if (!d || e.pointerId !== d.pointerId || app.scaleChanging || app.dragMove) return; - const origin = app.winPos; + if (!d || e.pointerId !== d.pointerId || app.scaleChanging) return; const dx = e.clientX - d.grabX; const dy = e.clientY - d.grabY; if (!d.active) { @@ -939,25 +1092,17 @@ function onSpritePointerMove(e) { app.oneShotToken++; app.oneShot = false; stopLook(); - hideQuickbar(); + renderDeskShortcuts(); els.sprite.classList.add('is-dragging'); refreshInteractivity(); - if (!origin) console.warn('[pet] drag_without_window_position: no window position yet, animation only'); - } - const x = origin ? Math.round(origin.x + dx) : e.clientX; - updateDragDirection(d, x); - if (!origin) return; - const y = Math.round(origin.y + dy); - if (x === origin.x && y === origin.y) return; - // On Windows a position-only update can return enlarged native bounds. Send the - // design size with the move, rather than carrying the enlarged bounds into the next one. - app.dragMove = callBridge(() => win.update({ x, y, width: DESK_WIDTH, height: deskHeight(prefs.scale) })).then((state) => { - if (app.mode === 'window') onWindowState(state); - }).catch((error) => { - const code = errCode(error); - if (code === 'not_permitted') console.debug('[pet] drag_move_rejected: not_permitted (target is off every display)'); - else console.warn('[pet] drag_move_failed:', code, error); - }).finally(() => { app.dragMove = null; }); + const limit = (offset) => Math.max(-512, Math.min(512, Math.round(offset))); + void requestDesktopDrag('drag', { dx: limit(dx), dy: limit(dy) }).then((started) => { + if (!started && app.drag === d && !disposed && app.mode === 'window') { + showTransient(t('mode.positionFailed', { code: 'desktop_drag_unavailable' }), 'error'); + } + }); + } + updateDragDirection(d, e.screenX); } function updateDragDirection(d, sx) { @@ -986,7 +1131,8 @@ function updateDragDirection(d, sx) { function finishDrag(e, cancelled) { const d = app.drag; if (!d || e.pointerId !== d.pointerId) return; - if (!cancelled && d.active) onSpritePointerMove(e); + if (cancelled && d.active) void requestDesktopDrag('stop'); + else if (d.active) onSpritePointerMove(e); app.drag = null; try { if (els.sprite.hasPointerCapture(e.pointerId)) els.sprite.releasePointerCapture(e.pointerId); @@ -996,22 +1142,25 @@ function finishDrag(e, cancelled) { els.sprite.classList.remove('is-dragging'); if (d.active) { app.dragging = false; - if (cancelled || desiredAnimation().state === 'jumping') { + renderDeskShortcuts(); + if (app.workbenchOpen || cancelled || desiredAnimation().state === 'jumping') { // Hover already owns the same three-cycle jump; release must not queue it twice. animationGate?.invalidate(); applyActivity(); } else playOneShot('jumping'); - if (!app.dragMove) callBridge(() => win.getState()).then(onWindowState, logError('get_state_after_drag')); + callBridge(() => win.getState()).then(onWindowState, logError('get_state_after_drag')); } else if (!cancelled) { - void openWorkbench('tasks'); + void openWorkbench('chat'); } refreshInteractivity(); } function cancelDrag() { - if (!app.drag && !app.dragging) return; + if (!app.drag && !app.dragging) return undefined; + const stopped = app.drag?.active ? requestDesktopDrag('stop') : undefined; app.drag = null; app.dragging = false; els.sprite.classList.remove('is-dragging'); + return stopped; } // --------------------------------------------------------------------------- @@ -1034,15 +1183,12 @@ function renderBubble() { renderNotificationStack(); if (app.workbenchOpen) { els.bubble.hidden = true; - app.bubbleSessionId = null; refreshInteractivity(); return; } - const a = activity(); let title = ''; let text = ''; let kind = 'info'; - let clickable = false; if (app.transient) { ({ text, kind } = app.transient); } else if (!app.pet && app.loadError) { @@ -1051,30 +1197,20 @@ function renderBubble() { } else if (app.source === 'real' && app.availability !== 'ready') { text = availabilityText(); kind = app.availability === 'connecting' ? 'info' : 'error'; - } else { - if (a.session) { - text = a.session.needsAnswer ? t('status.needsAnswer') : a.status === 'running' ? '' : statusText(a.status); - title = a.session.title; - clickable = !!text; - } - } if (app.source === 'demo') { title = t('tasks.demoTitle'); text = statusText(app.demoStatus) ? t('tasks.demoStatus', { status: statusText(app.demoStatus) }) : ''; - clickable = false; } els.bubbleTitle.textContent = title; els.bubbleTitle.hidden = !title; els.bubbleText.textContent = text; els.bubble.dataset.kind = kind; - els.bubble.classList.toggle('is-clickable', clickable); els.bubble.tabIndex = text ? 0 : -1; els.bubble.setAttribute('aria-label', text ? (title ? t('desk.bubbleAriaTitle', { title, text }) : t('desk.bubbleAria', { text })) : t('desk.bubbleIdle')); els.bubble.hidden = !text || (!app.transient && !els.notificationStack.hidden); - app.bubbleSessionId = clickable && a.session ? a.session.sessionId : null; refreshInteractivity(); } @@ -1083,96 +1219,273 @@ function stopNoticeTimer() { noticeTimer = null; } -function armNoticeTimer(shown) { +function armNoticeTimer(shown, options) { stopNoticeTimer(); - if (!(prefs.noticeTimeout > 0) || noticePaused || !shown.length) return; let next = Infinity; for (const item of shown) { - const remaining = noticeRemaining(item, { shownAt: noticeShownAt, now: Date.now(), timeoutSeconds: prefs.noticeTimeout }); + if (noticePaused && item.displayStatus !== 'completed') continue; + const remaining = noticeRemaining(item, options); if (remaining !== null) next = Math.min(next, remaining); } if (!Number.isFinite(next)) return; noticeTimer = setTimeout(() => { noticeTimer = null; renderBubble(); - }, Math.max(250, next + 50)); + }, Math.max(16, next)); } function pauseNotices(paused) { if (paused === noticePaused) return; const now = Date.now(); noticePaused = paused; - if (paused) { noticePauseAt = now; return; } - // Shift every card's start by the paused span so the remaining time is exact. - const pausedMs = now - noticePauseAt; - noticePauseAt = 0; - if (pausedMs > 0) for (const [id, since] of noticeShownAt) noticeShownAt.set(id, since + pausedMs); + if (paused) noticePauseAt = now; + else { + for (const item of notificationItems(reminders.getState().items)) { + const key = noticeKey(item); + const since = noticeShownAt.get(key); + if (item.displayStatus !== 'completed' && Number.isFinite(since)) { + noticeShownAt.set(key, since + Math.max(0, now - Math.max(noticePauseAt, since))); + } + } + noticePauseAt = 0; + } renderBubble(); } -function renderNotificationStack() { - const container = els.notificationStack; - const all = notificationItems(reminders.getState().items); - const now = Date.now(); - // Records the moment a card first appeared; a card that stays hidden by the - // workbench keeps its original start instead of restarting on every paint. - for (const item of all) if (!noticeShownAt.has(item.sessionId)) noticeShownAt.set(item.sessionId, now); - for (const id of [...noticeShownAt.keys()]) if (!all.some((item) => item.sessionId === id)) noticeShownAt.delete(id); - const items = visibleNotices(all, { shownAt: noticeShownAt, now, timeoutSeconds: prefs.noticeTimeout }); - const visible = app.mode === 'window' && app.availability === 'ready' && items.length - && !app.workbenchOpen && !app.transient; - container.hidden = !visible; - // Keep a timer running only while cards can actually expire on screen. - if (visible) armNoticeTimer(items); else stopNoticeTimer(); - if (!visible) return; +function bellTasks() { + const running = app.sessions.filter((row) => row.status === 'running') + .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true) || b.updatedAtMs - a.updatedAtMs); + const runningIds = new Set(running.map((row) => row.sessionId)); + const finished = (liveProgress?.unread ?? []).filter((row) => !runningIds.has(row.sessionId)); + const included = new Set([...runningIds, ...finished.map((row) => row.sessionId)]); const previews = notificationPreviews?.getState().previews ?? {}; - const existing = new Map([...container.children].map((node) => [node.dataset.sessionId, node])); - const nodes = items.map((item) => { - let node = existing.get(item.sessionId); - if (!node) { - node = document.createElement('div'); node.className = 'pet-notice'; node.dataset.sessionId = item.sessionId; - const open = document.createElement('button'); open.type = 'button'; open.className = 'pet-notice-open'; - const title = document.createElement('strong'), preview = document.createElement('span'); preview.className = 'pet-notice-preview'; - open.append(title, preview); - open.addEventListener('click', () => { openTaskPreview(node.dataset.sessionId); }); - const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.className = 'pet-notice-dismiss'; dismiss.textContent = '×'; - dismiss.addEventListener('click', () => { reminders.dismiss(node.dataset.sessionId); applyActivity(); }); - node.append(open, dismiss); + const errors = reminders.getState().items.filter((row) => row.displayStatus === 'error' && !included.has(row.sessionId)); + return [ + ...running.map((row) => { + const progress = liveProgress?.progress(row.sessionId); + const preview = row.needsAnswer ? t('status.needsAnswer') + : progress?.steps.at(-1) || progress?.text || t('status.runningText'); + return { ...row, displayStatus: 'running', preview }; + }), + ...finished.map((row) => ({ ...row, displayStatus: 'completed', preview: row.text || t('desk.noticeCompleted') })), + ...errors.map((row) => ({ ...row, preview: notificationText(row, previews) })), + ]; +} + +function closeBellStack() { + if (!bellView) return false; + bellView = ''; + syncQuickbar(); + renderBubble(); + return true; +} + +function openNoticeInHost(id, toStop = false) { + if (app.availability !== 'ready' || !desktopCatalog?.bySession.has(id)) return; + if (toStop && !app.sessions.some((row) => row.sessionId === id && row.status === 'running')) return; + const completion = !toStop && liveProgress?.unread.find((row) => row.sessionId === id); + void openSessionInHost(id).then((result) => { + if (disposed) return; + if (result.kind === 'error') { + showTransient(result.text, 'error'); + return; } - const open = node.children[0]; - open.children[0].textContent = item.title; - // A notification shows a five-line preview, so markdown is flattened, not rendered. - open.children[1].textContent = markdownToPlainText(notificationText(item, previews)); - open.setAttribute('aria-label', t('desk.noticeView', { title: item.title })); - node.children[1].setAttribute('aria-label', t('desk.noticeClose', { title: item.title })); - return node; + if (result.kind !== 'ok' || !completion) return; + const native = app.sessions.find((row) => row.sessionId === id); + if (native?.liveCompleted && (!native.observedTurnId || native.observedTurnId === completion.turnId)) reminders.dismiss(id); + liveProgress?.viewed(id, completion.turnId); + applyActivity(); }); - if (nodes.length !== container.children.length || nodes.some((node, i) => node !== container.children[i])) container.replaceChildren(...nodes); } -function toggleQuickbar() { - if (els.quickbar.hidden) showQuickbar(); - else hideQuickbar(); -} -function showQuickbar() { - if (app.mode !== 'window') return; - els.quickbar.hidden = false; - armQuickbarHide(); - refreshInteractivity(); +function createNoticeCard(id) { + const node = document.createElement('div'); + node.className = 'pet-notice'; + node.dataset.sessionId = id; + node.setAttribute('role', 'listitem'); + const open = document.createElement('button'); + open.type = 'button'; + open.className = 'pet-notice-open'; + const title = document.createElement('strong'); + const preview = document.createElement('span'); + preview.className = 'pet-notice-preview'; + open.append(title, preview); + open.addEventListener('click', () => { + if (node.dataset.expand === 'true') { + bellView = 'expanded'; + syncQuickbar(); + renderBubble(); + els.noticeList.querySelector('.pet-notice-open')?.focus({ preventScroll: true }); + } else openTaskPreview(id); + }); + const actions = document.createElement('span'); + actions.className = 'pet-notice-actions'; + const button = (className, text, action) => { + const element = document.createElement('button'); + element.type = 'button'; + element.className = className; + element.textContent = text; + element.addEventListener('click', action); + actions.append(element); + }; + button('pet-notice-action pet-notice-jump', '↵', () => openNoticeInHost(id)); + button('pet-notice-action pet-notice-stop', '■', () => openNoticeInHost(id, true)); + button('pet-notice-dismiss', '×', () => { reminders.dismiss(id); applyActivity(); }); + const count = document.createElement('span'); + count.className = 'pet-stack-count'; + count.setAttribute('aria-hidden', 'true'); + actions.append(count); + node.append(open, actions); + return node; +} + +function animateNotice(node, leaving) { + const resting = { opacity: 1, transform: 'translateY(0) scale(1)' }; + const tucked = { opacity: 0, transform: 'translateY(9px) scale(.94)' }; + return node.animate(leaving ? [resting, tucked] : [tucked, resting], + { duration: leaving ? 155 : 190, easing: leaving ? 'ease-in' : 'ease-out', fill: leaving ? 'forwards' : 'none' }); +} + +function syncNoticeCards(nodes, animate) { + const list = els.noticeList; + const wanted = new Set(nodes); + for (const node of [...list.children]) { + if (wanted.has(node)) continue; + if (!animate || node.dataset.automatic !== 'true') { node.remove(); continue; } + if (node.dataset.leaving === 'true') continue; + node.dataset.leaving = 'true'; + node.inert = true; + node.getAnimations().forEach((animation) => animation.cancel()); + animateNotice(node, true).onfinish = () => { + node.remove(); + if (!disposed) renderBubble(); + }; + } + nodes.forEach((node, index) => { + const entering = node.parentElement !== list; + if (node.dataset.leaving === 'true') { + node.getAnimations().forEach((animation) => animation.cancel()); + delete node.dataset.leaving; + } + if (list.children[index] !== node) list.insertBefore(node, list.children[index] || null); + if (animate && entering) animateNotice(node, false); + }); } -function hideQuickbar() { - clearTimeout(app.quickbarTimer); - if (els.quickbar.hidden) return; - els.quickbar.hidden = true; - refreshInteractivity(); + +function layoutExpandedNotices(count) { + const expanded = count > 0; + els.desk.classList.toggle('show-all-notices', expanded); + if (!expanded) return; + const lower = app.workbenchOpen ? Math.max(100, Math.min(els.workbench.offsetHeight, 220)) : 48; + const available = Math.max(40, els.desk.clientHeight - els.sprite.offsetHeight - lower - 24); + const columns = Math.ceil(count / Math.max(1, Math.floor(available / 41))); + els.desk.style.setProperty('--notice-lower-reserve', `${lower}px`); + els.noticeList.style.setProperty('--notice-columns', String(columns)); } -function armQuickbarHide() { - clearTimeout(app.quickbarTimer); - app.quickbarTimer = setTimeout(() => { - const p = app.pointer; - if (p && pointInRect(els.quickbar.getBoundingClientRect(), p.x, p.y)) armQuickbarHide(); - else hideQuickbar(); - }, 6000); + +function renderNotificationStack() { + const container = els.notificationStack; + const list = els.noticeList; + const all = notificationItems(reminders.getState().items); + const now = Date.now(); + const ready = app.mode === 'window' && app.availability === 'ready' && !app.transient; + const tasks = bellView ? bellTasks() : []; + if (!tasks.length) bellView = ''; + const manual = Boolean(bellView); + const keys = new Set(all.map(noticeKey)); + for (const key of noticeShownAt.keys()) if (!keys.has(key)) noticeShownAt.delete(key); + if (ready) for (const key of keys) if (!noticeShownAt.has(key)) noticeShownAt.set(key, now); + const timing = { shownAt: noticeShownAt, now, timeoutSeconds: prefs.noticeTimeout, pausedAt: noticePauseAt }; + const items = !ready ? [] : manual ? tasks : visibleNotices(all, timing); + const expanded = manual && bellView === 'expanded'; + const stacked = !expanded && items.length > 1; + const animate = ready && !manual && !reducedMotion.matches; + container.classList.toggle('is-manual', manual); + container.classList.toggle('is-expanded', expanded); + if (ready && !manual) armNoticeTimer(items, timing); else stopNoticeTimer(); + const previews = notificationPreviews?.getState().previews ?? {}; + const existing = new Map([...list.children].map((node) => [node.dataset.noticeKey, node])); + const nodes = (stacked ? items.slice(0, 3) : items).map((item, index) => { + const key = manual ? item.sessionId : noticeKey(item); + const node = existing.get(key) || createNoticeCard(item.sessionId); + const [open, actions] = node.children; + const [jump, stop, dismiss, count] = actions.children; + const title = item.title || t('chat.untitled'); + const expand = stacked && index === 0; + node.dataset.noticeKey = key; + node.dataset.automatic = String(!manual); + node.dataset.layer = String(stacked ? index : 0); + node.dataset.expand = String(expand); + node.inert = stacked && index > 0; + node.dataset.status = item.displayStatus; + open.children[0].textContent = title; + open.children[1].textContent = markdownToPlainText(manual ? item.preview : notificationText(item, previews)); + open.setAttribute('aria-label', expand ? t('live.expandTasks', { count: items.length }) : t('desk.noticeView', { title })); + count.hidden = !expand; + count.textContent = expand ? String(items.length) : ''; + jump.hidden = stacked || !canOpenSession; + jump.title = t('live.jumpTask', { title }); + jump.setAttribute('aria-label', jump.title); + stop.hidden = stacked || !canOpenSession || item.displayStatus !== 'running'; + stop.title = t('live.stopInHost', { title }); + stop.setAttribute('aria-label', stop.title); + dismiss.hidden = stacked || manual; + dismiss.setAttribute('aria-label', t('desk.noticeClose', { title })); + return node; + }); + syncNoticeCards(nodes, animate); + container.classList.toggle('is-stacked', stacked || (!expanded && list.children.length > 1)); + const visible = ready && list.children.length > 0; + container.hidden = !visible; + if (!visible && noticePaused) queueMicrotask(() => { if (!disposed && container.hidden) pauseNotices(false); }); + els.quickBell.setAttribute('aria-expanded', String(visible && manual)); + layoutExpandedNotices(visible && expanded ? items.length : 0); +} + +function renderDeskShortcuts() { + const desktop = app.mode === 'window'; + const available = desktop && !app.dragging && !app.menuOpen; + const expanded = app.workbenchOpen && !els.workbench.hidden; + const bellParent = expanded ? workbenchView?.progressSlot : els.quickbar; + if (bellParent && els.quickBell.parentElement !== bellParent) { + if (expanded) bellParent.insertBefore(els.quickBell, bellParent.lastElementChild); + else bellParent.append(els.quickBell); + } + petQuota?.setActive(desktop && !document.hidden); + liveProgress?.update(app.sessions.some((row) => row.status === 'running') || + reminders.getState().items.some((row) => row.displayStatus === 'error'), available); + syncQuickbar(); +} + +function syncQuickbar(hideNow = false) { + const available = app.mode === 'window' && !app.workbenchOpen && !app.dragging && !app.menuOpen; + if (!available) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = true; + return; + } + const pointer = app.pointer; + const focus = document.activeElement; + const buttonFocused = focus?.matches(':focus-visible') && (els.quickbar.contains(focus) || focus === els.sprite); + const overPet = pointer && isOverPet(pointer.x, pointer.y); + let overShortcuts = false; + if (pointer && !els.quickbar.hidden) { + const rect = els.quickbar.getBoundingClientRect(); + const sprite = els.sprite.getBoundingClientRect(); + overShortcuts = pointer.x >= rect.left - 4 && pointer.x <= rect.right + 4 && + pointer.y >= sprite.bottom - 22 && pointer.y <= rect.bottom + 3; + } + if (bellView || app.hovered || overPet || overShortcuts || buttonFocused) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = false; + return; + } + if (hideNow) { + clearTimeout(shortcutHideTimer); shortcutHideTimer = undefined; + els.quickbar.hidden = true; + } else if (!els.quickbar.hidden && shortcutHideTimer === undefined) { + shortcutHideTimer = setTimeout(() => { shortcutHideTimer = undefined; syncQuickbar(true); refreshInteractivity(); }, 210); + } } // --------------------------------------------------------------------------- @@ -1335,10 +1648,10 @@ function positionMenu() { function openMenu(x, y) { if (app.mode !== 'window') return; noteInteraction(); - hideQuickbar(); stopLook(); disarmMenuClose(); app.menuOpen = true; + renderDeskShortcuts(); app.menuView = 'root'; app.menuAnchor = { x, y }; renderMenu(0); @@ -1347,6 +1660,7 @@ function openMenu(x, y) { function closeMenu({ restoreFocus = false } = {}) { if (!app.menuOpen) return; app.menuOpen = false; + renderDeskShortcuts(); disarmMenuClose(); els.menu.hidden = true; els.menu.replaceChildren(); @@ -1534,10 +1848,10 @@ function setScale(value) { const intent = ++scaleIntent; // Geometry stays with the size setting until its bounds and preference agree. app.scaleChanging = true; - cancelDrag(); + const stopped = cancelDrag(); const current = () => !disposed && intent === scaleIntent; scaleUpdates = scaleUpdates.then(async () => { - if (app.dragMove) await app.dragMove; + if (stopped) await stopped; if (!current()) return; if (app.workbenchOpen) await closeWorkbench(); if (!current()) return; @@ -1824,12 +2138,11 @@ async function confirmImport() { function renderAll() { renderHeader(); - renderActivityUI(); + renderVisibleActivity(); renderScale(); renderNoticeTimeout(); renderLanguage(); renderGallery(); - renderBubble(); } function renderHeader() { @@ -1880,6 +2193,10 @@ function renderActivityUI() { const text = real && !available ? availabilityText() : a.session?.needsAnswer ? t('status.needsAnswer') : a.session || !real ? statusText(a.status) || t('status.idleNow') : t('tasks.noCurrent'); els.panelStatus.textContent = a.session?.needsAnswer ? t('status.needsAnswerFor', { title: a.session.title }) : a.session && statusText(a.status) ? `「${a.session.title}」${text}` : text; renderDetail(); + renderSpriteActivityLabel(a); +} + +function renderSpriteActivityLabel(a = activity()) { const name = app.pet?.displayName ?? t('desk.pet'); const stateLabel = a.session?.needsAnswer ? t('status.needsAnswer') : statusLabel(a.status) || sourceLabelForActivity(); els.sprite.setAttribute('aria-label', app.mode === 'window' @@ -1968,28 +2285,145 @@ function renderDetailOpen(needsAnswer) { els.detailOpen.textContent = needsAnswer ? t('tasks.goAnswer') : t('tasks.open'); } +async function openDeliveryWindow({ asset, title }) { + // The separate viewer can focus itself after the spawn request has returned. + const deadline = performance.now() + 5000; + previewBlurDeadline = deadline; + try { + const response = await fetch('/api/delivery-preview', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + asset, title, language: root.lang, theme: root.dataset.theme, + area: { x: screen.availLeft, y: screen.availTop, width: screen.availWidth, height: screen.availHeight }, + }), + }); + if (!response.ok) throw new Error('preview_window_unavailable'); + } catch { + if (previewBlurDeadline === deadline) previewBlurDeadline = 0; + if (!disposed) showTransient(t('delivery.windowFailed'), 'error'); + } +} + function initWorkbench() { + petQuota = createPetQuota({ document, ring: els.quotaRing, button: els.quickQuota }); + liveProgress = createLiveProgress({ button: els.quickBell, isVisibleSession: (id) => desktopCatalog?.bySession.has(id), + onChange: () => { + syncQuickbar(); + if (app.mode === 'window' && !document.hidden) { + renderBubble(); + if (app.workbenchOpen) renderCompactView(); + } + }, + }); workbenchView = createCompactPetView({ container: els.workbench, + getAnchor: () => shortcutSize, onClose: () => { void closeWorkbench(); }, + onChangeView: openWorkbench, onSelectTask: openTaskPreview, onOpenSession: canOpenSession ? openSessionInHost : null, + onSelectChat: (sessionId) => activitySource?.selectSession(sessionId), + onOpenDelivery: openDeliveryWindow, + onOpenProject: typeof hostNavigation?.open === 'function' ? (projectId) => { + const project = desktopCatalog?.projects.find((item) => item.id === projectId); + if (!project) return { kind: 'error', text: t('chat.project.unavailable') }; + if (!project.path) return openInHost({ id: 'home' }); + const sessionId = desktopCatalog.firstSession.get(projectId); + return sessionId ? openSessionInHost(sessionId) : openInHost({ id: 'home' }); + } : null, + onAppendDraft: typeof hostMessage?.append === 'function' ? appendDraftToHost : null, + quota: petQuota, + }); + const resizeWorkbench = new ResizeObserver(() => { + if (app.workbenchOpen && !app.restoringPosition) keepDeskPartVisible(els.workbench); }); - notificationPreviews = createNotificationPreviews({ agent, onChange: () => { renderBubble(); renderCompactView(); } }); - disposers.push(() => { notificationPreviews.dispose(); workbenchView.dispose(); }); + resizeWorkbench.observe(els.workbench); + notificationPreviews = createNotificationPreviews({ agent, onChange: () => { + if (document.hidden || app.mode !== 'window') return; + renderBubble(); + if (app.workbenchOpen) renderCompactView(); + } }); + disposers.push(() => { resizeWorkbench.disconnect(); notificationPreviews.dispose(); workbenchView.dispose(); petQuota.dispose(); liveProgress.dispose(); }); +} + +function syncNotificationPreviews() { + notificationPreviews?.update({ availability: app.availability, items: notificationItems(reminders.getState().items) }); } function renderCompactView() { const notice = reminders.getState(); - notificationPreviews?.update({ availability: app.availability, items: notificationItems(notice.items) }); const previews = notificationPreviews?.getState().previews ?? {}; - workbenchView?.update({ reminders: { ...notice, items: notice.items.map((item) => ({ ...item, previewText: item.needsAnswer ? t('status.needsAnswer') : markdownToPlainText(previews[item.sessionId] || '') })) }, allSessions: app.sessions, - taskSelection: { availability: app.availability, selectedSessionId: app.selectedSessionId, session: app.sessions.find((row) => row.sessionId === app.selectedSessionId), detail: app.detail, detailLoading: app.detailLoading, detailError: app.detailError } }); + const selected = app.sessions.find((row) => row.sessionId === app.selectedSessionId); + const unread = liveProgress?.unread ?? []; + const unreadIds = new Set(unread.map((row) => row.sessionId)); + const finishedRows = unread.map((row) => ({ ...row, status: 'idle', liveCompleted: true, previewText: row.text })); + const recent = [...finishedRows, ...notice.items.filter((item) => !unreadIds.has(item.sessionId)).map((item) => ({ + ...item, previewText: previews[item.sessionId] || '', + }))]; + const task = workbenchView?.view === 'detail' ? notificationTask : null; + const detailState = task ? taskPreviewState(task, unread.find((row) => row.sessionId === task.sessionId)) : null; + const chatSessions = app.sessions.map((row) => ({ ...row, projectId: desktopCatalog?.bySession.get(row.sessionId) })); + const projects = app.availability === 'ready' ? desktopCatalog?.projects || [] : []; + workbenchView?.update({ reminders: { ...notice, items: recent }, + allSessions: [...finishedRows, ...app.sessions.filter((row) => !unreadIds.has(row.sessionId))], + chatSessions, projects, + originId: app.originSession?.sessionId, + notificationSelection: detailState, + taskSelection: { availability: app.availability, selectedSessionId: app.selectedSessionId, session: selected, detail: app.detail, detailLoading: app.detailLoading, detailError: app.detailError } }); + if (detailState?.readable && workbenchView.viewing(task.sessionId)) { + const turn = task.completion?.turnId || detailState.session?.observedTurnId || detailState.session?.updatedAtMs; + if (task.readTurn !== turn) { + task.readTurn = turn; + if (detailState.reminderCompleted) reminders.dismiss(task.sessionId); + liveProgress?.viewed(task.sessionId, task.completion?.turnId); + } + } else if (!task && selected?.liveCompleted && app.detail?.sessionId === selected.sessionId && + app.detail.updatedAtMs >= selected.updatedAtMs && workbenchView?.viewing(selected.sessionId)) { + reminders.dismiss(selected.sessionId); + liveProgress?.viewed(selected.sessionId, selected.observedTurnId); + } +} + +function taskPreviewState(task, completion) { + const id = task.sessionId; + if (completion) task.completion = completion; + const saved = task.completion; + const native = app.sessions.find((row) => row.sessionId === id); + const allowed = app.availability === 'ready'; + const observed = liveProgress?.progress(id); + const progress = saved && observed?.turnId !== saved.turnId ? null : observed; + const session = saved ? { ...saved, status: 'idle', liveCompleted: true } : native || task.row; + const hostDetail = app.detail?.sessionId === id ? app.detail : task.detail; + const hasReply = Boolean(saved?.text || hostDetail || progress?.text); + const detailLoading = Boolean(task.waiting || app.selectedSessionId === id && app.detailLoading); + const detail = hasReply || saved && !detailLoading ? { ...session, sessionId: id, status: session?.status, + lastAssistantText: saved?.text || progress?.text || hostDetail?.lastAssistantText || '' } : null; + return { availability: allowed || saved || progress ? 'ready' : app.availability, selectedSessionId: id, session, detail, + detailLoading, detailError: saved ? null : task.error || (app.selectedSessionId === id ? app.detailError : null), + steps: progress?.steps, canOpenHost: allowed && !id.startsWith('pet:'), + reminderCompleted: native?.liveCompleted && (!saved || !native.observedTurnId || native.observedTurnId === saved.turnId), + readable: Boolean(detail && (saved || native?.liveCompleted && hostDetail && hostDetail.updatedAtMs >= native.updatedAtMs)) }; } function openTaskPreview(sessionId) { - if (!activitySource || app.availability !== 'ready') { showTransient(availabilityText(), 'error'); return; } - try { void activitySource.selectSession(sessionId).catch((error) => showTransient(t('desk.replyFailed', { code: errCode(error) }), 'error')); } - catch (error) { showTransient(t('desk.replyFailed', { code: errCode(error) }), 'error'); return; } + const completion = liveProgress?.unread.find((row) => row.sessionId === sessionId); + const row = app.sessions.find((item) => item.sessionId === sessionId); + if (!row && !completion) return; + bellView = ''; + if (row?.liveCompleted) reminders.dismiss(sessionId); + const task = { sessionId, row, completion, waiting: false }; + notificationTask = task; + if (!sessionId.startsWith('pet:') && app.availability === 'ready') { + if (row && activitySource) { + task.waiting = !completion?.text; + void callBridge(() => activitySource.selectSession(sessionId)).catch((error) => { task.error = errCode(error); }) + .finally(() => { task.waiting = false; if (notificationTask === task && app.workbenchOpen) renderCompactView(); }); + } else if (typeof agent?.session === 'function' && !completion?.text) { + task.waiting = true; + void callBridge(() => agent.session(sessionId)).then((detail) => { task.detail = detail; }, (error) => { task.error = errCode(error); }) + .finally(() => { task.waiting = false; if (notificationTask === task && app.workbenchOpen) renderCompactView(); }); + } + } void openWorkbench('detail'); } @@ -1998,6 +2432,18 @@ function focusFullPanel(view) { else { panelNavigation?.showTab('tasks'); panelNavigation?.showTaskList(); } } +function keepDeskPartVisible(element) { + const bounds = app.winBounds; + const top = screen.availTop, height = screen.availHeight; + if (app.mode !== 'window' || app.dragging || element.hidden || !bounds || !Number.isFinite(top) || !(height > 0)) return; + const rect = element.getBoundingClientRect(); + const minY = Math.ceil(top - rect.top + 4); + const maxY = Math.floor(top + height - rect.bottom - 4); + if (minY > maxY) return; + const y = clamp(bounds.y, minY, maxY); + if (y !== bounds.y) void callBridge(() => win.update({ y })).then(onWindowState, logError('show_card_in_work_area')); +} + async function openWorkbench(view = 'tasks') { if (disposed) return; app.workbenchView = view; @@ -2007,8 +2453,14 @@ async function openWorkbench(view = 'tasks') { } const token = ++app.workbenchRevision; app.compacting = false; + const entering = !app.workbenchOpen; + if (entering && !els.quickbar.hidden) { + const { width, height } = els.quickbar.getBoundingClientRect(); + shortcutSize = { width, height }; + } app.workbenchOpen = true; - closeMenu(); hideQuickbar(); stopLook(); + closeMenu(); + if (entering) stopLook(); setClickThrough(false); const waitingAt = Date.now(); while (app.restoringPosition && token === app.workbenchRevision && !disposed && Date.now() - waitingAt < 3000) await new Promise((resolve) => setTimeout(resolve, 20)); @@ -2016,14 +2468,20 @@ async function openWorkbench(view = 'tasks') { workbenchView.open(view); root.classList.add('workbench-open'); applyActivity(); + keepDeskPartVisible(els.workbench); } -async function closeWorkbench() { +async function closeWorkbench({ restoreFocus = true } = {}) { const token = ++app.workbenchRevision; + previewBlurDeadline = 0; app.compacting = true; app.workbenchOpen = false; + app.workbenchNodded = false; + notificationTask = null; + if (restoreFocus && els.workbench.contains(document.activeElement)) els.sprite.focus({ preventScroll: true }); workbenchView.close(); root.classList.remove('workbench-open'); + stopLook(); applyActivity(); app.compacting = false; if (!disposed && token === app.workbenchRevision && app.mode === 'window' && !app.workbenchOpen) refreshInteractivity(); @@ -2031,7 +2489,6 @@ async function closeWorkbench() { function renderReminders() { const state = reminders.getState(); - renderCompactView(); els.reminderNote.textContent = state.items.length ? t('tasks.reminderNote.active') : t('tasks.reminderNote.idle'); const existing = new Map([...els.reminderList.children].map((node) => [node.dataset.sessionId, node])); const nodes = state.items.slice(0, 10).map((item) => { @@ -2088,10 +2545,11 @@ function setNoticeTimeout(raw) { els.noticeInput.value = String(next); if (next === prefs.noticeTimeout) { setMsg(els.noticeMsg, ''); return; } prefs.noticeTimeout = next; - // Restart every card's clock so the new duration applies from now. const at = Date.now(); - for (const id of noticeShownAt.keys()) noticeShownAt.set(id, at); - // Keep counting from now if the input is focused while the pointer stays on a card. + for (const item of notificationItems(reminders.getState().items)) { + const key = noticeKey(item); + if (item.displayStatus === 'error' && noticeShownAt.has(key)) noticeShownAt.set(key, at); + } noticePauseAt = noticePaused ? at : 0; setMsg(els.noticeMsg, next === 0 ? t('settings.noticeNever') : t('settings.noticeSaved', { seconds: next }), 'ok'); savePreferences({ noticeTimeout: next }); @@ -2258,12 +2716,29 @@ function bindDesk() { if (!e.relatedTarget) onPointerLeave(); }); listen(root, 'mouseleave', onPointerLeave); + listen(document, 'visibilitychange', () => { + if (!document.hidden) return; + onPointerLeave(); + stopLook(); + }); listen(window, 'blur', () => { - if (app.mode === 'window') closeMenu(); + if (app.mode !== 'window') return; + const openingPreview = performance.now() < previewBlurDeadline; + previewBlurDeadline = 0; + onPointerLeave(); + closeMenu(); + if (!openingPreview) closeBellStack(); + if (app.workbenchOpen && !openingPreview && !app.dragging && !app.modeSwitching) { + void closeWorkbench({ restoreFocus: false }); + } }); listen(els.sprite, 'pointerenter', () => { if (app.mode !== 'window') return; app.hovered = true; applyActivity(); }); listen(els.sprite, 'pointerleave', () => { app.hovered = false; applyActivity(); }); + listen(els.sprite, 'focusin', () => syncQuickbar()); + listen(els.sprite, 'focusout', () => queueMicrotask(() => !disposed && syncQuickbar())); + listen(els.quickbar, 'focusin', () => syncQuickbar()); + listen(els.quickbar, 'focusout', () => queueMicrotask(() => !disposed && syncQuickbar())); listen(els.sprite, 'pointerdown', onSpritePointerDown); listen(els.sprite, 'pointermove', onSpritePointerMove); listen(els.sprite, 'pointerup', (e) => finishDrag(e, false)); @@ -2273,7 +2748,7 @@ function bindDesk() { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); noteInteraction(); - void openWorkbench('tasks'); + void openWorkbench('chat'); } else if (e.key === 'F10' && e.shiftKey) { e.preventDefault(); const r = els.sprite.getBoundingClientRect(); @@ -2298,35 +2773,54 @@ function bindDesk() { listen(document, 'pointerdown', (e) => { if (app.mode !== 'window') return; + previewBlurDeadline = 0; noteInteraction(); if (app.menuOpen && !els.menu.contains(e.target)) closeMenu(); + if (bellView && !els.quickBell.contains(e.target) && !els.notificationStack.contains(e.target)) closeBellStack(); + if (app.workbenchOpen && e.button === 0 && + ![els.workbench, els.sprite, els.quickbar, els.bubble, els.notificationStack, els.menu].some((element) => element.contains(e.target))) { + void closeWorkbench({ restoreFocus: false }); + } }); listen(document, 'keydown', (e) => { if (app.mode !== 'window' || e.key !== 'Escape') return; + if (closeBellStack()) { + els.quickBell.focus({ preventScroll: true }); + return; + } if (app.workbenchOpen) { void closeWorkbench(); } - else hideQuickbar(); }); listen(els.menu, 'keydown', onMenuKeyDown); - listen(els.quickTasks, 'click', () => { void openWorkbench('tasks'); }); - listen(els.bubble, 'click', () => { void openWorkbench('tasks'); }); + listen(els.quickChat, 'click', () => { + if (app.workbenchOpen && workbenchView.view === 'chat') void closeWorkbench(); + else void openWorkbench('chat'); + }); + listen(els.quickQuota, 'click', () => { + void openWorkbench('chat').then(() => petQuota.panel.focus({ preventScroll: true })); + }); + const previewBubble = () => { void openWorkbench('tasks'); }; + listen(els.bubble, 'click', previewBubble); listen(els.bubble, 'keydown', (event) => { - if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); void openWorkbench('tasks'); } + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); previewBubble(); } }); - listen(els.quickMenu, 'click', () => { - const r = els.quickMenu.getBoundingClientRect(); - openMenu(r.left + r.width / 2, r.bottom); + listen(els.quickBell, 'click', () => { + if (closeBellStack()) return; + if (!bellTasks().length) return; + bellView = 'stacked'; + syncQuickbar(); + renderBubble(); }); - listen(els.quickbar, 'pointerenter', armQuickbarHide); + listen(window, 'resize', () => { if (bellView === 'expanded') renderBubble(); }); - // Reading a card, with a pointer or a keyboard, must outlast the timeout. + // Hover or keyboard focus pauses dismissible error cards. listen(els.notificationStack, 'pointerenter', () => pauseNotices(true)); listen(els.notificationStack, 'pointerleave', () => pauseNotices(false)); listen(els.notificationStack, 'focusin', () => pauseNotices(true)); listen(els.notificationStack, 'focusout', (e) => { - if (!els.notificationStack.contains(e.relatedTarget)) pauseNotices(false); + if (!els.notificationStack.contains(e.relatedTarget)) queueMicrotask(() => { if (!disposed) pauseNotices(false); }); }); } @@ -2356,6 +2850,7 @@ async function boot() { player.setReducedMotion(e.matches); importState.player?.setReducedMotion(e.matches); if (e.matches) stopLook(); + else applyActivity(); }); initHostUi(); @@ -2388,12 +2883,16 @@ async function boot() { function disposeApp() { if (disposed) return; disposed = true; + stopLook(); + if (deskPointerFrame !== null) cancelAnimationFrame(deskPointerFrame); + clearTimeout(shortcutHideTimer); + cancelDrag(); for (const dispose of disposers.splice(0).reverse()) { try { dispose(); } catch (error) { console.warn('[pet] dispose_failed:', errCode(error), error); } } stopNoticeTimer(); noticeShownAt.clear(); - for (const key of ['positionTimer', 'ctWatchdog', 'menuCloseTimer', 'quickbarTimer', 'transientTimer']) { + for (const key of ['positionTimer', 'ctWatchdog', 'menuCloseTimer', 'transientTimer']) { clearTimeout(app[key]); clearInterval(app[key]); app[key] = null; diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/pet-player.js b/sources/minimax-ai/minimax-pet/miniapp/client/pet-player.js index cfaa102b..21c3d353 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/pet-player.js +++ b/sources/minimax-ai/minimax-pet/miniapp/client/pet-player.js @@ -24,6 +24,9 @@ const ATLAS_WIDTH = CELL.width * CELL.columns; // 1536 const ROWS = { 1: 9, 2: 11 }; const LOOK_ROW = 9; const ALPHA_THRESHOLD = 24; +const FAST_BLINK = [42, 55, 48]; +const CHAO_YIN_IDLE = [1700, 850, 1670, ...FAST_BLINK]; +const CHAO_YIN_EYES = { x: 63, y: 69, width: 70, height: 25 }; /** 1536×1872 → 1, 1536×2288 → 2, otherwise null. */ export function atlasVersionFromSize(width, height) { @@ -148,6 +151,9 @@ export class SpritePlayer { this._scale = clampScale(scale); this._reduced = false; this._lookIndex = null; + this._blinkTimer = null; + this._blinkStep = null; + this._eyelids = null; this._state = 'idle'; // requested semantic state, independent of the rendered pose this._pose = 'idle'; this._loop = false; @@ -167,6 +173,7 @@ export class SpritePlayer { /** @param {LoadedPet} loadedPet */ setPet(loadedPet) { if (this._destroyed) return; + this._clearBlink(); this._pet = loadedPet; if (loadedPet.version !== 2) this._lookIndex = null; this._restart(); @@ -187,6 +194,7 @@ export class SpritePlayer { } get supportsLook() { return this._pet?.version === 2; } + get _hasShortBlink() { return this._pet?.id === 'chao-yin-soundwave-teacher-smooth'; } /** * Request a normal playback track. Non-idle actions play three cycles, then @@ -229,15 +237,18 @@ export class SpritePlayer { if (angleDegOrNull === null || angleDegOrNull === undefined || !Number.isFinite(angleDegOrNull)) { if (this._lookIndex === null) return; this._lookIndex = null; + this._clearBlink(); this._restart(); return; } const index = ((Math.round(angleDegOrNull / 22.5) % 16) + 16) % 16; + if (this._lookIndex === index) return; const wasLooking = this._lookIndex !== null; this._lookIndex = index; if (!wasLooking) { this._stopTimer(); if (this._transientThen !== null) this._finishTransient(); + this._scheduleBlink(); } this._render(); } @@ -269,6 +280,8 @@ export class SpritePlayer { destroy() { if (this._destroyed) return; + this._clearBlink(); + this._eyelids?.remove(); this._stopTimer(); this._settle(); document.removeEventListener('visibilitychange', this._onVisibility); @@ -317,11 +330,55 @@ export class SpritePlayer { this._col = 0; if (!this._pet || this._reduced || this._lookIndex !== null) { if (this._transientThen !== null) this._finishTransient(); + if (this._reduced) this._clearBlink(); + else this._scheduleBlink(); this._render(); return; } this._render(); - this._schedule(ANIMATIONS[this._pose].durations[0]); + this._schedule(this._durations()[0]); + } + + _durations() { return this._pose === 'idle' && this._hasShortBlink ? CHAO_YIN_IDLE : ANIMATIONS[this._pose].durations; } + + _clearBlink() { + clearTimeout(this._blinkTimer); + this._blinkTimer = this._blinkStep = null; + if (this._eyelids) this._eyelids.hidden = true; + } + + _scheduleBlink(delay = 3900) { + if (this._blinkTimer !== null || !this._hasShortBlink || this._lookIndex === null || this._reduced || document.hidden) return; + this._blinkTimer = setTimeout(() => { + this._blinkTimer = null; + this._blinkStep = this._blinkStep === null ? 0 : this._blinkStep + 1; + if (this._blinkStep === FAST_BLINK.length) this._blinkStep = null; + this._paintBlink(); + this._scheduleBlink(this._blinkStep === null ? 3900 : FAST_BLINK[this._blinkStep]); + }, delay); + } + + _paintBlink() { + if (this._blinkStep === null) { + if (this._eyelids) this._eyelids.hidden = true; + return; + } + if (!this._eyelids) { + this._eyelids = this._el.ownerDocument.createElement('span'); + this._eyelids.className = 'pet-blink-overlay'; + this._eyelids.setAttribute('aria-hidden', 'true'); + this._el.append(this._eyelids); + } + const { x, y, width, height } = CHAO_YIN_EYES, scale = this._scale; + const style = this._eyelids.style; + style.left = `${x * scale}px`; + style.top = `${y * scale}px`; + style.width = `${width * scale}px`; + style.height = `${height * scale}px`; + style.backgroundImage = this._el.style.backgroundImage; + style.backgroundSize = this._el.style.backgroundSize; + style.backgroundPosition = `-${((this._blinkStep + 3) * CELL.width + x) * scale}px -${y * scale}px`; + this._eyelids.hidden = false; } _schedule(ms) { @@ -337,7 +394,7 @@ export class SpritePlayer { this._timer = null; if (this._destroyed) return; this._col += 1; - if (this._col >= ANIMATIONS[this._pose].durations.length) { + if (this._col >= this._durations().length) { this._col = 0; this._round += 1; if (!this._loop && this._round >= this._repeat) { @@ -346,12 +403,13 @@ export class SpritePlayer { } } this._render(); - this._schedule(ANIMATIONS[this._pose].durations[this._col]); + this._schedule(this._durations()[this._col]); } _handleVisibility() { if (this._destroyed) return; if (document.hidden) { + this._clearBlink(); if (this._timer === null) return; clearTimeout(this._timer); this._timer = null; @@ -360,7 +418,7 @@ export class SpritePlayer { const ms = this._remaining; this._remaining = null; this._schedule(ms); - } + } else this._scheduleBlink(); } _render() { @@ -374,6 +432,7 @@ export class SpritePlayer { s.backgroundRepeat = 'no-repeat'; s.backgroundSize = `${ATLAS_WIDTH * k}px ${ROWS[this._pet.version] * CELL.height * k}px`; s.backgroundPosition = `-${col * CELL.width * k}px -${row * CELL.height * k}px`; + this._paintBlink(); } } diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs index 6eb01618..2f6fa8ee 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/pet-presentation.mjs @@ -13,32 +13,25 @@ export function aggregateText(counts, locale) { export function notificationItems(items) { return items.filter((item) => item.needsAnswer === true || ['completed', 'error'].includes(item.displayStatus)) - .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true)).slice(0, 3); + .sort((a, b) => Number(b.needsAnswer === true) - Number(a.needsAnswer === true)); } -/** - * Notification cards hide themselves; they never dismiss the reminder. `needsAnswer` - * cards ignore the timeout because they are the one thing the user must act on. - * A zero or negative timeout keeps every card until the user closes it. - */ -export function visibleNotices(items, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0 } = {}) { - const list = Array.isArray(items) ? items : []; - if (!(timeoutSeconds > 0)) return list; - const limit = timeoutSeconds * 1000; - return list.filter((item) => { - if (item?.needsAnswer === true) return true; - const since = shownAt instanceof Map ? shownAt.get(item?.sessionId) : shownAt?.[item?.sessionId]; - // An unknown start counts as just shown; the next paint records it. - return !Number.isFinite(since) || now - since < limit; - }); +export const noticeKey = (item) => item?.reminderKey || item?.sessionId; + +export function visibleNotices(items, options) { + return (Array.isArray(items) ? items : []).filter((item) => noticeRemaining(item, options) !== 0); } /** Milliseconds left before `item` hides, or null when it never does. */ -export function noticeRemaining(item, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0 } = {}) { - if (!(timeoutSeconds > 0) || item?.needsAnswer === true) return null; - const since = shownAt instanceof Map ? shownAt.get(item?.sessionId) : shownAt?.[item?.sessionId]; - if (!Number.isFinite(since)) return timeoutSeconds * 1000; - return Math.max(0, timeoutSeconds * 1000 - (now - since)); +export function noticeRemaining(item, { shownAt = new Map(), now = Date.now(), timeoutSeconds = 0, pausedAt = 0 } = {}) { + const completed = item?.displayStatus === 'completed'; + const duration = (completed ? 5 : timeoutSeconds) * 1000; + if (!(duration > 0) || item?.needsAnswer === true) return null; + const key = noticeKey(item); + const since = shownAt instanceof Map ? shownAt.get(key) : shownAt?.[key]; + if (!Number.isFinite(since)) return duration; + const clock = !completed && pausedAt ? Math.max(since, pausedAt) : now; + return Math.max(0, duration - (clock - since)); } export function notificationText(item, previews = {}) { diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs new file mode 100644 index 00000000..71ee4799 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/client/pet-quota.mjs @@ -0,0 +1,86 @@ +import { t } from './i18n.mjs'; + +const label = (item) => t(`chat.quota.${item.id}`); +const percentage = (item) => item.unlimited ? '∞' : Math.round(item.remaining) + '%'; +const color = (item) => `hsl(${Math.round(item.remaining * 1.16)} 62% 39%)`; + +export function createPetQuota({ document: doc, ring, button }) { + const make = (tag, className, text) => { + const node = doc.createElement(tag); + if (className) node.className = className; + if (text) node.textContent = text; + return node; + }; + const panel = make('section', 'chat-quota'); + panel.tabIndex = -1; + panel.hidden = true; + let snapshot, active = false, pending = false, timer, updated = 0, disposed = false; + + function paint() { + const windows = snapshot?.windows || []; + const main = windows.find((item) => item.id === 'interval') || windows[0]; + const labelText = t('chat.quota.label'); + panel.setAttribute('aria-label', labelText); + const heading = make('strong', 'chat-quota-title', snapshot?.tier ? 'MiniMax ' + snapshot.tier : 'MiniMax'); + panel.replaceChildren(heading); + if (!windows.length || snapshot?.stale) { + panel.append(make('span', 'chat-quota-status', t(`chat.quota.${snapshot?.stale ? 'stale' : snapshot?.status || 'loading'}`))); + } + for (const item of windows) { + const cell = make('div', 'chat-quota-cell'); + const meter = make('span', 'chat-quota-meter'); + const fill = make('i'); + fill.style.width = item.remaining + '%'; + fill.style.backgroundColor = color(item); + meter.append(fill); + const title = label(item) + ' ' + percentage(item); + cell.append(make('span', '', label(item)), make('b', '', percentage(item)), meter); + cell.title = item.resetAt ? title + ' · ' + t('chat.quota.reset', { date: new Date(item.resetAt).toLocaleString(doc.documentElement.lang) }) : title; + panel.append(cell); + } + if (!ring || !button) return; + ring.textContent = main ? percentage(main) : '—'; + ring.style.setProperty('--quota-progress', main ? main.remaining + '%' : '0%'); + ring.style.setProperty('--quota-color', main ? color(main) : 'transparent'); + const title = main ? labelText + ' · ' + label(main) + ' ' + percentage(main) : labelText; + button.title = title; + button.setAttribute('aria-label', title); + } + + async function refresh() { + if (!active || pending || disposed) return; + pending = true; + try { + const response = await fetch('/api/minimax-quota', { cache: 'no-store' }); + if (!response.ok) throw new Error('quota'); + snapshot = await response.json(); + } catch { + snapshot = snapshot?.windows?.length ? { ...snapshot, stale: true } : { status: 'error', windows: [] }; + } finally { + pending = false; + updated = Date.now(); + if (!disposed) { paint(); schedule(); } + } + } + + function schedule() { + clearTimeout(timer); + if (!active) return; + const interval = snapshot?.stale || snapshot?.status === 'error' ? 15_000 : 60_000; + const remaining = (updated + interval) - Date.now(); + if (!updated || remaining <= 0) void refresh(); + else timer = setTimeout(refresh, remaining); + } + + paint(); + return { + panel, + translate: paint, + setActive(value) { + if (value === active) return; + active = value; + schedule(); + }, + dispose() { disposed = true; active = false; clearTimeout(timer); panel.remove(); }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/pet.css b/sources/minimax-ai/minimax-pet/miniapp/client/pet.css index fd48054d..1e300453 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/pet.css +++ b/sources/minimax-ai/minimax-pet/miniapp/client/pet.css @@ -623,14 +623,15 @@ html.mode-window body { } .desk-overlays { + position: relative; display: flex; flex-direction: column; align-items: center; + justify-content: flex-end; + flex: 1; gap: 6px; - max-width: 100%; + width: min(100%, 264px); min-height: 0; - max-height: calc(100% - var(--minimax-pet-height, 104px) - 12px); - overflow-y: auto; } .desk-pet-slot { @@ -639,11 +640,32 @@ html.mode-window body { justify-content: center; } +.desk-lower { + display: grid; + flex: none; + grid-template: minmax(0, 1fr) / minmax(0, 1fr); + place-items: start center; + width: min(100%, 264px); + height: clamp(108px, calc(100vh - var(--minimax-pet-height, 104px) - 104px), 282px); +} +.desk-lower > .quickbar, .desk-lower > .workbench { grid-area: 1 / 1; } +.desk.show-all-notices .desk-overlays { flex: 1 0 auto; } +.desk.show-all-notices .desk-lower { flex: 0 1 auto; min-height: var(--notice-lower-reserve, 48px); } + html.mode-window .pet-sprite { + position: relative; cursor: grab; touch-action: none; border-radius: 8px; } +.pet-blink-overlay { + position: absolute; + pointer-events: none; + background-repeat: no-repeat; + mask-image: radial-gradient(ellipse, #000 61%, transparent 100%); +} +.chat-inline-project { display: flex; flex: none; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--mcode-text-muted); } +.chat-inline-project select { min-width: 0; max-width: calc(100% - 32px); height: 24px; color: var(--mcode-text); background: var(--mcode-bg-secondary); border: 1px solid var(--mcode-border); border-radius: 5px; font: inherit; } html.mode-window .pet-sprite.is-dragging { cursor: grabbing; } @@ -701,31 +723,55 @@ html.mode-window .pet-sprite:focus-visible { .quickbar { display: flex; - gap: 6px; -} - -.chip { - height: 28px; - padding: 0 10px; + flex: none; + align-items: center; + gap: 2px; + padding: 3px; border: 1px solid var(--mcode-border); - border-radius: 8px; + border-radius: 13px; background: var(--mcode-surface); color: var(--mcode-text); box-shadow: var(--pet-bubble-shadow); - font: inherit; - font-size: 12px; - white-space: nowrap; - cursor: pointer; - transition: background-color 150ms ease-out; } -.chip:hover, -.chip:active { - background: var(--mcode-bg-secondary); +@media (prefers-reduced-motion: no-preference) { + .quickbar:not([hidden]) { animation: shortcuts-reveal 140ms ease-out both; } + @keyframes shortcuts-reveal { from { opacity: 0; transform: scaleX(.78); } } } -.chip:disabled { - opacity: 0.5; - cursor: not-allowed; +.desk-shortcut { + position: relative; + display: grid; + place-items: center; + width: 38px; + height: 34px; + padding: 0; + background: transparent; + color: inherit; + border: 0; + border-radius: 8px; + cursor: pointer; } +.desk-shortcut:hover, .desk-shortcut[aria-expanded='true'] { background: var(--mcode-bg-secondary); } +.desk-chat-icon { position: relative; width: 17px; height: 14px; border: 1.6px solid currentColor; border-radius: 5px; } +.desk-chat-icon::after { content: ''; position: absolute; bottom: -3px; left: 3px; width: 5px; height: 5px; border-bottom: 1.6px solid; border-right: 1.6px solid; background: var(--mcode-surface); transform: rotate(45deg); } +.desk-chat-icon::before { content: ''; position: absolute; width: 7px; height: 1px; top: 5px; left: 3px; background: currentColor; } +.desk-quota-ring { + --quota-track: color-mix(in srgb, var(--mcode-text) 13%, var(--mcode-surface)); + display: grid; + place-items: center; + width: 31px; + height: 31px; + border-radius: 50%; + background: radial-gradient(closest-side, var(--mcode-surface) 79%, transparent 81%), + conic-gradient(var(--quota-color, transparent) var(--quota-progress, 0%), var(--quota-track) 0); + font-size: 9px; + font-weight: 700; + font-variant-numeric: tabular-nums; +} +.desk-bell-icon { width: 14px; height: 14px; border: 1.6px solid currentColor; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; position: relative; } +.desk-bell-icon::after { content: ''; position: absolute; height: 3px; width: 5px; bottom: -5px; left: 50%; transform: translateX(-50%); border: 1.5px solid currentColor; border-top: none; border-radius: 0 0 4px 4px; } +.desk-bell-badge { position: absolute; top: 1px; right: 3px; width: 12px; height: 12px; border-radius: 50%; background: var(--mcode-accent); color: #fff; font-size: 8px; line-height: 12px; font-weight: 700; } +.desk-bell-badge { min-width: 12px; width: auto; padding-inline: 2px; } + .menu { position: absolute; @@ -817,21 +863,16 @@ html.mode-window .pet-sprite:focus-visible { /* Small companion bubble; detailed workflows stay in the main panel. */ .workbench { - position: absolute; z-index: 5; - left: 8px; - right: 8px; - bottom: calc(var(--minimax-pet-height, 104px) + 8px); - /* Keep the 280px desk's two 8px gutters even if the native viewport becomes wider. */ - max-width: 264px; - margin-inline: auto; - /* Use the space the expanded window provides, up to what the desk leaves above the pet. */ - max-height: max(216px, calc(100% - var(--minimax-pet-height, 104px) - 24px)); + width: 100%; + min-height: 0; + max-height: 100%; display: flex; flex-direction: column; border: 1px solid var(--mcode-border); border-radius: 12px; overflow: hidden; + transform-origin: top center; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); color: var(--mcode-text); @@ -841,17 +882,66 @@ html.mode-window .pet-sprite:focus-visible { font-size: 12px; line-height: 18px; } -.compact-header { display: flex; align-items: center; justify-content: space-between; min-height: 32px; padding: 0 6px 0 10px; gap: 6px; } -.compact-state { color: var(--mcode-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.compact-header { display: flex; flex: none; align-items: center; justify-content: space-between; min-height: 32px; padding: 0 6px 0 10px; gap: 6px; } +.compact-state { color: var(--mcode-text-muted); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .compact-button { border: 0; border-radius: 6px; background: transparent; color: var(--mcode-text); font: inherit; cursor: pointer; padding: 3px 6px; } .compact-button:hover { background: var(--mcode-bg-secondary); } .compact-button:disabled { opacity: .4; cursor: default; } .compact-close { color: var(--mcode-text-muted); margin-left: auto; font-size: 17px; padding: 0 5px; min-width: 32px; min-height: 32px; } +.compact-switch { margin-left: auto; min-height: 26px; white-space: nowrap; } +.compact-switch ~ .compact-close { margin-left: 0; } +.compact-header .desk-bell { width: 30px; height: 28px; } +.chat-quota { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 9px; flex: none; padding: 7px 9px 8px; border-top: 1px solid var(--mcode-border); background: var(--mcode-bg-secondary); font-size: 10px; line-height: 13px; } +.chat-quota:focus-visible { outline-offset: -2px; } +.chat-quota strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chat-quota-status { color: var(--mcode-text-muted); } +.chat-quota-cell { display: grid; grid-template-columns: auto auto; gap: 2px 4px; align-items: baseline; flex: none; } +.chat-quota-cell span { color: var(--mcode-text-muted); } +.chat-quota-cell b { font-variant-numeric: tabular-nums; } +.chat-quota-meter { grid-column: 1 / -1; display: block; height: 3px; overflow: hidden; border-radius: 3px; background: color-mix(in srgb, var(--mcode-text) 15%, transparent); } +.chat-quota-meter i { display: block; height: 100%; } +.compact-chat { display: flex; flex-direction: column; gap: 6px; min-height: 0; padding: 2px 8px 8px; overflow: auto; scrollbar-width: thin; } +.chat-content { display: flex; flex-direction: column; gap: 5px; min-height: 0; overflow: auto; scrollbar-width: thin; } +.chat-sessions, .chat-actions, .chat-composer { display: flex; align-items: center; gap: 5px; flex: none; } +.chat-picker, .chat-input { + box-sizing: border-box; color: var(--mcode-text); background: var(--mcode-bg-secondary); font: inherit; + border: 1px solid var(--mcode-border); border-radius: 6px; padding: 3px 5px; min-width: 0; +} +.chat-picker { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex: 1; height: 32px; width: 0; padding-inline: 8px; font-size: 12px; cursor: pointer; text-align: left; } +.chat-picker:disabled { cursor: default; opacity: .65; } +.chat-picker-label, .chat-session-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chat-picker-label { min-width: 0; } +.chat-picker-chevron { flex: none; width: 6px; height: 6px; border: solid currentColor; border-width: 0 1px 1px 0; transform: translateY(-2px) rotate(45deg); transition: transform 120ms ease; } +.chat-picker[aria-expanded='true'] .chat-picker-chevron { transform: translateY(1px) rotate(225deg); } +.chat-project-list { min-height: 0; max-height: min(144px, 29vh); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; border: 1px solid var(--mcode-border); border-radius: 8px; padding: 3px; } +.chat-session-row { display: flex; align-items: center; gap: 5px; width: 100%; min-width: 0; padding: 4px 6px; border: 0; border-radius: 5px; background: transparent; color: var(--mcode-text); text-align: left; font: inherit; line-height: 17px; cursor: pointer; } +.chat-session-row:hover, .chat-session-row[aria-current='true'] { background: var(--mcode-bg-secondary); } +.chat-session-row:focus-visible { outline-offset: -2px; } +.chat-session-label { min-width: 0; flex: 1; } +.chat-session-check { color: var(--mcode-accent); } +.chat-session-running { width: 5px; height: 5px; flex: none; border-radius: 50%; background: var(--mcode-accent); } +.chat-empty { margin: 0; padding: 5px 6px; color: var(--mcode-text-muted); } +.chat-new { font-size: 18px; border: 1px solid var(--mcode-border); min-width: 32px; height: 32px; line-height: 20px; } +.chat-preview.md { min-height: 18px; max-height: min(126px, 25vh); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; } +.chat-open { padding-left: 2px; color: var(--mcode-accent); } +.chat-input { flex: 1; resize: vertical; min-height: 32px; max-height: 62px; font-size: 13px; line-height: 19px; user-select: text; } +.compact-button.chat-draft-submit { border: 1px solid var(--mcode-border); font-weight: 600; white-space: nowrap; } +.chat-status { flex: none; margin: 0; font-size: 11px; line-height: 15px; } +.chat-sessions.is-composing .chat-new { order: -1; } +.chat-sessions.is-composing .chat-new, +.compact-button.chat-inline-send { flex: none; width: 28px; min-width: 28px; height: 28px; padding: 0; border: 0; border-radius: 50%; font-size: 16px; line-height: 1; } +.chat-sessions.is-composing .chat-new { color: var(--mcode-text-muted); background: var(--mcode-bg-secondary); } +.chat-inline-compose { min-width: 0; flex: 1; display: flex; gap: 5px; align-items: flex-end; } +.chat-inline-compose .chat-input { min-width: 0; width: 0; min-height: 28px; max-height: 76px; field-sizing: content; padding: 4px 7px; resize: none; scrollbar-width: thin; font-size: 12px; line-height: 18px; } +.compact-button.chat-inline-send { color: var(--mcode-text-muted); background: var(--mcode-bg-secondary); } +.compact-button.chat-inline-send:not(:disabled) { color: white; background: var(--mcode-accent); } +@media (prefers-reduced-motion: reduce) { .chat-picker-chevron { transition: none; } } .compact-body { min-height: 0; overflow: auto; padding: 2px 10px 8px; } /* The detail pane owns the height: head and footer are fixed, the reply is the only scroller. */ .compact-detail { display: flex; flex-direction: column; gap: 4px; min-height: 0; padding: 2px 10px 8px; overflow: hidden; } .compact-detail-head { display: flex; align-items: baseline; gap: 6px; flex: none; min-width: 0; } .compact-detail-body { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; } +.compact-detail-steps { margin: 0 0 5px; padding-left: 16px; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-detail .compact-footer { flex: none; margin-top: 0; padding-top: 4px; border-top: 1px solid var(--mcode-border); } .compact-detail .compact-hint { flex: none; } .compact-hint { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; color: var(--mcode-text-muted); margin: 4px 0; font-size: 12px; line-height: 16px; } @@ -865,25 +955,42 @@ html.mode-window .pet-sprite:focus-visible { .compact-task-status { justify-self: end; padding-inline: 6px; text-align: right; white-space: nowrap; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-task-preview { grid-column: 1 / -1; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 5; overflow: hidden; margin: 0; color: var(--mcode-text-muted); font-size: 11px; line-height: 16px; } .compact-empty { color: var(--mcode-text-muted); padding: 8px 0; } -.notification-stack { display: flex; flex-direction: column-reverse; gap: 5px; width: 248px; max-height: 216px; overflow-y: auto; } -.pet-notice { display: flex; align-items: start; border: 0.5px solid var(--mcode-border); border-radius: 12px; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); padding: 6px 7px 6px 10px; flex: none; } +.notification-stack { width: min(100%, 248px); } +.pet-notice-list { display: grid; gap: 3px; padding: 1px 2px 3px; } +.pet-notice { display: flex; align-items: center; gap: 5px; min-width: 0; border: 1px solid var(--mcode-border); border-radius: 18px; background: var(--mcode-surface); box-shadow: var(--pet-bubble-shadow); padding: 6px 7px 6px 11px; } +.notification-stack.is-stacked .pet-notice-list { isolation: isolate; padding-bottom: 14px; } +.notification-stack.is-stacked .pet-notice { grid-area: 1 / 1; align-self: start; } +.notification-stack.is-stacked .pet-notice[data-layer='0'] { z-index: 3; } +.notification-stack.is-stacked .pet-notice[data-layer='1'] { z-index: 2; translate: 0 6px; scale: .96; background: var(--mcode-bg-secondary); } +.notification-stack.is-stacked .pet-notice[data-layer='2'] { z-index: 1; translate: 0 12px; scale: .91; background: var(--mcode-bg-secondary); } +.notification-stack.is-stacked .pet-notice[data-layer='1'] > *, +.notification-stack.is-stacked .pet-notice[data-layer='2'] > * { visibility: hidden; } +.notification-stack.is-expanded .pet-notice-list { grid-template-columns: repeat(var(--notice-columns, 1), minmax(0, 1fr)); } +@media (prefers-reduced-motion: no-preference) { + .pet-notice { transition: translate 140ms ease-out, scale 140ms ease-out; } + .notification-stack.is-expanded .pet-notice { animation: notice-expand 180ms ease-out both; } + @keyframes notice-expand { + from { opacity: .5; transform: translateY(7px) scale(.97); } + to { opacity: 1; transform: none; } + } +} +.pet-stack-count { flex: none; min-width: 22px; height: 22px; padding-inline: 5px; border-radius: 11px; background: var(--mcode-bg-secondary); color: var(--mcode-text-muted); text-align: center; line-height: 22px; font-variant-numeric: tabular-nums; } .pet-notice-open { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--mcode-text); text-align: left; font: inherit; font-size: 12px; line-height: 16px; padding: 0; cursor: pointer; } .pet-notice-open strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; } -.pet-notice-preview { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 5; overflow: hidden; color: var(--mcode-text-muted); overflow-wrap: anywhere; } +.pet-notice[data-status='running'] strong::before { content: '●'; color: var(--mcode-accent); margin-right: 5px; font-size: 8px; } +.pet-notice[data-status='completed'] strong::before { content: '✓'; color: var(--mcode-success); margin-right: 5px; } +.pet-notice-preview { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; color: var(--mcode-text-muted); overflow-wrap: anywhere; } +.pet-notice-actions { flex: none; display: flex; gap: 4px; align-items: center; } +.pet-notice-action { display: grid; place-items: center; width: 25px; height: 25px; border: 0; border-radius: 50%; background: var(--mcode-bg-secondary); color: var(--mcode-text-muted); padding: 0; font-size: 14px; cursor: pointer; } +.pet-notice-action:hover { color: var(--mcode-accent); } +.pet-notice-stop { font-size: 10px; } +.pet-notice-stop:hover { color: var(--mcode-danger); } +.notification-stack.is-manual .pet-notice { padding-block: 3px; } +.notification-stack.is-manual .pet-notice-open { line-height: 14px; } +.notification-stack.is-manual .pet-notice-list .pet-notice-preview { -webkit-line-clamp: 1; } .compact-detail-title { flex: 1; min-width: 0; margin: 0; font-size: 13px; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .compact-detail-status { flex: none; font-size: 12px; line-height: 16px; color: var(--mcode-text-muted); } .compact-detail-reply { margin: 0; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } -/* The desktop card is 280px wide; keep the same structure at a tighter scale. */ -.compact-detail-reply.md { font-size: 12px; line-height: 17px; text-align: left; } -.compact-detail-reply.md .md-p, -.compact-detail-reply.md .md-list, -.compact-detail-reply.md .md-pre, -.compact-detail-reply.md .md-table, -.compact-detail-reply.md .md-quote { margin-bottom: 5px; } -.compact-detail-reply.md .md-heading { margin: 8px 0 4px; font-size: 13px; line-height: 18px; } -.compact-detail-reply.md .md-pre { padding: 6px 8px; } -.compact-detail-reply.md .md-table th, -.compact-detail-reply.md .md-table td { padding: 3px 6px; font-size: 11px; } .compact-detail-back { color: var(--mcode-text-muted); font-size: 12px; line-height: 16px; } .compact-open { font-size: 12px; font-weight: 600; } .pet-notice-dismiss { flex: none; border: 0; background: transparent; color: var(--mcode-text-muted); cursor: pointer; font-size: 15px; padding: 0 2px 0 6px; } @@ -912,6 +1019,29 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } overflow-wrap: anywhere; } +.md-delivery { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 6px; } +.md-delivery figure { margin: 0; width: fit-content; max-width: min(100%, 170px); } +.md-delivery-thumbnail { display: block; max-width: 100%; padding: 0; border: 0; background: none; cursor: zoom-in; border-radius: 5px; } +.md-delivery img { display: block; max-width: 100%; max-height: 100px; width: auto; height: auto; border-radius: 5px; } +.md-delivery figcaption { margin-top: 2px; color: var(--mcode-text-muted); font-size: 11px; line-height: 14px; } +.md-delivery-file { display: grid; width: 100%; gap: 2px; padding: 6px 8px; border: 1px solid var(--mcode-border); border-radius: 6px; background: var(--mcode-bg-secondary); color: var(--mcode-text); text-align: left; font: inherit; overflow-wrap: anywhere; } +button.md-delivery-file { cursor: pointer; } +button.md-delivery-file:hover { border-color: var(--mcode-accent); } +.md-delivery-file small { font-size: 10px; line-height: 14px; color: var(--mcode-text-muted); } + +.delivery-preview-page body { margin: 0; overflow: hidden; background: var(--mcode-surface); color: var(--mcode-text); } +.delivery-preview { display: flex; flex-direction: column; height: 100dvh; } +.delivery-preview-header { display: flex; align-items: center; flex: none; gap: 10px; min-height: 45px; padding: 4px 12px 4px 16px; border-bottom: 1px solid var(--mcode-border); } +.delivery-preview-header h1 { flex: 1; min-width: 0; margin: 0; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.delivery-preview-header button { min-height: 32px; font-size: 12px; white-space: nowrap; } +.delivery-preview-body { flex: 1; min-height: 0; overflow: auto; padding: 12px 16px; scrollbar-width: thin; overscroll-behavior: contain; user-select: text; -webkit-user-select: text; } +.delivery-preview-status { margin: 0; font-size: 13px; color: var(--mcode-text-muted); } +.delivery-preview-content { font-size: 14px; line-height: 1.6; } +.delivery-preview-content[data-kind='image']:not(.is-original) { display: grid; place-items: center; height: 100%; } +.delivery-preview-content > img { display: block; max-width: 100%; max-height: calc(100dvh - 69px); } +.delivery-preview-content.is-original > img { width: auto; max-width: none; max-height: none; } +.delivery-preview-content > pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } + .md > :first-child { margin-top: 0; } .md > :last-child { margin-bottom: 0; } @@ -969,14 +1099,18 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } overflow-wrap: anywhere; } +/* Wide blocks scroll sideways and let vertical wheel input reach the reply. */ +.md :is(.md-pre, .md-table) { + overflow-x: auto; + overscroll-behavior-x: contain; +} + .md .md-pre { margin: 0 0 8px; padding: 8px 10px; border: 1px solid var(--mcode-border); border-radius: 8px; background: var(--mcode-surface-muted); - overflow: auto; - overscroll-behavior: contain; } .md .md-pre code { @@ -1013,8 +1147,6 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } .md .md-table { margin: 0 0 8px; - overflow-x: auto; - overscroll-behavior: contain; } .md .md-table table { @@ -1067,6 +1199,20 @@ summary { cursor: pointer; color: var(--mcode-text-muted); font-size: 12px; } .md strong { font-weight: 600; } .md del { color: var(--mcode-text-muted); } +/* The floating chat and task replies share one compact Markdown scale. */ +.desk .md { font-size: 12px; line-height: 17px; } +.desk .md :where(.md-p, .md-list, .md-pre, .md-table, .md-quote, .md-block) { margin-bottom: 5px; } +.desk .md .md-heading { margin: 8px 0 4px; font-size: 13px; line-height: 18px; } +.desk .md .md-list { padding-left: 17px; } +.desk .md .md-li { margin: 1px 0; } +.desk .md .md-task { margin-left: -17px; padding-left: 17px; } +.desk .md .md-pre { padding: 5px 7px; } +.desk .md .md-pre code { font-size: 11px; line-height: 16px; } +.desk .md .md-table th, +.desk .md .md-table td { padding: 3px 5px; } +.desk .md > :first-child { margin-top: 0; } +.desk .md > :last-child { margin-bottom: 0; } + /* Main panel: appearance, task reading, and settings share one quiet surface. All selectors are panel-scoped so the desktop companion keeps its layout. */ html.mode-inline, diff --git a/sources/minimax-ai/minimax-pet/miniapp/client/preferences.mjs b/sources/minimax-ai/minimax-pet/miniapp/client/preferences.mjs index 5895a2ec..dc6a2a5e 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/client/preferences.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/client/preferences.mjs @@ -1,6 +1,5 @@ -// noticeTimeout: seconds a desktop notification card stays before it hides itself. -// 0 keeps the card until the user closes it. The card hiding never dismisses the -// reminder itself, so the task list keeps showing the same round. +// noticeTimeout controls error cards. Zero keeps errors visible until dismissed. +// Completion cards use their own five-second timer and keep the reminder unread. export const DEFAULT_PREFERENCES = Object.freeze({ petId: null, scale: 0.75, autoCycle: false, windowPosition: null, noticeTimeout: 10, language: 'auto' }); export const LANGUAGES = Object.freeze(['auto', 'zh-Hans', 'en']); export const MAX_NOTICE_TIMEOUT_SECONDS = 3600; diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs new file mode 100644 index 00000000..686f4264 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/completion-store.mjs @@ -0,0 +1,43 @@ +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { completionRecord } from '../client/completion-inbox.mjs'; + +export function createCompletionStore(dataDir) { + const file = join(dataDir, 'completions.json'); + let queue = Promise.resolve(); + let records; + async function load() { + if (records) return records; + let data; + try { data = JSON.parse(await readFile(file, 'utf8')); } + catch (error) { if (error.code !== 'ENOENT') throw error; } + if (data && (data.version !== 1 || !Array.isArray(data.records))) throw new Error('completion_store_invalid'); + records = new Map((data?.records || []).map(completionRecord).filter(Boolean).map((row) => [row.sessionId, row])); + return records; + } + return { + async get() { await queue; return [...(await load()).values()]; }, + apply(change) { + const result = queue.then(async () => { + const values = await load(); + const row = change?.action === 'complete' ? completionRecord(change.row) : null; + const current = values.get(row?.sessionId || change?.sessionId); + const next = row && current?.turnId !== row.turnId && (!current || row.updatedAtMs >= current.updatedAtMs) ? row : + change?.action === 'view' && current && !current.viewed && current.turnId === change.turnId ? { ...current, text: '', viewed: true } : null; + if (!next) return; + const updated = new Map(values).set(next.sessionId, next); + const temporary = join(dataDir, `.completions-${randomUUID()}.tmp`); + await mkdir(dataDir, { recursive: true }); + try { + await writeFile(temporary, JSON.stringify({ version: 1, records: [...updated.values()] }), { mode: 0o600, flag: 'wx' }); + await rename(temporary, file); + records = updated; + } finally { await rm(temporary, { force: true }).catch(() => {}); } + }); + queue = result.catch(() => {}); + return result; + }, + flush: () => queue, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs new file mode 100644 index 00000000..f853eb54 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-catalog.mjs @@ -0,0 +1,68 @@ +import { existsSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +const listedProject = ` + p.hidden = 0 AND (p.project_kind = 'default' OR p.listed_at_ms IS NOT NULL) + AND json_type(CASE WHEN json_valid(p.extra_data_json) THEN p.extra_data_json ELSE '{}' END, '$.sidebarRemoval') IS NULL +`; +const sidebarSession = ` + s.archived = 0 AND s.visibility = 'visible' + AND s.session_kind IN ('conversation', 'task') + AND coalesce(s.parent_session_id, '') = '' AND coalesce(s.origin_cron_id, '') = '' + AND json_extract(CASE WHEN json_valid(s.extra_data_json) THEN s.extra_data_json ELSE '{}' END, '$.miniAppOrigin') IS NULL + AND ${listedProject} + AND (p.project_kind <> 'default' OR s.is_default_workspace = 1) +`; + +async function withDesktopDatabase(read, roots = [process.env.MINIMAX_DATA_DIR, process.env.MINIS_MAX_DATA_DIR, process.env.MAVIS_DATA_DIR, join(homedir(), '.minimax')]) { + const path = roots + .filter(Boolean).map((root) => join(root, 'v2', 'sqlite', 'runtime-state.sqlite')).find(existsSync); + if (!path) return null; + let db; + try { + const { DatabaseSync } = await import('node:sqlite'); + db = new DatabaseSync(path, { readOnly: true }); + db.exec('PRAGMA busy_timeout = 250'); + return read(db); + } catch { + return null; + } finally { db?.close(); } +} + +// Filter against the desktop sidebar using metadata only. +export function readDesktopCatalog(roots) { + return withDesktopDatabase((db) => { + const projects = db.prepare(` + SELECT project_id AS id, workspace_dir AS path, display_name AS name + FROM local_runtime_projects p + WHERE ${listedProject} + ORDER BY pinned DESC, order_index, recent_at_ms DESC + `).all().map((row) => ({ id: String(row.id), path: row.path || '', name: row.name || '' })); + const sessions = db.prepare(` + SELECT s.session_id AS id, s.project_id AS projectId + FROM local_runtime_sessions s + JOIN local_runtime_projects p ON s.project_id = p.project_id + WHERE ${sidebarSession} + ORDER BY s.updated_at_ms DESC + `).all().map((row) => ({ id: row.id, projectId: String(row.projectId) })); + return { projects, sessions }; + }, roots); +} + +export function readDesktopAsset(sessionId, { nodeId, path }, roots) { + const match = nodeId + ? "a.asset_type = 'image' AND cast(json_extract(CASE WHEN json_valid(a.data_json) THEN a.data_json ELSE '{}' END, '$.nodeId') AS TEXT) = ?" + : `replace(a.path, char(92), '/') = ? ${process.platform === 'win32' ? 'COLLATE NOCASE' : ''}`; + return withDesktopDatabase((db) => db.prepare(` + SELECT a.path, coalesce(nullif(s.workspace_dir, ''), p.workspace_dir) AS workspace + FROM local_runtime_session_assets a + JOIN local_runtime_sessions s ON s.session_id = a.session_id + JOIN local_runtime_projects p ON p.project_id = s.project_id + WHERE a.session_id = ? AND a.role = 'assistant' AND a.source_tag = 'deliver-assets' + AND ${match} + AND ${sidebarSession} + ORDER BY a.updated_at_ms DESC + LIMIT 1 + `).get(sessionId, nodeId || path?.replaceAll('\\', '/')) || null, roots); +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs new file mode 100644 index 00000000..65ae1be3 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.mjs @@ -0,0 +1,74 @@ +import { spawn } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { createInterface } from 'node:readline'; + +export function createDesktopDrag(pluginRoot) { + let worker; + let pending; + let requests = Promise.resolve(); + let stopped = false; + + function disconnect(child, error) { + if (worker !== child) return; + worker = undefined; + pending?.finish(error); + } + + async function connect() { + const script = await readFile(join(pluginRoot, 'miniapp/node/desktop-drag.ps1'), 'utf8'); + if (stopped) throw new Error('desktop_drag_stopped'); + const shell = join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'); + const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { + stdio: ['pipe', 'pipe', 'ignore'], + windowsHide: true, + }); + worker = child; + child.once('error', (error) => disconnect(child, error)); + child.once('close', () => disconnect(child, new Error('desktop_drag_closed'))); + child.stdin.on('error', (error) => disconnect(child, error)); + createInterface({ input: child.stdout }).on('line', (line) => { + if (worker !== child) return; + if (line === 'ok') pending?.finish(undefined, true); + else if (line === 'ignored') pending?.finish(undefined, false); + else if (line === 'error') pending?.finish(new Error('desktop_drag_failed')); + }); + return child; + } + + return { + send(command) { + const task = requests.then(async () => { + if (stopped) throw new Error('desktop_drag_stopped'); + const child = worker ?? await connect(); + if (worker !== child) throw new Error('desktop_drag_closed'); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + disconnect(child, new Error('desktop_drag_timeout')); + child.kill(); + }, 6_000); + pending = { + finish(error, result) { + clearTimeout(timeout); + pending = undefined; + if (error) reject(error); + else resolve(result); + }, + }; + child.stdin.write(command + '\n'); + }); + }); + requests = task.catch(() => {}); + return task; + }, + async dispose() { + stopped = true; + if (worker) { + const child = worker; + disconnect(child, new Error('desktop_drag_stopped')); + child.kill(); + } + await requests; + }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 new file mode 100644 index 00000000..c088ff23 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/desktop-drag.ps1 @@ -0,0 +1,130 @@ +$ErrorActionPreference = 'Stop' + +Add-Type -TypeDefinition @' +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +public static class MiniMaxPetDrag { + private static int moving; + private static int cancellation; + [StructLayout(LayoutKind.Sequential)] + private struct Rect { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] + private struct Point { public int X, Y; } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr FindWindow(string className, string title); + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process); + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] + private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] + private static extern uint GetDpiForWindow(IntPtr window); + [DllImport("user32.dll")] + private static extern bool GetWindowRect(IntPtr window, out Rect rectangle); + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out Point point); + [DllImport("user32.dll")] + private static extern short GetAsyncKeyState(int key); + [DllImport("user32.dll")] + private static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] + private static extern bool SetWindowPos(IntPtr window, IntPtr order, int x, int y, int width, int height, uint flags); + [DllImport("winmm.dll")] + private static extern uint timeBeginPeriod(uint period); + [DllImport("winmm.dll")] + private static extern uint timeEndPeriod(uint period); + + public static void Stop() { + Interlocked.Increment(ref cancellation); + } + + private static IntPtr FindPetWindow() { + IntPtr window = FindWindow("Chrome_WidgetWin_1", "MiniMax Pet"); + IntPtr main = FindWindow("Chrome_WidgetWin_1", "MiniMax Code"); + uint owner, mainOwner; + GetWindowThreadProcessId(window, out owner); + GetWindowThreadProcessId(main, out mainOwner); + if (window == IntPtr.Zero || !IsWindowVisible(window) || owner == 0 || owner != mainOwner) + return IntPtr.Zero; + try { + using (Process process = Process.GetProcessById((int)owner)) { + if (process.ProcessName != "MiniMax Code") return IntPtr.Zero; + } + } catch (ArgumentException) { return IntPtr.Zero; } + catch (InvalidOperationException) { return IntPtr.Zero; } + return window; + } + + public static bool Start(int dx, int dy) { + IntPtr window = FindPetWindow(); + if (window == IntPtr.Zero) return false; + int primary = GetSystemMetrics(23) != 0 ? 2 : 1; // SM_SWAPBUTTON + if (GetAsyncKeyState(primary) >= 0) return false; + + Rect frame; + Point cursor; + IntPtr previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); + try { + if (!GetWindowRect(window, out frame) || !GetCursorPos(out cursor)) return false; + } finally { + if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi); + } + double scale = GetDpiForWindow(window) / 96.0; + int pressX = cursor.X - (int)Math.Round(dx * scale); + int pressY = cursor.Y - (int)Math.Round(dy * scale); + if (scale <= 0 || pressX < frame.Left || pressX >= frame.Right || pressY < frame.Top || pressY >= frame.Bottom) + return false; + if (Interlocked.CompareExchange(ref moving, 1, 0) != 0) return false; + + int ticket = Volatile.Read(ref cancellation); + Thread thread = new Thread(delegate() { + SetThreadDpiAwarenessContext(new IntPtr(-4)); + int lastX = frame.Left, lastY = frame.Top; + const uint moveOnly = 0x0001 | 0x0004 | 0x0010; // NOSIZE, NOZORDER, NOACTIVATE + bool highResolution = timeBeginPeriod(1) == 0; + try { + Point point; + while (ticket == Volatile.Read(ref cancellation) && GetAsyncKeyState(primary) < 0 && + IsWindowVisible(window) && GetCursorPos(out point)) { + int x = frame.Left + point.X - pressX, y = frame.Top + point.Y - pressY; + if (x != lastX || y != lastY) { + if (!SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, moveOnly)) break; + lastX = x; + lastY = y; + } + Thread.Sleep(5); + } + } finally { + if (highResolution) timeEndPeriod(1); + Interlocked.Exchange(ref moving, 0); + } + }); + thread.IsBackground = true; + thread.Start(); + return true; + } +} +'@ + +while ($null -ne ($line = [Console]::ReadLine())) { + try { + if ($line -eq 'warm') { + [Console]::WriteLine('ok') + } elseif ($line -eq 'stop') { + [MiniMaxPetDrag]::Stop() + [Console]::WriteLine('ok') + } elseif ($line -match '^drag (-?\d+) (-?\d+)$') { + $started = [MiniMaxPetDrag]::Start([int]$Matches[1], [int]$Matches[2]) + [Console]::WriteLine($(if ($started) {'ok'} else {'ignored'})) + } else { + [Console]::WriteLine('error') + } + } catch { + [Console]::WriteLine('error') + } +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs new file mode 100644 index 00000000..37a8856c --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/minimax-quota.mjs @@ -0,0 +1,121 @@ +import { createHash } from 'node:crypto'; +import { access, readFile, readdir } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +// Same two account endpoints used by the Agent 额度看板 plugin. +const MEMBERSHIP_URL = 'https://agent.minimax.cn/matrix/api/v1/commerce/get_membership_info'; +const QUOTA_URL = 'https://www.minimaxi.com/v1/api/openplatform/coding_plan/remains'; +const QUERY = { + device_platform: 'web', biz_id: '3', app_id: '3001', version_code: '22201', timezone_offset: '0', + sys_language: 'zh', lang: 'zh', device_id: '0', user_id: '0', client: 'desktop', region: 'cn', is_desktop: '1', +}; +const number = (value) => typeof value === 'number' || typeof value === 'string' && value.trim() ? Number(value) : NaN; +const tokenText = (value) => typeof value === 'string' ? value.trim() : ''; +const md5 = (value) => createHash('md5').update(value).digest('hex'); + +async function findAuth(root) { + const dirs = [join(root, 'auth')]; + while (dirs.length) { + const dir = dirs.pop(); + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + const path = join(dir, entry.name); + if (entry.isDirectory()) dirs.push(path); + if (!entry.isFile() || entry.name !== 'auth.json') continue; + try { + const profile = JSON.parse(await readFile(path, 'utf8')); + for (const item of Object.values(profile.records ?? {})) { + const token = tokenText(item?.accessToken); + const expiry = number(item?.expiresAtMs); + if (token && (!Number.isFinite(expiry) || expiry > Date.now())) return token; + } + } catch { /* A profile may be replaced during an account change. */ } + } + } + return ''; +} + +async function readAccountToken() { + const homeData = join(homedir(), '.minimax'); + const roots = [process.env.MINIS_MAX_DATA_DIR, process.env.MAVIS_DATA_DIR, process.env.MINIMAX_DATA_DIR, process.env.DATA_DIR, homeData]; + for (const root of roots) { + if (!root) continue; + if (root !== homeData && !await access(join(root, 'v2', 'sqlite')).then(() => true, () => false)) continue; + return findAuth(root); + } + return ''; +} + +export function quotaWindows(payload) { + const models = payload?.data?.model_remains ?? payload?.model_remains; + if (!Array.isArray(models)) return []; + const source = models.find((model) => model?.model_name === 'general') ?? models.find((model) => tokenText(model?.model_name)); + if (!source) return []; + return [['interval', 'remains_time'], ['weekly', 'weekly_remains_time']].flatMap(([id, resetKey]) => { + const prefix = `current_${id}`; + const unlimited = number(source[`${prefix}_status`]) === 3; + const explicit = number(source[`${prefix}_remaining_percent`]); + const total = number(source[`${prefix}_total_count`]); + const remainingCount = number(source[`${prefix}_usage_count`]); + const percent = explicit >= 0 && explicit <= 100 ? explicit : total > 0 ? remainingCount / total * 100 : NaN; + if (!unlimited && !Number.isFinite(percent)) return []; + const resetMs = number(source[resetKey]); + return [{ id, remaining: unlimited ? 100 : Math.min(100, Math.max(0, percent)), unlimited, + resetAt: Number.isFinite(resetMs) && resetMs > 0 ? Date.now() + resetMs : null }]; + }); +} + +export function createMiniMaxQuota({ fetch: request = globalThis.fetch, readToken = readAccountToken } = {}) { + let cache, pending; + const controller = new AbortController(); + async function fetchQuota() { + try { + const token = await readToken(); + if (!token) return { status: 'signedOut', windows: [] }; + const now = Date.now(), second = Math.floor(now / 1000); + const url = new URL(MEMBERSHIP_URL); + url.search = new URLSearchParams({ ...QUERY, unix: String(now) }).toString(); + const body = JSON.stringify({ workspace_id: 0 }); + const auth = { Accept: 'application/json', Authorization: `Bearer ${token}` }; + const options = () => ({ redirect: 'error', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]) }); + const membershipResponse = await request(url, { + ...options(), method: 'POST', body, + headers: { + ...auth, 'Content-Type': 'application/json', + yy: md5(`${encodeURIComponent(url.pathname + url.search)}_${body}${md5(String(now))}ooui`), + 'x-timestamp': String(second), + 'x-signature': md5(`${second}I*7Cf%WZ#S&%1RlZJ&C2${body}`), + }, + }); + if (!membershipResponse.ok) throw new Error('membership request failed'); + const membership = await membershipResponse.json(); + const groupId = tokenText(membership?.op_group_id ?? membership?.data?.op_group_id); + if (!groupId) return { status: 'unavailable', windows: [] }; + const quotaUrl = new URL(QUOTA_URL); + quotaUrl.search = new URLSearchParams({ business: 'Agent', device_platform: 'desktop' }).toString(); + const quotaResponse = await request(quotaUrl, { ...options(), headers: { ...auth, 'X-Group-Id': groupId } }); + if (!quotaResponse.ok) throw new Error('quota request failed'); + const windows = quotaWindows(await quotaResponse.json()); + const tier = tokenText(membership?.token_plan_tier ?? membership?.data?.token_plan_tier).slice(0, 40); + return { status: windows.length ? 'ok' : 'unavailable', tier, windows }; + } catch { + return { status: 'error', windows: [] }; + } + } + + return { + get() { + if (cache?.until > Date.now()) return Promise.resolve(cache.value); + pending ??= fetchQuota().then((value) => { + if (value.status === 'error' && cache?.value?.windows.length) { + value = { ...cache.value, stale: true }; + } + cache = { value, until: Date.now() + (value.status === 'error' || value.stale ? 12_000 : 55_000) }; + return value; + }).finally(() => { pending = undefined; }); + return pending; + }, + dispose() { controller.abort(); }, + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs new file mode 100644 index 00000000..b7033d76 --- /dev/null +++ b/sources/minimax-ai/minimax-pet/miniapp/node/preview-window.mjs @@ -0,0 +1,39 @@ +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { stat } from 'node:fs/promises'; +import { join } from 'node:path'; + +export function previewWindowBounds(area) { + if (!area || ![area.x, area.y, area.width, area.height].every(Number.isFinite) || + Math.abs(area.x) > 100_000 || Math.abs(area.y) > 100_000 || + area.width < 200 || area.height < 180 || area.width > 16_000 || area.height > 16_000) { + return { width: 840, height: 480 }; + } + const width = Math.round(Math.min(area.width, Math.max(360, area.width / 2))); + const height = Math.round(Math.min(area.height, Math.max(260, area.height / 2))); + return { width, height, x: Math.round(area.x + (area.width - width) / 2), y: Math.round(area.y + (area.height - height) / 2) }; +} + +export function createPreviewLauncher(dataDir, spawnProcess = spawn) { + const profile = join(dataDir, 'delivery-preview-browser'); + let edge; + return async ({ url, bounds }) => { + if (process.platform !== 'win32') throw new Error('preview_window_unavailable'); + if (!edge) { + for (const root of [process.env['ProgramFiles(x86)'], process.env.ProgramFiles, process.env.LOCALAPPDATA]) { + if (!root) continue; + const candidate = join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'); + if ((await stat(candidate).catch(() => null))?.isFile()) { edge = candidate; break; } + } + } + if (!edge) throw new Error('preview_window_unavailable'); + const position = Number.isFinite(bounds.x) && Number.isFinite(bounds.y) + ? [`--window-position=${bounds.x},${bounds.y}`] : []; + const child = spawnProcess(edge, [ + `--app=${url}`, `--user-data-dir=${profile}`, `--window-size=${bounds.width},${bounds.height}`, ...position, + '--no-first-run', '--no-default-browser-check', '--disable-background-mode', + ], { stdio: 'ignore', windowsHide: false }); + await once(child, 'spawn'); + child.unref(); + }; +} diff --git a/sources/minimax-ai/minimax-pet/miniapp/node/server.mjs b/sources/minimax-ai/minimax-pet/miniapp/node/server.mjs index 5eac7caf..a6a0a593 100644 --- a/sources/minimax-ai/minimax-pet/miniapp/node/server.mjs +++ b/sources/minimax-ai/minimax-pet/miniapp/node/server.mjs @@ -2,12 +2,19 @@ // MiniMax Pet — Codex Pet Mini App Node entry. Serves the pet page, static client assets, and the pet API. import { open, readFile, realpath } from 'node:fs/promises'; +import { randomBytes } from 'node:crypto'; import { createServer } from 'node:http'; -import { extname, join, resolve, sep } from 'node:path'; +import { extname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { pipeline } from 'node:stream/promises'; import { PET_ID_PATTERN, PetError, createPetStore } from './pet-store.mjs'; import { PreferenceError, createPreferenceStore } from './preferences-store.mjs'; +import { createDesktopDrag } from './desktop-drag.mjs'; +import { createMiniMaxQuota } from './minimax-quota.mjs'; +import { createCompletionStore } from './completion-store.mjs'; +import { readDesktopCatalog, readDesktopAsset } from './desktop-catalog.mjs'; +import { deliveryFormat } from '../client/delivery-formats.mjs'; +import { createPreviewLauncher, previewWindowBounds } from './preview-window.mjs'; /** * @typedef {{ debug(m: string, f?: object): void, info(m: string, f?: object): void, warn(m: string, f?: object): void, error(m: string, f?: object): void }} Logger @@ -18,6 +25,10 @@ import { PreferenceError, createPreferenceStore } from './preferences-store.mjs' const BODY_LIMIT = 12 * 1024 * 1024; const DRAIN_LIMIT = 4 * BODY_LIMIT; +const IMAGE_LIMIT = 20 * 1024 * 1024; +const TEXT_PREVIEW_LIMIT = 512 * 1024; +const PREVIEW_LIFETIME = 8 * 60 * 60 * 1000; +const MAX_PREVIEWS = 32; const ASSET_MIME = /** @type {Record} */ ({ '.html': 'text/html; charset=utf-8', @@ -44,11 +55,15 @@ class HttpError extends Error { * @param {MiniAppContext} context * @returns {Promise<{ dispose(): Promise }>} */ -export async function start(context) { +export async function start(context, { launchPreview = createPreviewLauncher(context.dataDir) } = {}) { const clientRoot = resolve(context.pluginRoot, 'miniapp', 'client'); const logger = context.logger; const store = createPetStore({ clientRoot, dataDir: context.dataDir, logger }); const preferences = createPreferenceStore({ dataDir: context.dataDir }); + const completions = createCompletionStore(context.dataDir); + const previews = new Map(); + const desktopDrag = process.platform === 'win32' ? createDesktopDrag(context.pluginRoot) : null; + const quota = createMiniMaxQuota(); /** @type {string | null} */ let clientRootReal = null; @@ -85,6 +100,80 @@ export async function start(context) { requireMethod(method, ['GET']); return serveAsset(response, path.slice('/assets/'.length)); } + if (path === '/api/session-asset') { + requireMethod(method, ['GET']); + requireLocalOrigin(request); + return serveSessionAsset(response, new URLSearchParams(queryAt === -1 ? '' : rawUrl.slice(queryAt + 1))); + } + if (path === '/api/delivery-preview') { + requireMethod(method, ['POST']); + const origin = requireLocalOrigin(request); + const body = await readJsonBody(request, 16 * 1024); + const params = new URLSearchParams(); + for (const field of ['session', 'node', 'file']) { + if (typeof body?.asset?.[field] === 'string') params.set(field, body.asset[field]); + } + const { format, name } = await resolveSessionAsset(params); + const token = randomBytes(24).toString('base64url'); + const title = typeof body?.title === 'string' ? body.title.trim().slice(0, 300) : ''; + const theme = body?.theme === 'dark' || body?.theme === 'light' ? body.theme : ''; + const language = typeof body?.language === 'string' && /^zh\b/iu.test(body.language) ? 'zh-Hans' : 'en'; + if (previews.size >= MAX_PREVIEWS) previews.delete(previews.keys().next().value); + previews.set(token, { params, title: title || name, kind: format.kind, theme, language, expires: Date.now() + PREVIEW_LIFETIME }); + try { + await launchPreview({ url: `${origin}/preview/${token}`, bounds: previewWindowBounds(body?.area) }); + } catch { + previews.delete(token); + throw new HttpError(503, 'preview_window_unavailable', 'preview window unavailable'); + } + return sendJson(response, 200, { opened: true }); + } + if (path.startsWith('/preview/')) { + requireMethod(method, ['GET']); + const route = /^\/preview\/([\w-]{32})(?:\/(info|content))?$/u.exec(path); + const preview = route && previews.get(route[1]); + if (!preview || preview.expires <= Date.now()) throw notFound(); + if (!route[2]) { + const html = await readFile(join(clientRoot, 'delivery-preview.html')); + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff', + 'referrer-policy': 'no-referrer', + 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'", + }); + response.end(html); + return; + } + requireLocalOrigin(request); + if (route[2] === 'content') return serveSessionAsset(response, preview.params); + return sendJson(response, 200, { title: preview.title, kind: preview.kind, theme: preview.theme, language: preview.language }); + } + if (path === '/api/completions' || path === '/api/desktop-catalog') { + if ((request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin') || + (request.headers.origin && request.headers.origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + if (path === '/api/desktop-catalog') { + requireMethod(method, ['GET']); + const catalog = await readDesktopCatalog(); + if (!catalog) throw new HttpError(503, 'desktop_catalog_unavailable', 'desktop catalog unavailable'); + return sendJson(response, 200, catalog); + } + requireMethod(method, ['GET', 'POST']); + if (method === 'GET') return sendJson(response, 200, { records: await completions.get() }); + await completions.apply(await readJsonBody(request, 64 * 1024)); + return sendJson(response, 200, { saved: true }); + } + if (path === '/api/minimax-quota') { + requireMethod(method, ['GET']); + const origin = request.headers.origin; + const fetchSite = request.headers['sec-fetch-site']; + if ((fetchSite && fetchSite !== 'same-origin') || (origin && origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + return sendJson(response, 200, await quota.get()); + } if (path === '/api/preferences') { requireMethod(method, ['GET', 'PATCH']); if (method === 'GET') return sendJson(response, 200, await preferences.get()); @@ -95,6 +184,31 @@ export async function start(context) { if (condition !== undefined && condition !== '*') throw new HttpError(400, 'invalid_preferences_condition', 'only If-None-Match: * is supported'); return sendJson(response, 200, await preferences.patch(await readJsonBody(request, 16 * 1024), { onlyIfUnpersisted: condition === '*' })); } + if (path === '/api/desktop-drag') { + requireMethod(method, ['POST']); + const origin = request.headers.origin; + if (request.headers['sec-fetch-site'] === 'cross-site' || (origin && origin !== `http://${request.headers.host}`)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin write not allowed'); + } + const body = await readJsonBody(request, 512); + const action = body?.action; + if (action !== 'warm' && action !== 'stop' && action !== 'drag') { + throw new HttpError(400, 'invalid_drag_action', 'invalid desktop drag action'); + } + let command = action; + if (action === 'drag') { + const { dx, dy } = body; + if (![dx, dy].every((offset) => Number.isInteger(offset) && Math.abs(offset) <= 512)) { + throw new HttpError(400, 'invalid_drag_offset', 'invalid desktop drag offset'); + } + command = `drag ${dx} ${dy}`; + } + try { + return sendJson(response, 200, { ok: await desktopDrag?.send(command) === true }); + } catch { + return sendJson(response, 200, { ok: false }); + } + } if (path === '/api/pets') { requireMethod(method, ['GET', 'POST']); if (method === 'GET') { @@ -174,7 +288,8 @@ export async function start(context) { disposing ??= (async () => { context.signal.removeEventListener('abort', onAbort); server.closeAllConnections(); - await close(server); + quota.dispose(); + await Promise.all([close(server), desktopDrag?.dispose(), completions.flush()]); logger.info('pet.runtime.disposed'); })(); return disposing; @@ -236,6 +351,59 @@ function notFound() { return new HttpError(404, 'not_found', 'not found'); } +/** @param {Req} request */ +function requireLocalOrigin(request) { + const host = request.headers.host || ''; + const origin = `http://${host}`; + if (!/^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/iu.test(host) || + request.headers['sec-fetch-site'] !== 'same-origin' || + (request.headers.origin && request.headers.origin !== origin)) { + throw new HttpError(403, 'origin_not_allowed', 'cross-origin access not allowed'); + } + return origin; +} + +/** @param {unknown} path @returns {path is string} */ +function isLocalAbsolutePath(path) { + if (typeof path !== 'string' || !isAbsolute(path)) return false; + return process.platform === 'win32' ? /^[a-z]:[/\\][^:\0]*$/iu.test(path) : !path.startsWith('//') && !path.includes('\0'); +} + +/** @param {URLSearchParams} params */ +async function resolveSessionAsset(params) { + const id = params.get('session') || ''; + const node = params.get('node') || ''; + const path = params.get('file') || ''; + if (!/^[\w.:-]{1,128}$/u.test(id) || (node ? path || !/^[\w-]{1,128}$/u.test(node) : path.length > 2048 || !isLocalAbsolutePath(path))) throw notFound(); + // Only the indexed delivery supplies the file path and its permitted workspace. + const asset = await readDesktopAsset(id, { nodeId: node, path }); + if (!asset || !isLocalAbsolutePath(asset.path) || !isLocalAbsolutePath(asset.workspace)) throw notFound(); + const format = deliveryFormat(asset.path); + if (!format || (node && format.kind !== 'image')) throw notFound(); + const [file, workspace] = await Promise.all([realpath(asset.path), realpath(asset.workspace)]).catch(() => []); + if (!file || !workspace || !isLocalAbsolutePath(file) || !isLocalAbsolutePath(workspace)) throw notFound(); + const child = relative(workspace, file); + if (!child || child === '..' || child.startsWith('..' + sep) || isAbsolute(child)) throw notFound(); + return { file, format, name: asset.path.split(/[/\\]/u).at(-1) }; +} + +/** @param {Res} response @param {URLSearchParams} params */ +async function serveSessionAsset(response, params) { + const { file, format } = await resolveSessionAsset(params); + return sendFile(response, file, format.mime, format.kind); +} + +/** @param {import('node:fs/promises').FileHandle} file @param {string} type */ +async function hasRasterSignature(file, type) { + const head = Buffer.alloc(12); + const { bytesRead } = await file.read(head, 0, head.length, 0); + if (bytesRead < head.length) return false; + if (type === 'image/jpeg') return head.subarray(0, 3).toString('hex') === 'ffd8ff'; + if (type === 'image/png') return head.subarray(0, 8).toString('hex') === '89504e470d0a1a0a'; + if (type === 'image/gif') return /^GIF8[79]a$/u.test(head.toString('ascii', 0, 6)); + return head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP'; +} + /** @param {unknown} error */ function errnoCode(error) { return error && typeof error === 'object' && 'code' in error ? String(error.code) : 'unknown'; @@ -263,8 +431,8 @@ function sendError(response, status, code, message, headers) { sendJson(response, status, { error: code, message }, headers); } -/** @param {Res} response @param {string} path @param {string} contentType */ -async function sendFile(response, path, contentType) { +/** @param {Res} response @param {string} path @param {string} contentType @param {string} [preview] */ +async function sendFile(response, path, contentType, preview) { let handle; try { handle = await open(path, 'r'); @@ -274,11 +442,14 @@ async function sendFile(response, path, contentType) { try { const st = await handle.stat(); if (!st.isFile()) throw notFound(); + if (preview === 'image' && (st.size > IMAGE_LIMIT || !await hasRasterSignature(handle, contentType))) throw notFound(); + if (preview && preview !== 'image' && st.size > TEXT_PREVIEW_LIMIT) throw notFound(); response.writeHead(200, { 'content-type': contentType, 'content-length': String(st.size), - 'cache-control': 'no-cache', + 'cache-control': preview ? 'private, no-store' : 'no-cache', 'x-content-type-options': 'nosniff', + ...(preview ? { 'cross-origin-resource-policy': 'same-origin' } : {}), }); const stream = handle.createReadStream({ autoClose: false }); try { diff --git a/sources/minimax-ai/minimax-pet/package-lock.json b/sources/minimax-ai/minimax-pet/package-lock.json index 81e6e669..1cc83b3a 100644 --- a/sources/minimax-ai/minimax-pet/package-lock.json +++ b/sources/minimax-ai/minimax-pet/package-lock.json @@ -1,12 +1,12 @@ { "name": "minimax-pet-source", - "version": "0.9.5", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "minimax-pet-source", - "version": "0.9.5", + "version": "0.10.0", "devDependencies": { "esbuild": "0.25.12", "jsdom": "24.1.3", diff --git a/sources/minimax-ai/minimax-pet/package.json b/sources/minimax-ai/minimax-pet/package.json index ffe64fe5..f2d8411f 100644 --- a/sources/minimax-ai/minimax-pet/package.json +++ b/sources/minimax-ai/minimax-pet/package.json @@ -1,6 +1,6 @@ { "name": "minimax-pet-source", - "version": "0.9.5", + "version": "0.10.0", "private": true, "type": "module", "description": "桌宠插件的开发与验证工具,不进入分发包。",