From 4b0ee4c1c9735722f26bd781dfac82211dabef2d Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 11 Oct 2026 02:44:49 +0800 Subject: [PATCH] feat(notion): connect the Notion account from its plugin page The Notion plugin registered its server but left authorization to a Remote client that did not exist, so a product user could not connect an account. Its browser half now shows a Notion account section on the plugin's page, a connection tag beside the title, guidance after the plugin is switched on, and toasts for connection outcomes. The page mirrors the MCP manager's entry and drives authorization, cancellation, sign-out, and retry through the manager's Remote; it keeps no connection state of its own and opens an authorization URL only for the attempt it started. The model guidance adds one fixed sentence telling the model to send the user to the plugin page when no Notion tool is available. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/connector/notion/README.i18n.yaml | 42 ++-- packages/connector/notion/README.md | 30 ++- packages/connector/notion/README.zh.md | 30 ++- packages/connector/notion/package.json | 37 ++- .../src/client/NotionConnection.module.css | 51 ++++ .../notion/src/client/NotionConnection.tsx | 127 ++++++++++ .../connector/notion/src/client/connection.ts | 225 ++++++++++++++++++ packages/connector/notion/src/client/index.ts | 41 ++++ .../connector/notion/src/client/locales.ts | 105 ++++++++ .../connector/notion/src/css-modules.d.ts | 6 + packages/connector/notion/src/index.ts | 1 + .../notion/tests/components.client.spec.tsx | 150 ++++++++++++ .../notion/tests/connection.client.spec.ts | 208 ++++++++++++++++ .../notion/tests/mount.client.spec.ts | 48 ++++ .../connector/notion/tests/plugin.spec.ts | 1 + .../connector/notion/tsconfig.client.json | 53 +++++ packages/connector/notion/tsconfig.host.json | 25 ++ packages/connector/notion/tsconfig.json | 19 +- packages/connector/notion/tsdown.config.ts | 3 + pnpm-lock.yaml | 51 ++++ scripts/package-dependency-policy.ts | 1 + scripts/verify-package-dependencies.spec.ts | 1 + tsconfig.client.json | 4 +- tsconfig.host.json | 2 +- 26 files changed, 1207 insertions(+), 58 deletions(-) create mode 100644 packages/connector/notion/src/client/NotionConnection.module.css create mode 100644 packages/connector/notion/src/client/NotionConnection.tsx create mode 100644 packages/connector/notion/src/client/connection.ts create mode 100644 packages/connector/notion/src/client/index.ts create mode 100644 packages/connector/notion/src/client/locales.ts create mode 100644 packages/connector/notion/src/css-modules.d.ts create mode 100644 packages/connector/notion/tests/components.client.spec.tsx create mode 100644 packages/connector/notion/tests/connection.client.spec.ts create mode 100644 packages/connector/notion/tests/mount.client.spec.ts create mode 100644 packages/connector/notion/tsconfig.client.json create mode 100644 packages/connector/notion/tsconfig.host.json create mode 100644 packages/connector/notion/tsdown.config.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d4e61f781d..ca29a1f264 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2560,7 +2560,7 @@ export interface Config { ## `@deepseek-ai/dsh-notion` - `inject`: `mcpServers` · `systemPrompt` -- `source`: [`packages/connector/notion/src/index.ts:26`](../packages/connector/notion/src/index.ts) +- `source`: [`packages/connector/notion/src/index.ts:27`](../packages/connector/notion/src/index.ts) ```ts config-catalog /** Notion MCP endpoint and tool loading for the managed server entry. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 44984b226b..684051259a 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2562,7 +2562,7 @@ export interface Config { ## `@deepseek-ai/dsh-notion` - `inject`: `mcpServers` · `systemPrompt` -- `source`: [`packages/connector/notion/src/index.ts:26`](../packages/connector/notion/src/index.ts) +- `source`: [`packages/connector/notion/src/index.ts:27`](../packages/connector/notion/src/index.ts) ```ts config-catalog /** Notion MCP endpoint and tool loading for the managed server entry. */ diff --git a/packages/connector/notion/README.i18n.yaml b/packages/connector/notion/README.i18n.yaml index 228410cbdf..b34481a0bf 100644 --- a/packages/connector/notion/README.i18n.yaml +++ b/packages/connector/notion/README.i18n.yaml @@ -9,8 +9,8 @@ en: ebcdb43f309b330c zh: 364385eb8bbf6171 /deepseek-ai-dsh-notion/summary: - en: d987f216f9bebd1f - zh: 0348b39e08b0d903 + en: ce335815b5b7cb53 + zh: a26d3e61baf53eb9 /deepseek-ai-dsh-notion/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -21,8 +21,8 @@ en: 9643befdbb99d390 zh: b7d6cf34bd69993e /deepseek-ai-dsh-notion/use-this-package/authorize-and-sign-out: - en: bac2be240e693f4a - zh: 10af6da37fd11807 + en: d1709f5f06abcda7 + zh: aa1522f7f858f822 /deepseek-ai-dsh-notion/use-this-package/turn-off-and-uninstall: en: 8fb8e3a36288a635 zh: 3ba01fe30e802d1f @@ -30,27 +30,27 @@ en: fbba2c704dab668a zh: 7fd7ece85739c6e3 /deepseek-ai-dsh-notion/understand-the-implementation: - en: 8e9f6ed96ee55201 - zh: 10e8d2071d85069d + en: 5fdb86f56d07b8e1 + zh: 3fee4ea1c0689d1f /deepseek-ai-dsh-notion/further-exploration: - en: 9de5e710b4dd7ba9 - zh: d895238cbd9e08f7 + en: b1a8832ec6aaa59a + zh: 69eb8266916d008a /deepseek-ai-dsh-notion/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 -/deepseek-ai-dsh-notion/model-experience/naming-guidance: - en: c5d4839916cd6dc2 - zh: cb6d9b8c4182929c -/deepseek-ai-dsh-notion/model-experience/naming-guidance/what-the-model-sees: +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance: + en: 01b6ec6d681e457b + zh: 7fe0d1c9d1037bd4 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/what-the-model-sees: en: a62a8dbe1f7b7944 zh: 32a94fa68d8b30c2 -/deepseek-ai-dsh-notion/model-experience/naming-guidance/what-the-model-sees/guidance-text: +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/what-the-model-sees/guidance-text: en: 8f57292f6821da96 zh: b2d3bc7e5c9cbc05 -/deepseek-ai-dsh-notion/model-experience/naming-guidance/token-effect: - en: 570e40dca65df1ef - zh: 4f71ad76a17a2c54 -/deepseek-ai-dsh-notion/model-experience/naming-guidance/kv-cache-effect: +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/token-effect: + en: 263969c79903e387 + zh: d45f9e49d9a252c3 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/kv-cache-effect: en: e9668826c9355444 zh: 66f609e3779fd510 /deepseek-ai-dsh-notion/model-experience/notion-server-tools-and-instructions: @@ -66,8 +66,8 @@ en: c9327a5b0f494922 zh: e36a635527a79dee /deepseek-ai-dsh-notion/known-limitations-and-deferred-work: - en: ea61eb47ae041420 - zh: 65eed6f181f9b392 + en: 7a6944464f5f1f93 + zh: 8230c8d06b7d577b /deepseek-ai-dsh-notion/known-limitations-and-deferred-work/dev-note: - en: ad49c4ecc94eebdf - zh: 965abefc874d8e55 + en: fc88fd2563d58b64 + zh: ac8c6b5db2138e28 diff --git a/packages/connector/notion/README.md b/packages/connector/notion/README.md index d5232c1af1..7819a7a0fd 100644 --- a/packages/connector/notion/README.md +++ b/packages/connector/notion/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The Notion plugin registers Notion's hosted MCP server, `https://mcp.notion.com/mcp`, with the Host's shared [MCP manager](../../mcp/mcp-manager/README.md) for as long as the plugin is loaded. After the user authorizes a Notion account, every conversation on that Host can use the server's tools, and the model is told to call the integration the Notion plugin. The manager owns the connection, OAuth authorization, the saved grant, and sign-out; this package adds no account interface of its own. It runs in the Web and Desktop compositions. +The Notion plugin registers Notion's hosted MCP server, `https://mcp.notion.com/mcp`, with the Host's shared [MCP manager](../../mcp/mcp-manager/README.md) for as long as the plugin is loaded. The user connects a Notion account from the plugin's page on the Web sidebar's **Plugins** page; afterwards every conversation on that Host can use the server's tools, and the model is told to call the integration the Notion plugin. The manager owns the connection, OAuth authorization, the saved grant, and sign-out; the page reads and drives them through the manager's Remote and adds no account interface of its own. It runs in the Web and Desktop compositions. ## Table of Contents @@ -39,7 +39,18 @@ The bundle patch inserts the `notion` row after the profile's other layers. The The plugin registers the server `notion` with the fixed OAuth credential key `mcp-client/notion`. Without a saved grant the server waits for authorization and exposes no Notion tools. With a saved grant the manager connects at startup and refreshes tokens as needed. Notion's tools load [on demand](../../mcp/mcp-client/README.md#on-demand-tool-loading) by default: the system prompt lists them, and each agent loads the ones it needs with `mcp__notion__load_tools`. -Authorization uses the manager's [OAuth operations](../../mcp/mcp-manager/README.md#oauth-authorization) through Remote; there is no sign-in page yet. A Remote client calls `ctx.remote.mcpServers.startAuthorization('notion')`, opens the returned `authorizationUrl` in a browser on the Host machine, and the user approves access in Notion. `list()` and `watch` report progress, and `cancelAuthorization('notion', id)` cancels one attempt. `signOut('notion')` deletes the local grant and keeps the client registration; it does not revoke the connection on Notion's side. +While the plugin is on, its page on the **Plugins** page shows a **Notion account** section, and a tag beside the title reads Not connected, Connecting, Connected, Reconnect, or Unavailable. Switching the plugin on from the list while no account is connected offers **Connect Notion**, which opens the plugin's page and starts authorization. + +| Section state | Action | +|---|---| +| Not connected, or the grant expired, no longer matches the settings, was rejected, or lacks permissions | **Connect Notion** or **Connect again** starts an authorization attempt | +| Waiting for you to confirm in the browser | The browser that started the attempt opens Notion's authorization page once; **Open authorization page** opens it again, and **Cancel** ends the attempt | +| Connected | **Sign out** asks for confirmation, then deletes the local grant | +| Cannot connect right now | **Retry** restarts the server and keeps the existing grant | + +Authorization must be completed in a browser on the Host machine. After the user approves access in Notion, the callback page says DSH received the authorization; the section then shows the result. Leaving the page does not cancel an attempt, which the Host owns. A failed attempt shows **Authorization was not completed. Try again.**; a failed page action shows a toast. Sign-out keeps the client registration and does not revoke the connection on Notion's side. + +The page calls the manager's [OAuth operations](../../mcp/mcp-manager/README.md#oauth-authorization) through Remote: `watch` reports the entry, `startAuthorization('notion')` returns an attempt whose `authorizationUrl` the stream reports, `cancelAuthorization('notion', id)` cancels it, `signOut('notion')` deletes the grant, and `restart('notion')` retries. Other Remote clients can use the same operations. ### Turn off and uninstall @@ -62,7 +73,9 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-no
Implementation internals — click to expand -[`src/index.ts`](src/index.ts) makes two registrations, both effects of the plugin's fiber: `ctx.mcpServers.register('notion', …)` adds a Streamable HTTP entry with the configured `url` and OAuth credential key, and `ctx.systemPrompt.section()` adds the naming guidance at the `MCP_SERVERS` order. The server name fixes the `mcp__notion__` tool namespace, and the credential key fixes the grant address, so a reloaded or reinstalled plugin reaches the same tools and grant. The manager validates the entry when it is registered; a configured or registered server that already uses the name or key makes the plugin fail to load before the guidance is added. +The Host half, [`src/index.ts`](src/index.ts), makes two registrations, both effects of the plugin's fiber: `ctx.mcpServers.register('notion', …)` adds a Streamable HTTP entry with the configured `url` and OAuth credential key, and `ctx.systemPrompt.section()` adds the naming guidance at the `MCP_SERVERS` order. The server name fixes the `mcp__notion__` tool namespace, and the credential key fixes the grant address, so a reloaded or reinstalled plugin reaches the same tools and grant. The manager validates the entry when it is registered; a configured or registered server that already uses the name or key makes the plugin fail to load before the guidance is added. + +The browser half, [`src/client/index.ts`](src/client/index.ts), attaches to the `notion` row, so its registrations exist while that row is on. One `NotionConnection` per browser plugin mirrors the manager's `watch` stream and derives the page state from the `notion` entry alone; it keeps only whether the stream is delivering, whether a page action is pending, and the latest notice. It registers `plugins.bundle.config` keyed by the package name for the section, `plugins.bundle.activation` for the guidance, `plugins.detail.badge` for the tag, and a `shell.overlay` toast. It opens an authorization URL only for the attempt this browser started, and only when the URL uses HTTPS or loopback HTTP.
@@ -76,13 +89,14 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-no - [MCP client](../../mcp/mcp-client/README.md) — connection, tool naming, OAuth grant refresh, and redaction. - [MCP subsystem](../../../docs/subsystems/mcp.md) — how the MCP packages fit together. - [Plugin Manager](../../boot/plugin-manager/README.md) — installation and enablement. +- [Plugins page](../../client/ui-plugin-manager/README.md#use-this-package) — the bundle page slots the browser half registers into. ----- ## Model Experience -### Naming guidance +### Naming and connection guidance #### What the model sees @@ -91,12 +105,12 @@ While the plugin is loaded, the system prompt contains the text below after the ##### Guidance text ```markdown -Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. +Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins. ``` #### Token effect -The fixed sentence adds a few dozen tokens to every request while the plugin is loaded. +The two fixed sentences add about 70 tokens to every request while the plugin is loaded. #### KV Cache effect @@ -120,7 +134,7 @@ Notion's instructions (or, with `eager`, its tools) appear when the connection s -- There is no sign-in page. Until a Remote client presents the manager's authorization URL, a user cannot authorize Notion from the product. +- The Notion account section exists only while the plugin is on. To sign out after turning the plugin off, turn it on again or delete the grant record. - Only the Web and Desktop compositions mount the MCP manager; other profiles leave the plugin inactive. - The authorization callback is `http://127.0.0.1:` on the Host, so the browser that completes authorization must run on the Host machine. A Web Host reached from another machine cannot finish authorization. - Desktop listens on an OS-assigned port for each launch. Authorizing again after a restart registers a new OAuth client and keeps the earlier registration record; saved grants refresh normally across restarts. @@ -133,6 +147,6 @@ Notion's instructions (or, with `eager`, its tools) appear when the connection s
Working context for maintainers — click to expand -Specs run the plugin against the MCP manager and the mcp-client loopback OAuth server fixture. The `notion-plugin` session snapshot replays the Notion row without a saved grant, so it pins the naming guidance and verifies that no request reaches the server. +Host specs run the plugin against the MCP manager and the mcp-client loopback OAuth server fixture; client specs drive the browser half with a fake manager stream. The `notion-plugin` session snapshot replays the Notion row without a saved grant, so it pins the naming guidance and verifies that no request reaches the server.
diff --git a/packages/connector/notion/README.zh.md b/packages/connector/notion/README.zh.md index b2d3a4ad35..5578ddbb69 100644 --- a/packages/connector/notion/README.zh.md +++ b/packages/connector/notion/README.zh.md @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -Notion 插件在加载期间把 Notion 托管的 MCP 服务器 `https://mcp.notion.com/mcp` 注册到 Host 共用的 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)。用户授权一个 Notion 账号后,该 Host 上的所有对话都能使用这个服务器的工具,模型也会被告知把这项集成称为 Notion 插件。连接、OAuth 授权、已保存的 grant 和退出登录都由管理器负责,本包不另设账号接口。插件运行在 Web 与 Desktop 组合中。 +Notion 插件在加载期间把 Notion 托管的 MCP 服务器 `https://mcp.notion.com/mcp` 注册到 Host 共用的 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)。用户在 Web 侧栏**插件**页面的插件详情页中连接 Notion 账号,之后该 Host 上的所有对话都能使用这个服务器的工具,模型也会被告知把这项集成称为 Notion 插件。连接、OAuth 授权、已保存的 grant 和退出登录都由管理器负责;页面通过管理器的 Remote 读取和操作它们,不另设账号接口。插件运行在 Web 与 Desktop 组合中。 ## 目录 @@ -39,7 +39,18 @@ bundle patch 在 profile 其他层之后插入 `notion` 行。插件需要 `mcpS 插件以固定的 OAuth 凭据 key `mcp-client/notion` 注册服务器 `notion`。没有已保存的 grant 时,服务器等待授权,不提供 Notion 工具。有已保存的 grant 时,管理器在启动时连接,并按需刷新 token。Notion 的工具默认[按需加载](../../mcp/mcp-client/README.zh.md#on-demand-tool-loading):系统提示词列出这些工具,每个 agent 用 `mcp__notion__load_tools` 加载需要的工具。 -授权通过 Remote 使用管理器的 [OAuth 操作](../../mcp/mcp-manager/README.zh.md#oauth-authorization);目前还没有登录页面。Remote 客户端调用 `ctx.remote.mcpServers.startAuthorization('notion')`,在 Host 所在机器的浏览器中打开返回的 `authorizationUrl`,用户在 Notion 中同意授权。`list()` 与 `watch` 报告进度,`cancelAuthorization('notion', id)` 取消一次授权尝试。`signOut('notion')` 删除本地 grant 并保留客户端注册;它不会在 Notion 一侧撤销连接。 +插件开启期间,它在**插件**页面的详情页显示 **Notion 账号**区块,标题旁的标签显示未连接、连接中、已连接、需要重新连接或暂时无法连接。在列表中开启插件而尚未连接账号时,页面提示**连接 Notion**,点击后打开插件详情页并发起授权。 + +| 区块状态 | 操作 | +|---|---| +| 未连接,或授权已过期、与当前设置不再匹配、被拒绝、缺少权限 | **连接 Notion** 或**重新连接**发起一次授权尝试 | +| 等待你在浏览器中确认 | 发起尝试的浏览器打开一次 Notion 授权页面;**打开授权页面**再次打开,**取消**结束这次尝试 | +| 已连接 | **退出登录**确认后删除本地 grant | +| 暂时无法连接 | **重试**重启服务器并保留现有授权 | + +授权必须在 Host 所在机器的浏览器中完成。用户在 Notion 中同意授权后,回调页面说明 DSH 已收到授权,区块随后显示结果。离开页面不会取消授权尝试,尝试由 Host 持有。授权失败时显示**授权未完成,请重试**;页面操作失败时显示 toast。退出登录保留客户端注册,不会在 Notion 一侧撤销连接。 + +页面通过 Remote 调用管理器的 [OAuth 操作](../../mcp/mcp-manager/README.zh.md#oauth-authorization):`watch` 报告条目,`startAuthorization('notion')` 返回一次授权尝试,其 `authorizationUrl` 由流报告,`cancelAuthorization('notion', id)` 取消它,`signOut('notion')` 删除 grant,`restart('notion')` 重试。其他 Remote 客户端可以使用同样的操作。 ### 停用与卸载 @@ -62,7 +73,9 @@ bundle patch 在 profile 其他层之后插入 `notion` 行。插件需要 `mcpS
实现内部机制——点击展开 -[`src/index.ts`](src/index.ts) 进行两项注册,二者都是插件 fiber 的 effect:`ctx.mcpServers.register('notion', …)` 以配置的 `url` 和 OAuth 凭据 key 添加一个 Streamable HTTP 条目,`ctx.systemPrompt.section()` 在 `MCP_SERVERS` 排序位置添加称呼指引。服务器名固定了 `mcp__notion__` 工具命名空间,凭据 key 固定了 grant 地址,因此重新加载或重新安装的插件会得到同样的工具和 grant。管理器在注册时校验条目;如果已配置或已注册的服务器占用了该名称或 key,插件会在添加指引之前加载失败。 +Host 侧的 [`src/index.ts`](src/index.ts) 进行两项注册,二者都是插件 fiber 的 effect:`ctx.mcpServers.register('notion', …)` 以配置的 `url` 和 OAuth 凭据 key 添加一个 Streamable HTTP 条目,`ctx.systemPrompt.section()` 在 `MCP_SERVERS` 排序位置添加称呼指引。服务器名固定了 `mcp__notion__` 工具命名空间,凭据 key 固定了 grant 地址,因此重新加载或重新安装的插件会得到同样的工具和 grant。管理器在注册时校验条目;如果已配置或已注册的服务器占用了该名称或 key,插件会在添加指引之前加载失败。 + +浏览器侧的 [`src/client/index.ts`](src/client/index.ts) 挂在 `notion` 行上,因此其注册只在该行开启时存在。每个浏览器插件有一个 `NotionConnection`,镜像管理器的 `watch` 流,只根据 `notion` 条目推导页面状态;它只保存流是否在送达、页面操作是否进行中以及最近一条提示。它注册以包名为 key 的 `plugins.bundle.config` 作为区块、`plugins.bundle.activation` 作为引导、`plugins.detail.badge` 作为标签,以及一个 `shell.overlay` toast。它只为本浏览器发起的尝试打开授权链接,且只打开使用 HTTPS 或回环 HTTP 的链接。
@@ -76,13 +89,14 @@ bundle patch 在 profile 其他层之后插入 `notion` 行。插件需要 `mcpS - [MCP 客户端](../../mcp/mcp-client/README.zh.md)——连接、工具命名、OAuth grant 刷新与脱敏。 - [MCP 子系统](../../../docs/subsystems/mcp.zh.md)——各 MCP 包如何协同。 - [Plugin Manager](../../boot/plugin-manager/README.zh.md)——安装与启用。 +- [插件页面](../../client/ui-plugin-manager/README.zh.md#use-this-package)——浏览器侧注册所用的 bundle 详情页 slot。 ----- ## 模型体验 -### 称呼指引 +### 称呼与连接指引 #### 模型看到什么 @@ -91,12 +105,12 @@ bundle patch 在 profile 其他层之后插入 `notion` 行。插件需要 `mcpS ##### 指引文本 ```markdown -Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. +Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins. ``` #### Token 影响 -插件加载期间,这句固定文字为每次请求增加几十个 token。 +插件加载期间,这两句固定文字为每次请求增加约 70 个 token。 #### KV Cache 影响 @@ -120,7 +134,7 @@ Notion 的服务器说明(设为 `eager` 时则是其工具)在连接成功 -- 没有登录页面。在 Remote 客户端展示管理器的授权链接之前,用户无法在产品中授权 Notion。 +- Notion 账号区块只在插件开启时存在。关闭插件后如需退出登录,请先重新开启插件,或删除 grant 记录。 - 只有 Web 与 Desktop 组合挂载 MCP 管理器;在其他 profile 中插件保持未激活。 - 授权回调地址是 Host 上的 `http://127.0.0.1:`,因此完成授权的浏览器必须运行在 Host 所在机器上。从另一台机器访问的 Web Host 无法完成授权。 - Desktop 每次启动都监听操作系统分配的端口。重启后再次授权会注册一个新的 OAuth 客户端,并保留之前的注册记录;已保存的 grant 在重启前后正常刷新。 @@ -133,6 +147,6 @@ Notion 的服务器说明(设为 `eager` 时则是其工具)在连接成功
维护者工作上下文——点击展开 -单测让插件运行在 MCP 管理器和 mcp-client 的回环 OAuth 服务器夹具之上。`notion-plugin` 会话快照在没有已保存 grant 的情况下回放 Notion 行,因此它固定称呼指引,并验证没有请求到达服务器。 +Host 侧单测让插件运行在 MCP 管理器和 mcp-client 的回环 OAuth 服务器夹具之上;客户端单测用模拟的管理器流驱动浏览器侧。`notion-plugin` 会话快照在没有已保存 grant 的情况下回放 Notion 行,因此它固定称呼指引,并验证没有请求到达服务器。
diff --git a/packages/connector/notion/package.json b/packages/connector/notion/package.json index d58e423d43..1378801a7f 100644 --- a/packages/connector/notion/package.json +++ b/packages/connector/notion/package.json @@ -18,6 +18,10 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, "./locale/*.json": "./locale/*.json", "./src/*": "./src/*", "./package.json": "./package.json", @@ -26,6 +30,7 @@ "files": [ "locale/*.json", "lib/index.js", + "lib/client.js", "cordis.patch.yml", "lib/types/**/*.d.ts" ], @@ -33,8 +38,21 @@ "dsh": { "bundle": { "patch": "./cordis.patch.yml" + }, + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-ui-plugin-manager" + ], + "platform": "web" } }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" }, @@ -51,6 +69,23 @@ "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-mcp-resources": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-mcp-client": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@testing-library/react": "^16.3.3", + "@types/react": "~18.3.1", + "react": "^18.2.0", + "react-dom": "^18.2.0" } } diff --git a/packages/connector/notion/src/client/NotionConnection.module.css b/packages/connector/notion/src/client/NotionConnection.module.css new file mode 100644 index 0000000000..c15f495d50 --- /dev/null +++ b/packages/connector/notion/src/client/NotionConnection.module.css @@ -0,0 +1,51 @@ +.section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.title { + margin: 0 0 4px; + font-size: 14px; + line-height: 20px; + font-weight: 500; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + min-height: 28px; +} + +.label { + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.actions { + display: flex; + gap: 8px; + margin-left: auto; +} + +.detail, +.hint, +.failure { + margin: 0; + font-size: 13px; + line-height: 20px; +} + +.detail { + color: var(--dsw-alias-label-secondary); +} + +.hint { + color: var(--dsw-alias-label-tertiary); +} + +.failure { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/connector/notion/src/client/NotionConnection.tsx b/packages/connector/notion/src/client/NotionConnection.tsx new file mode 100644 index 0000000000..8635b69448 --- /dev/null +++ b/packages/connector/notion/src/client/NotionConnection.tsx @@ -0,0 +1,127 @@ +/** Notion connection surfaces on the Plugins page: the bundle section, title tag, activation guidance, and notices. */ +import { useEffect, useState, type ReactNode } from 'react' +import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import { NOTION_PACKAGE, presentConnection, type ConnectionFace, type ConnectionPresentation } from './connection.ts' +import type { NotionKey, NS } from './locales.ts' +import css from './NotionConnection.module.css' + +type Phase = ConnectionPresentation['phase'] +type FaceProps = InjectFace & PropsLocale + +const TONE: Record = { + 'checking': 'ongoing', 'connecting': 'ongoing', 'authorizing': 'ongoing', 'waiting-browser': 'ongoing', + 'connected': 'done', 'disconnected': 'idle', 'reconnect': 'warning', 'unavailable': 'error', +} + +const BADGE: Record = { + 'checking': undefined, + 'connecting': ['badge.connecting', 'info'], 'authorizing': ['badge.connecting', 'info'], 'waiting-browser': ['badge.connecting', 'info'], + 'connected': ['badge.connected', 'success'], 'disconnected': ['badge.disconnected', 'outline'], + 'reconnect': ['badge.reconnect', 'warning'], 'unavailable': ['badge.unavailable', 'danger'], +} + +function detail(shown: ConnectionPresentation): NotionKey | undefined { + switch (shown.phase) { + case 'checking': return undefined + case 'reconnect': return `detail.reconnect.${shown.reason}` + default: return `detail.${shown.phase}` + } +} + +/** + * The connection section on the Notion bundle's page. + * @param props - the shared connection face and the Notion dictionary. + * @returns the status line, its actions, and the sign-out confirmation. + */ +export function NotionConnectionSection(props: FaceProps): ReactNode { + const { useNotionConnection, connect, cancel, signOut, retry, openAuthorization, t } = props + const snapshot = useNotionConnection(value => value) + const [confirming, setConfirming] = useState(false) + const shown = presentConnection(snapshot.server) + const disabled = snapshot.busy || !snapshot.linked + const key = detail(shown) + const action = (label: NotionKey, onClick: () => void, variant: 'primary' | 'outline' | 'ghost' = 'outline'): ReactNode => + + const actions: ReactNode[] = [] + switch (shown.phase) { + case 'disconnected': actions.push(action('action.connect', connect, 'primary')); break + case 'reconnect': actions.push(action('action.reconnect', connect, 'primary')); break + case 'waiting-browser': actions.push(action('action.open', openAuthorization, 'primary'), action('action.cancel', cancel, 'ghost')); break + case 'authorizing': actions.push(action('action.cancel', cancel, 'ghost')); break + case 'connected': actions.push(action('action.signOut', () => { setConfirming(true) })); break + case 'unavailable': actions.push(action('action.retry', retry)); break + case 'checking': + case 'connecting': break + } + return ( +
+

{t('section.title')}

+
+ + {t(`status.${shown.phase}`)} +
{actions}
+
+ {key === undefined ? null :

{t(key)}

} + {'failed' in shown && shown.failed ?

{t('failed')}

: null} +

{t('hostBrowser')}

+ { setConfirming(false) }} + footer={<> + + + }> +

{t('signOut.body')}

+
+
+ ) +} + +/** + * The connection tag beside the Notion bundle's title. + * @param props - the open detail page's subject, the connection face, and the dictionary. + * @returns the tag for the Notion bundle, or null on any other page. + */ +export function NotionConnectionBadge({ subject, useNotionConnection, t }: FaceProps & PropsRuntime<'plugins.detail.badge'>): ReactNode { + const phase = useNotionConnection(value => presentConnection(value.server).phase) + if (subject.kind === 'item' || subject.pkg.name !== NOTION_PACKAGE || !subject.pkg.enabled) return null + const badge = BADGE[phase] + return badge === undefined ? null : {t(badge[0])} +} + +/** + * Guidance after the user switches the Notion bundle on while no account is connected. + * @param props - activation callbacks, the connection face, and the dictionary. + * @returns a dismissible prompt that starts authorization from the bundle's page. + */ +export function NotionConnectionActivation({ useNotionConnection, connect, onDismiss, onOpenDetails, t }: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode { + const phase = useNotionConnection(value => presentConnection(value.server).phase) + const needed = phase === 'disconnected' || phase === 'reconnect' + useEffect(() => { + if (phase !== 'checking' && !needed) onDismiss() + }, [phase, needed, onDismiss]) + return ( + + + + }> +

{t('activation.body')}

+
+ ) +} + +/** + * Connection outcomes reported outside the Plugins panel's lifetime. + * @param props - the shared notice, its dismissal, and the dictionary. + * @returns the toast for the latest notice, or null. + */ +export function NotionConnectionToast({ useNotionConnection, dismissNotice, t }: FaceProps): ReactNode { + const notice = useNotionConnection(value => value.notice) + if (notice === undefined) return null + const failed = notice.kind === 'action-failed' + return ( + } : { tone: 'success' as const }} /> + ) +} diff --git a/packages/connector/notion/src/client/connection.ts b/packages/connector/notion/src/client/connection.ts new file mode 100644 index 0000000000..7cbc3abbce --- /dev/null +++ b/packages/connector/notion/src/client/connection.ts @@ -0,0 +1,225 @@ +/** Browser mirror of the managed Notion server and the Plugins page's connection actions. */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { McpAuthorizationReason, McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' + +/** The server name the Notion plugin registers with the MCP manager. */ +export const NOTION_SERVER = 'notion' + +/** The npm package whose bundle page carries the connection section. */ +export const NOTION_PACKAGE = '@deepseek-ai/dsh-notion' + +/** A transient outcome the page reports outside its own lifetime. */ +export interface ConnectionNotice { + readonly seq: number + readonly kind: 'connected' | 'signed-out' | 'action-failed' +} + +/** The page's whole view: the Host's Notion entry plus this browser's pending action and notice. */ +export interface ConnectionSnapshot { + /** The manager's Notion entry; undefined until the stream reports one. */ + readonly server: McpManagedServerView | undefined + /** Whether the manager stream is delivering. */ + readonly linked: boolean + /** Whether an action this page started has not settled. */ + readonly busy: boolean + readonly notice: ConnectionNotice | undefined +} + +/** What the user sees about the connection, derived from the Host entry alone. */ +export type ConnectionPresentation = + | { readonly phase: 'checking' | 'connected' | 'connecting' } + | { readonly phase: 'waiting-browser'; readonly attempt: McpOAuthAttemptId; readonly url: string | undefined } + | { readonly phase: 'authorizing'; readonly attempt: McpOAuthAttemptId } + | { readonly phase: 'disconnected'; readonly failed: boolean } + | { readonly phase: 'reconnect'; readonly reason: Exclude; readonly failed: boolean } + | { readonly phase: 'unavailable'; readonly failed: boolean } + +/** Page-facing actions and the snapshot hook the slot entries inject. */ +export interface ConnectionFace { + hooks: { notionConnection: HostObservable } + connect(): void + cancel(): void + signOut(): void + retry(): void + openAuthorization(): void + dismissNotice(): void +} + +function attemptPresentation(attempt: McpOAuthAttemptView): ConnectionPresentation | undefined { + switch (attempt.phase) { + case 'waiting-browser': return { phase: 'waiting-browser', attempt: attempt.id, url: attempt.authorizationUrl } + case 'starting': + case 'exchanging': + case 'committing': return { phase: 'authorizing', attempt: attempt.id } + case 'authorized': + case 'cancelled': + case 'failed': return undefined + /* v8 ignore next -- closed attempt phase union */ + default: return assertNever(attempt.phase) + } +} + +/** + * Derive the connection the page shows from the manager's Notion entry. + * @param server - the entry as the manager last reported it. + * @returns the phase, with the active attempt or the reason a new authorization is needed. + */ +export function presentConnection(server: McpManagedServerView | undefined): ConnectionPresentation { + if (server === undefined) return { phase: 'checking' } + const attempt = server.authorization + const active = attempt === undefined ? undefined : attemptPresentation(attempt) + if (active !== undefined) return active + const failed = attempt?.phase === 'failed' + const status = server.status + switch (status.state) { + case 'connected': return { phase: 'connected' } + case 'connecting': + case 'reconnecting': return { phase: 'connecting' } + case 'waiting-authorization': + return status.reason === 'missing' ? { phase: 'disconnected', failed } : { phase: 'reconnect', reason: status.reason, failed } + case 'closed': + case 'waiting-credentials': + case 'disabled': + case 'failed': return { phase: 'unavailable', failed } + /* v8 ignore next -- closed managed status union */ + default: return assertNever(status) + } +} + +function openable(url: string): boolean { + if (!URL.canParse(url)) return false + const parsed = new URL(url) + return parsed.protocol === 'https:' + || (parsed.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname)) +} + +function openAuthorizationPage(url: string | undefined): void { + if (url !== undefined && openable(url)) window.open(url, '_blank', 'noopener,noreferrer') +} + +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + +/** One manager subscription per browser plugin, shared by every Notion entry on the Plugins page. */ +export class NotionConnection { + /** The page's whole view, published after each stream item or page action settles. */ + readonly state: SnapshotStore = createSnapshotStore({ + server: undefined, linked: false, busy: false, notice: undefined, + }) + + /** The attempt this browser started; only its URL opens a window here. */ + private started: McpOAuthAttemptId | undefined + private readonly opened = new Set() + private seq = 0 + private disposed = false + private readonly stream: RemoteStream + private readonly observing: Promise + + constructor(private readonly ctx: Context) { + this.stream = ctx.remote.$stream({ + name: 'Notion connection', open: signal => ctx.remote.mcpServers.watch(signal), + ended: () => new Error('Notion connection stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() + } + + /** + * Bind the page-facing actions; each runs without awaiting so slot handlers stay synchronous. + * @returns the face the slot entries inject. + */ + face(): ConnectionFace { + return { + hooks: { notionConnection: this.state }, + connect: () => { void this.connect() }, + cancel: () => { void this.cancel() }, + signOut: () => { void this.run(async () => { await settle(this.ctx.remote.mcpServers.signOut(NOTION_SERVER)); this.notify('signed-out') }) }, + retry: () => { void this.run(async () => { await settle(this.ctx.remote.mcpServers.restart(NOTION_SERVER)) }) }, + openAuthorization: () => { + const shown = presentConnection(this.state.getSnapshot().server) + if (shown.phase === 'waiting-browser') openAuthorizationPage(shown.url) + }, + dismissNotice: () => { this.patch({ notice: undefined }) }, + } + } + + /** Stop observing the manager; Host-owned attempts keep running. */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private async observe(): Promise { + try { + for await (const item of this.stream) { + const server = item.value.find(entry => entry.name === NOTION_SERVER) + this.patch({ server, linked: true }) + this.follow(server) + item.accept() + } + } catch { + // The carrier already reported the failure; a disposed page has nothing left to show. + if (!this.disposed) this.patch({ linked: false }) + } + } + + /** Open this browser's authorization page once, and report its outcome. */ + private follow(server: McpManagedServerView | undefined): void { + const attempt = server?.authorization + if (attempt === undefined || attempt.id !== this.started) return + if (attempt.phase === 'waiting-browser' && !this.opened.has(attempt.id)) { + this.opened.add(attempt.id) + openAuthorizationPage(attempt.authorizationUrl) + } + if (attempt.phase === 'authorized') this.notify('connected') + if (attempt.phase === 'authorized' || attempt.phase === 'cancelled' || attempt.phase === 'failed') this.started = undefined + } + + private async connect(): Promise { + await this.run(async () => { + const attempt = await settle(this.ctx.remote.mcpServers.startAuthorization(NOTION_SERVER)) + this.started = attempt.id + // The stream may have reported this attempt before the call answered. + this.follow(this.state.getSnapshot().server) + }) + } + + private async cancel(): Promise { + const shown = presentConnection(this.state.getSnapshot().server) + if (shown.phase !== 'waiting-browser' && shown.phase !== 'authorizing') return + await this.run(async () => { await settle(this.ctx.remote.mcpServers.cancelAuthorization(NOTION_SERVER, shown.attempt)) }) + } + + private async run(operation: () => Promise): Promise { + if (this.state.getSnapshot().busy) return + this.patch({ busy: true }) + try { + await operation() + } catch { + // The Host keeps the diagnostic; the page reports one retryable outcome. + this.notify('action-failed') + } finally { + this.patch({ busy: false }) + } + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } + + private notify(kind: ConnectionNotice['kind']): void { + if (this.disposed) return + this.seq += 1 + this.patch({ notice: { seq: this.seq, kind } }) + } +} diff --git a/packages/connector/notion/src/client/index.ts b/packages/connector/notion/src/client/index.ts new file mode 100644 index 0000000000..7df48e78db --- /dev/null +++ b/packages/connector/notion/src/client/index.ts @@ -0,0 +1,41 @@ +/** + * Notion plugin, browser half: the connection section on the Notion bundle's + * page, the tag beside its title, guidance after the bundle is switched on, + * and connection notices. Authorization, status, and sign-out go through the + * MCP manager's Remote; the page keeps no connection state of its own. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { NOTION_PACKAGE, NotionConnection } from './connection.ts' +import { en, NS, zh } from './locales.ts' +import { NotionConnectionActivation, NotionConnectionBadge, NotionConnectionSection, NotionConnectionToast } from './NotionConnection.tsx' + +/** Services the slot registrations and the manager Remote need. */ +export const inject = ['remote', 'remote.mcpServers', 'slots', 'locale'] + +/** + * Register the Notion connection surfaces for as long as the Notion row is on. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'notion: dictionaries') + const connection = new NotionConnection(ctx) + ctx.effect(() => async () => { await connection.dispose() }, 'notion: connection') + const face = connection.face() + ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: NOTION_PACKAGE, locale: NS, inject: () => face, + }, NotionConnectionSection)) + ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: NOTION_PACKAGE, locale: NS, inject: () => face, + }, NotionConnectionActivation)) + ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'notion.connection', locale: NS, inject: () => face, + }, NotionConnectionBadge)) + ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'notion.connection-toast', locale: NS, inject: () => face, + }, NotionConnectionToast)) +} diff --git a/packages/connector/notion/src/client/locales.ts b/packages/connector/notion/src/client/locales.ts new file mode 100644 index 0000000000..08da815f7c --- /dev/null +++ b/packages/connector/notion/src/client/locales.ts @@ -0,0 +1,105 @@ +/** Locale-owned copy for the Notion plugin's connection on the Plugins page. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace for every Notion connection surface. */ +export const NS = 'notion' + +/** Chinese dictionary and key source. */ +export const zh = { + 'section.title': 'Notion 账号', + 'status.checking': '正在检查连接', + 'status.disconnected': '未连接', + 'status.waiting-browser': '等待你在浏览器中确认', + 'status.authorizing': '正在连接', + 'status.connecting': '正在连接', + 'status.connected': '已连接', + 'status.reconnect': '需要重新连接', + 'status.unavailable': '暂时无法连接', + 'detail.disconnected': '连接 Notion 账号后,可以在对话中搜索、读取和编辑你授权的页面与数据库。', + 'detail.waiting-browser': '已打开 Notion 授权页面。在 Notion 中确认后,回到这里查看结果。', + 'detail.authorizing': '正在与 Notion 完成授权。', + 'detail.connecting': '正在连接 Notion。', + 'detail.connected': '可以在对话中直接请 Agent 使用 Notion。', + 'detail.reconnect.expired': '授权已过期,请重新连接。', + 'detail.reconnect.binding': '授权与当前设置不再匹配,请重新连接。', + 'detail.reconnect.rejected': 'Notion 不再接受当前授权,请重新连接。', + 'detail.reconnect.scope': '当前授权缺少所需权限。重新连接时,请在 Notion 中确认权限。', + 'detail.unavailable': '已保留现有授权,可以稍后重试。', + hostBrowser: '授权需要在运行 DSH 的这台电脑上的浏览器中完成。', + failed: '授权未完成,请重试', + 'action.connect': '连接 Notion', + 'action.reconnect': '重新连接', + 'action.open': '打开授权页面', + 'action.cancel': '取消', + 'action.signOut': '退出登录', + 'action.retry': '重试', + 'badge.connected': '已连接', + 'badge.disconnected': '未连接', + 'badge.reconnect': '需要重新连接', + 'badge.unavailable': '暂时无法连接', + 'badge.connecting': '连接中', + 'signOut.title': '退出 Notion 登录?', + 'signOut.body': '将删除 DSH 保存的 Notion 授权,之后对话中无法使用 Notion。如需在 Notion 一侧撤销连接,请到 Notion 的设置中处理。', + 'activation.title': '连接 Notion 账号', + 'activation.body': 'Notion 插件已开启。连接你的 Notion 账号后,就可以在对话中使用它。', + 'activation.later': '稍后', + 'notice.connected': 'Notion 已连接', + 'notice.signed-out': '已退出 Notion 登录', + 'notice.action-failed': '操作未完成,请重试', + close: '关闭', +} + +/** Every key the Notion connection surfaces translate. */ +export type NotionKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + 'section.title': 'Notion account', + 'status.checking': 'Checking connection', + 'status.disconnected': 'Not connected', + 'status.waiting-browser': 'Waiting for you to confirm in the browser', + 'status.authorizing': 'Connecting', + 'status.connecting': 'Connecting', + 'status.connected': 'Connected', + 'status.reconnect': 'Reconnection needed', + 'status.unavailable': 'Cannot connect right now', + 'detail.disconnected': 'Connect your Notion account to search, read, and edit the pages and databases you authorize, right from a conversation.', + 'detail.waiting-browser': 'The Notion authorization page is open. Confirm in Notion, then come back here to see the result.', + 'detail.authorizing': 'Finishing authorization with Notion.', + 'detail.connecting': 'Connecting to Notion.', + 'detail.connected': 'Ask the agent to use Notion directly in a conversation.', + 'detail.reconnect.expired': 'The authorization has expired. Connect again.', + 'detail.reconnect.binding': 'The authorization no longer matches the current settings. Connect again.', + 'detail.reconnect.rejected': 'Notion no longer accepts the current authorization. Connect again.', + 'detail.reconnect.scope': 'The current authorization lacks required permissions. Confirm them in Notion when you connect again.', + 'detail.unavailable': 'The existing authorization is kept. Try again later.', + hostBrowser: 'Authorization must be completed in a browser on the computer running DSH.', + failed: 'Authorization was not completed. Try again.', + 'action.connect': 'Connect Notion', + 'action.reconnect': 'Connect again', + 'action.open': 'Open authorization page', + 'action.cancel': 'Cancel', + 'action.signOut': 'Sign out', + 'action.retry': 'Retry', + 'badge.connected': 'Connected', + 'badge.disconnected': 'Not connected', + 'badge.reconnect': 'Reconnect', + 'badge.unavailable': 'Unavailable', + 'badge.connecting': 'Connecting', + 'signOut.title': 'Sign out of Notion?', + 'signOut.body': 'This deletes the Notion authorization DSH saved, so conversations can no longer use Notion. To revoke the connection on Notion\'s side, use Notion\'s settings.', + 'activation.title': 'Connect your Notion account', + 'activation.body': 'The Notion plugin is on. Connect your Notion account to use it in conversations.', + 'activation.later': 'Later', + 'notice.connected': 'Notion connected', + 'notice.signed-out': 'Signed out of Notion', + 'notice.action-failed': 'The action did not finish. Try again.', + close: 'Close', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Notion connection section, tag, guidance, and notices on the Plugins page. */ + 'notion': NotionKey + } +} diff --git a/packages/connector/notion/src/css-modules.d.ts b/packages/connector/notion/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/connector/notion/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/connector/notion/src/index.ts b/packages/connector/notion/src/index.ts index 036336a28d..2fa272b064 100644 --- a/packages/connector/notion/src/index.ts +++ b/packages/connector/notion/src/index.ts @@ -21,6 +21,7 @@ export const inject = ['mcpServers', 'systemPrompt'] const SERVER_NAME = 'notion' const CREDENTIAL_KEY = 'mcp-client/notion' const GUIDANCE = 'Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP.' + + ' If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins.' /** Notion MCP endpoint and tool loading for the managed server entry. */ export interface Config { diff --git a/packages/connector/notion/tests/components.client.spec.tsx b/packages/connector/notion/tests/components.client.spec.tsx new file mode 100644 index 0000000000..88ede2bc31 --- /dev/null +++ b/packages/connector/notion/tests/components.client.spec.tsx @@ -0,0 +1,150 @@ +// @vitest-environment jsdom +/** The connection section, title tag, activation guidance, and notices render the Host entry the page mirrors. */ +import type { ComponentProps } from 'react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' +import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { PluginPackageRef, PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' +import { afterEach, expect, it, vi } from 'vitest' +import type { ConnectionSnapshot } from '../src/client/connection.ts' +import { zh } from '../src/client/locales.ts' +import { + NotionConnectionActivation, NotionConnectionBadge, NotionConnectionSection, NotionConnectionToast, +} from '../src/client/NotionConnection.tsx' + +afterEach(cleanup) + +const MISSING: McpManagedServerStatus = { state: 'waiting-authorization', reason: 'missing', lastError: 'x' } +const CONNECTED: McpManagedServerStatus = { state: 'connected', toolCount: 1, connectedAt: 1 } + +function server(status: McpManagedServerStatus, phase?: McpOAuthAttemptView['phase'], authorizationUrl?: string): McpManagedServerView { + return { + name: 'notion', configured: true, status, + ...phase === undefined ? {} : { authorization: { id: 'a' as McpOAuthAttemptId, phase, ...authorizationUrl === undefined ? {} : { authorizationUrl } } }, + } +} + +function fixture(initial: Partial = {}) { + const state = createSnapshotStore({ server: undefined, linked: true, busy: false, notice: undefined, ...initial }) + const face = { + useNotionConnection: bindSnapshotSelector(state), + connect: vi.fn(), cancel: vi.fn(), signOut: vi.fn(), retry: vi.fn(), openAuthorization: vi.fn(), dismissNotice: vi.fn(), + t: makeTranslate(zh), + } + return { state, face, set: (change: Partial) => { act(() => { state.set({ ...state.getSnapshot(), ...change }) }) } } +} + +const button = (name: string) => screen.getByRole('button', { name }) + +it('offers the next step for each connection state', () => { + const b = fixture({ server: server(MISSING) }) + render() + expect(screen.getByText(zh['status.disconnected'])).toBeTruthy() + expect(screen.getByText(zh.hostBrowser)).toBeTruthy() + fireEvent.click(button(zh['action.connect'])) + expect(b.face.connect).toHaveBeenCalledOnce() + + b.set({ server: server(MISSING, 'waiting-browser', 'https://notion.test') }) + expect(screen.getByText(zh['detail.waiting-browser'])).toBeTruthy() + fireEvent.click(button(zh['action.open'])) + fireEvent.click(button(zh['action.cancel'])) + expect(b.face.openAuthorization).toHaveBeenCalledOnce() + expect(b.face.cancel).toHaveBeenCalledOnce() + + b.set({ server: server(MISSING, 'exchanging') }) + expect(screen.queryByRole('button', { name: zh['action.open'] })).toBeNull() + fireEvent.click(button(zh['action.cancel'])) + expect(b.face.cancel).toHaveBeenCalledTimes(2) + + b.set({ server: server(MISSING, 'failed') }) + expect(screen.getByRole('alert').textContent).toBe(zh.failed) + + b.set({ server: server({ state: 'waiting-authorization', reason: 'scope', lastError: 'x' }) }) + expect(screen.getByText(zh['detail.reconnect.scope'])).toBeTruthy() + fireEvent.click(button(zh['action.reconnect'])) + expect(b.face.connect).toHaveBeenCalledTimes(2) + + b.set({ server: server({ state: 'failed', reason: 'gave-up' }) }) + fireEvent.click(button(zh['action.retry'])) + expect(b.face.retry).toHaveBeenCalledOnce() + + b.set({ server: server({ state: 'connecting', attempt: 0 }) }) + expect(screen.queryAllByRole('button')).toHaveLength(0) + + b.set({ server: undefined }) + expect(screen.getByText(zh['status.checking'])).toBeTruthy() + expect(document.querySelector('[data-notion-connection="checking"] p')?.textContent).toBe(zh.hostBrowser) +}) + +it('disables actions while one is pending or the Host stream is offline', () => { + const b = fixture({ server: server(MISSING), busy: true }) + render() + expect(button(zh['action.connect']).hasAttribute('disabled')).toBe(true) + b.set({ busy: false, linked: false }) + expect(button(zh['action.connect']).hasAttribute('disabled')).toBe(true) + b.set({ linked: true }) + expect(button(zh['action.connect']).hasAttribute('disabled')).toBe(false) +}) + +it('signs out only after confirmation', () => { + const b = fixture({ server: server(CONNECTED) }) + render() + expect(screen.getByText(zh['detail.connected'])).toBeTruthy() + fireEvent.click(button(zh['action.signOut'])) + expect(screen.getByText(zh['signOut.body'])).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(b.face.signOut).not.toHaveBeenCalled() + fireEvent.click(button(zh['action.signOut'])) + fireEvent.click(button(zh.close)) + expect(screen.queryByText(zh['signOut.body'])).toBeNull() + fireEvent.click(button(zh['action.signOut'])) + fireEvent.click(screen.getAllByRole('button', { name: zh['action.signOut'] }).at(-1)!) + expect(b.face.signOut).toHaveBeenCalledOnce() +}) + +it('tags only the enabled Notion bundle', () => { + const b = fixture({ server: server(CONNECTED) }) + const pkg = (name: string, enabled = true): PluginPackageRef => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] }) + const badge = (subject: PluginsSubject) => + } /> + const { rerender } = render(badge({ kind: 'bundle', pkg: pkg('@deepseek-ai/dsh-notion') })) + expect(screen.getByText(zh['badge.connected'])).toBeTruthy() + b.set({ server: server(MISSING, 'waiting-browser') }) + expect(screen.getByText(zh['badge.connecting'])).toBeTruthy() + b.set({ server: undefined }) + expect(document.body.textContent).toBe('') + b.set({ server: server(MISSING) }) + rerender(badge({ kind: 'bundle', pkg: pkg('@deepseek-ai/dsh-notion', false) })) + expect(document.body.textContent).toBe('') + rerender(badge({ kind: 'bundle', pkg: pkg('@acme/other') })) + expect(document.body.textContent).toBe('') + rerender(badge({ kind: 'item', id: 'shell' })) + expect(document.body.textContent).toBe('') +}) + +it('guides a newly enabled bundle to connect, and steps aside once connected', () => { + const b = fixture() + const onDismiss = vi.fn(), onOpenDetails = vi.fn() + const props = { ...b.face, packageName: '@deepseek-ai/dsh-notion', onDismiss, onOpenDetails } as ComponentProps + render() + expect(screen.queryByText(zh['activation.body'])).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + b.set({ server: server(MISSING) }) + fireEvent.click(button(zh['action.connect'])) + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(b.face.connect).toHaveBeenCalledOnce() + b.set({ server: server(CONNECTED) }) + expect(onDismiss).toHaveBeenCalledOnce() +}) + +it('reports the latest notice and leaves dismissal to the toast', () => { + const b = fixture() + render() + expect(document.body.textContent).toBe('') + b.set({ notice: { seq: 1, kind: 'connected' } }) + expect(screen.getByText(zh['notice.connected'])).toBeTruthy() + b.set({ notice: { seq: 2, kind: 'action-failed' } }) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) diff --git a/packages/connector/notion/tests/connection.client.spec.ts b/packages/connector/notion/tests/connection.client.spec.ts new file mode 100644 index 0000000000..cad8cf7e4c --- /dev/null +++ b/packages/connector/notion/tests/connection.client.spec.ts @@ -0,0 +1,208 @@ +// @vitest-environment jsdom +/** The page derives Notion's connection from the manager's entry and drives authorization through its Remote. */ +import { Context } from '@deepseek-ai/cordis' +import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' +import type { McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { NotionConnection, presentConnection } from '../src/client/connection.ts' + +const ATTEMPT = 'attempt-1' as McpOAuthAttemptId + +function attempt(phase: McpOAuthAttemptView['phase'], authorizationUrl?: string, id = ATTEMPT): McpOAuthAttemptView { + return { id, phase, ...authorizationUrl === undefined ? {} : { authorizationUrl } } +} + +function server(status: McpManagedServerStatus, authorization?: McpOAuthAttemptView): McpManagedServerView { + return { name: 'notion', configured: true, status, ...authorization === undefined ? {} : { authorization } } +} + +const MISSING: McpManagedServerStatus = { state: 'waiting-authorization', reason: 'missing', lastError: 'no grant' } +const CONNECTED: McpManagedServerStatus = { state: 'connected', toolCount: 2, connectedAt: 1 } + +it.each<[string, McpManagedServerView | undefined, ReturnType]>([ + ['no entry yet', undefined, { phase: 'checking' }], + ['a missing grant', server(MISSING), { phase: 'disconnected', failed: false }], + ['a failed attempt over a missing grant', server(MISSING, attempt('failed')), { phase: 'disconnected', failed: true }], + ['an expired grant', server({ state: 'waiting-authorization', reason: 'expired', lastError: 'x' }), { phase: 'reconnect', reason: 'expired', failed: false }], + ['missing permissions', server({ state: 'waiting-authorization', reason: 'scope', lastError: 'x' }), { phase: 'reconnect', reason: 'scope', failed: false }], + ['a starting attempt', server(MISSING, attempt('starting')), { phase: 'authorizing', attempt: ATTEMPT }], + ['an exchanging attempt', server(MISSING, attempt('exchanging')), { phase: 'authorizing', attempt: ATTEMPT }], + ['a committing attempt', server(MISSING, attempt('committing')), { phase: 'authorizing', attempt: ATTEMPT }], + ['a browser step', server(MISSING, attempt('waiting-browser', 'https://notion.test/auth')), + { phase: 'waiting-browser', attempt: ATTEMPT, url: 'https://notion.test/auth' }], + ['a connection', server(CONNECTED, attempt('authorized')), { phase: 'connected' }], + ['a cancelled attempt', server(MISSING, attempt('cancelled')), { phase: 'disconnected', failed: false }], + ['a first connection', server({ state: 'connecting', attempt: 0 }), { phase: 'connecting' }], + ['a reconnect backoff', server({ state: 'reconnecting', attempt: 1, maxAttempts: 3, nextRetryAtMs: 2, lastError: 'x' }), { phase: 'connecting' }], + ['a closed instance', server({ state: 'closed', result: { closeConfirmed: true } }), { phase: 'unavailable', failed: false }], + ['missing static credentials', server({ state: 'waiting-credentials', lastError: 'x' }), { phase: 'unavailable', failed: false }], + ['a disabled entry', server({ state: 'disabled' }), { phase: 'unavailable', failed: false }], + ['a stopped supervisor', server({ state: 'failed', reason: 'gave-up' }), { phase: 'unavailable', failed: false }], + ['a load failure', server({ state: 'failed', reason: 'load', lastError: 'x' }), { phase: 'unavailable', failed: false }], +])('presents %s', (_name, entry, expected) => { + expect(presentConnection(entry)).toEqual(expected) +}) + +function fixture() { + const queue: McpManagedServerView[][] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const stream = { + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + if (closed) return + const next = queue.shift() + if (next === undefined) { await new Promise((resolve) => { wake = resolve }); continue } + yield { value: next, accept: () => { accepted++ } } + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + } + const ok = (value: T) => ({ ok: true as const, value }) + const remote = { + watch: vi.fn(), + startAuthorization: vi.fn(async () => ok(attempt('starting'))), + cancelAuthorization: vi.fn(async () => ok(undefined)), + signOut: vi.fn(async () => ok(undefined)), + restart: vi.fn(async () => ok(undefined)), + } + const ctx = new Context() + ctx.provide('remote', { mcpServers: remote, $stream: (value: typeof options) => { options = value; return stream } }) + const open = vi.spyOn(window, 'open').mockReturnValue(null) + const connection = new NotionConnection(ctx) + onTestFinished(async () => { await connection.dispose(); open.mockRestore(); await ctx.fiber.dispose() }) + const face = connection.face() + const snapshot = () => connection.state.getSnapshot() + return { + connection, face, remote, open, stream, snapshot, options: () => options, + async publish(...servers: McpManagedServerView[]) { + const target = accepted + 1 + queue.push([{ name: 'other', configured: true, status: CONNECTED }, ...servers]) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + failOnClose(error: Error) { failure = error }, + } +} + +it('mirrors only the Notion entry and opens the manager stream', async () => { + const b = fixture() + const signal = new AbortController().signal + b.options().open(signal) + expect(b.remote.watch).toHaveBeenCalledWith(signal) + expect(b.options().ended(true)).toBeInstanceOf(Error) + await b.publish() + expect(b.snapshot()).toMatchObject({ server: undefined, linked: true, busy: false }) + b.options().carrierFailed?.(new Error('lost')) + expect(b.snapshot().linked).toBe(false) + await b.publish(server(MISSING)) + expect(b.snapshot().linked).toBe(true) +}) + +it('opens the authorization page once for the attempt this browser started, then reports the connection', async () => { + const b = fixture() + await b.publish(server(MISSING)) + b.face.connect() + await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) + expect(b.remote.startAuthorization).toHaveBeenCalledWith('notion') + const waiting = server(MISSING, attempt('waiting-browser', 'https://notion.test/auth')) + await b.publish(waiting) + await b.publish(server(MISSING, attempt('waiting-browser', 'https://notion.test/auth'))) + expect(b.open).toHaveBeenCalledOnce() + expect(b.open).toHaveBeenCalledWith('https://notion.test/auth', '_blank', 'noopener,noreferrer') + b.face.openAuthorization() + expect(b.open).toHaveBeenCalledTimes(2) + await b.publish(server(CONNECTED, attempt('authorized'))) + expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'connected' }) + await b.publish(server(CONNECTED, attempt('authorized'))) + expect(b.snapshot().notice?.seq).toBe(1) + b.face.dismissNotice() + expect(b.snapshot().notice).toBeUndefined() +}) + +it('opens a page the stream reported before the start call answered, and never another browser\'s attempt', async () => { + const b = fixture() + const answer = Promise.withResolvers<{ ok: true; value: McpOAuthAttemptView }>() + b.remote.startAuthorization.mockReturnValueOnce(answer.promise) + await b.publish(server(MISSING, attempt('waiting-browser', 'https://notion.test/other', 'other' as McpOAuthAttemptId))) + expect(b.open).not.toHaveBeenCalled() + b.face.connect() + await b.publish(server(MISSING, attempt('waiting-browser', 'http://127.0.0.1:3080/authorize'))) + expect(b.open).not.toHaveBeenCalled() + answer.resolve({ ok: true, value: attempt('starting') }) + await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('http://127.0.0.1:3080/authorize', '_blank', 'noopener,noreferrer') }) +}) + +it.each(['http://notion.test/auth', 'javascript:alert(1)', 'not a url'])('refuses to open %s', async (url) => { + const b = fixture() + b.face.connect() + await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) + await b.publish(server(MISSING, attempt('waiting-browser', url))) + b.face.openAuthorization() + expect(b.open).not.toHaveBeenCalled() +}) + +it('cancels only an active attempt and forgets an attempt that ended', async () => { + const b = fixture() + await b.publish(server(MISSING)) + b.face.cancel() + b.face.openAuthorization() + expect(b.remote.cancelAuthorization).not.toHaveBeenCalled() + expect(b.open).not.toHaveBeenCalled() + b.face.connect() + await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) + await b.publish(server(MISSING, attempt('starting'))) + b.face.cancel() + await vi.waitFor(() => { expect(b.remote.cancelAuthorization).toHaveBeenCalledWith('notion', ATTEMPT) }) + await b.publish(server(MISSING, attempt('cancelled'))) + await b.publish(server(MISSING, attempt('waiting-browser', 'https://notion.test/late'))) + expect(b.open).not.toHaveBeenCalled() + expect(b.snapshot().notice).toBeUndefined() +}) + +it('signs out and retries through the manager, reporting a failed action once and ignoring overlapping clicks', async () => { + const b = fixture() + await b.publish(server(CONNECTED)) + b.face.signOut() + b.face.retry() + await vi.waitFor(() => { expect(b.snapshot().notice?.kind).toBe('signed-out') }) + expect(b.remote.signOut).toHaveBeenCalledWith('notion') + expect(b.remote.restart).not.toHaveBeenCalled() + b.remote.restart.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + b.face.retry() + await vi.waitFor(() => { expect(b.snapshot().notice?.kind).toBe('action-failed') }) + expect(b.remote.restart).toHaveBeenCalledWith('notion') + expect(b.snapshot().busy).toBe(false) +}) + +it('stops observing on disposal without reporting the closed stream', async () => { + const b = fixture() + await b.publish(server(MISSING)) + await b.connection.dispose() + expect(b.stream.dispose).toHaveBeenCalled() + expect(b.snapshot().linked).toBe(true) +}) + +it('reports nothing for a stream failure or an action that settles after disposal', async () => { + const b = fixture() + await b.publish(server(CONNECTED)) + const answer = Promise.withResolvers<{ ok: true; value: undefined }>() + b.remote.signOut.mockReturnValueOnce(answer.promise) + b.face.signOut() + b.failOnClose(new Error('closed')) + await b.connection.dispose() + answer.resolve({ ok: true, value: undefined }) + await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) + expect(b.snapshot()).toMatchObject({ linked: true, notice: undefined }) +}) + +it('marks the page offline when the stream fails', async () => { + const b = fixture() + await b.publish(server(MISSING)) + b.fail(new Error('invalid frame')) + await vi.waitFor(() => { expect(b.snapshot().linked).toBe(false) }) +}) diff --git a/packages/connector/notion/tests/mount.client.spec.ts b/packages/connector/notion/tests/mount.client.spec.ts new file mode 100644 index 0000000000..2168c7db8e --- /dev/null +++ b/packages/connector/notion/tests/mount.client.spec.ts @@ -0,0 +1,48 @@ +/** The browser half registers its four surfaces while the Notion row is on and withdraws them with it. */ +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { expect, it, vi } from 'vitest' +import { apply, inject } from '../src/client/index.ts' +import { NotionConnectionActivation, NotionConnectionBadge, NotionConnectionSection, NotionConnectionToast } from '../src/client/NotionConnection.tsx' + +it('registers the connection surfaces with one shared face and removes them on disposal', async () => { + const ctx = new Context() + const dispose = vi.fn(async () => {}) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { async *[Symbol.asyncIterator]() { /* the manager reports nothing in this composition */ }, dispose } + } + } + new Remote() + ctx.provide('remote.mcpServers', { watch: vi.fn() }) + ctx.provide('locale', new LocaleRuntime(ctx)) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + try { + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber + const slots = [ + ['plugins.bundle.config', NotionConnectionSection], + ['plugins.bundle.activation', NotionConnectionActivation], + ['plugins.detail.badge', NotionConnectionBadge], + ['shell.overlay', NotionConnectionToast], + ] as const + const faces = slots.map(([slot, component]) => { + const [entry] = ctx.slots.entries(slot) + expect(entry).toMatchObject({ locale: 'notion', component }) + return entry!.inject!() + }) + expect(new Set(faces.map(face => face.hooks)).size).toBe(1) + expect(ctx.slots.entries('plugins.bundle.config')[0]!.options.key).toBe('@deepseek-ai/dsh-notion') + await fiber.dispose() + for (const [slot] of slots) expect(ctx.slots.entries(slot)).toHaveLength(0) + expect(dispose).toHaveBeenCalledOnce() + } finally { await ctx.fiber.dispose() } +}) diff --git a/packages/connector/notion/tests/plugin.spec.ts b/packages/connector/notion/tests/plugin.spec.ts index a3f272644b..f3d6736713 100644 --- a/packages/connector/notion/tests/plugin.spec.ts +++ b/packages/connector/notion/tests/plugin.spec.ts @@ -14,6 +14,7 @@ import { managerProfile } from '../../../mcp/mcp-manager/tests/profile-fixture.t import * as Notion from '../src/index.ts' const GUIDANCE = 'Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP.' + + ' If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins.' async function fixture(servers: Record = {}) { const world = await oauthWorld() diff --git a/packages/connector/notion/tsconfig.client.json b/packages/connector/notion/tsconfig.client.json new file mode 100644 index 0000000000..0662722bba --- /dev/null +++ b/packages/connector/notion/tsconfig.client.json @@ -0,0 +1,53 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../client/locale/tsconfig.client.json" + }, + { + "path": "../../client/store" + }, + { + "path": "../../client/ui-layout" + }, + { + "path": "../../client/ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../../client/ui-primitives" + }, + { + "path": "../../client/ui-renderer" + }, + { + "path": "../../client/ui-slots" + }, + { + "path": "../../mcp/mcp-client" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/connector/notion/tsconfig.host.json b/packages/connector/notion/tsconfig.host.json new file mode 100644 index 0000000000..2add6b53a9 --- /dev/null +++ b/packages/connector/notion/tsconfig.host.json @@ -0,0 +1,25 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../mcp/mcp-manager" + }, + { + "path": "../../core/system-prompt" + } + ] +} diff --git a/packages/connector/notion/tsconfig.json b/packages/connector/notion/tsconfig.json index 7f9fcbbf57..2eca820546 100644 --- a/packages/connector/notion/tsconfig.json +++ b/packages/connector/notion/tsconfig.json @@ -1,24 +1,11 @@ { - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ { - "path": "../../../vendor/cordis" + "path": "./tsconfig.host.json" }, { - "path": "../../../vendor/schemastery" - }, - { - "path": "../../mcp/mcp-manager" - }, - { - "path": "../../core/system-prompt" + "path": "./tsconfig.client.json" } ] } diff --git a/packages/connector/notion/tsdown.config.ts b/packages/connector/notion/tsdown.config.ts new file mode 100644 index 0000000000..d008cf9ebc --- /dev/null +++ b/packages/connector/notion/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../../client/tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-notion', ['lib/types/index.js'], { hostPhase: true }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a8f05e443..1c0d191ca1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7419,12 +7419,45 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../../client/locale + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../../client/store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-layout': + specifier: workspace:* + version: link:../../client/ui-layout + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:* + version: link:../../client/ui-plugin-manager + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../../client/ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../../client/ui-renderer + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../../client/ui-slots '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../../credentials/credentials '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm + '@deepseek-ai/dsh-mcp-client': + specifier: workspace:* + version: link:../../mcp/mcp-client '@deepseek-ai/dsh-mcp-manager': specifier: workspace:* version: link:../../mcp/mcp-manager @@ -7437,6 +7470,24 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:* version: link:../../core/system-prompt + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) packages/context/agent-instructions: dependencies: diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 21ad78761d..06b902472d 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -18,6 +18,7 @@ const HOST_DEPENDENCY_PACKAGES: readonly string[] = [ /** Required Cordis services whose Host imports are type-only. */ const REQUIRED_SERVICE_PEERS = { '@deepseek-ai/dsh-api-terminal-controller': ['@deepseek-ai/dsh-subprocess'], + '@deepseek-ai/dsh-notion': ['@deepseek-ai/dsh-mcp-manager', '@deepseek-ai/dsh-system-prompt'], } as const satisfies Readonly> /** Development-only package relationships not represented by source imports. */ diff --git a/scripts/verify-package-dependencies.spec.ts b/scripts/verify-package-dependencies.spec.ts index 195b71c6fd..c1e3859a1d 100644 --- a/scripts/verify-package-dependencies.spec.ts +++ b/scripts/verify-package-dependencies.spec.ts @@ -216,6 +216,7 @@ describe('package dependency scope', () => { ]) expect(PACKAGE_DEPENDENCY_POLICY.requiredServicePeers).toEqual({ '@deepseek-ai/dsh-api-terminal-controller': ['@deepseek-ai/dsh-subprocess'], + '@deepseek-ai/dsh-notion': ['@deepseek-ai/dsh-mcp-manager', '@deepseek-ai/dsh-system-prompt'], }) expect(PACKAGE_DEPENDENCY_POLICY.configurationOnlyDevDependencies).toEqual({ '@deepseek-ai/dsh-client-locale': ['@deepseek-ai/dsh-api-remotes'], diff --git a/tsconfig.client.json b/tsconfig.client.json index 559ca5368b..46797fcf69 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -36,7 +36,8 @@ "packages/*/*/tests/**/*.client.spec.tsx", "packages/*/*/tests/**/*.client.tsx", "packages/*/*/tests/**/*.client.ts", - // Client package outside packages/client with a local CSS module face. + // Client packages outside packages/client with a local CSS module face. + "packages/connector/notion/src/css-modules.d.ts", "packages/extensions/ui-cordis/src/css-modules.d.ts", "packages/client/tsdown.client.ts", "scripts/client-build-environment.ts", @@ -163,6 +164,7 @@ { "path": "./packages/client/ui-settings-models" }, { "path": "./packages/client/ui-plugin-manager/tsconfig.client.json" }, { "path": "./packages/client/ui-plugin-market" }, + { "path": "./packages/connector/notion/tsconfig.client.json" }, { "path": "./packages/client/ui-settings-plugin-inventory" }, { "path": "./packages/client/locale/tsconfig.client.json" }, { "path": "./packages/client/ui-renderer" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index f62696df44..4578c64d43 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -571,7 +571,7 @@ { "path": "./packages/mcp/mcp-client" }, { "path": "./packages/mcp/mcp-manager" }, { "path": "./packages/mcp/mcp-resources" }, - { "path": "./packages/connector/notion" }, + { "path": "./packages/connector/notion/tsconfig.host.json" }, { "path": "./packages/host/directory-picker" }, { "path": "./packages/host/directory-picker-auto" }, { "path": "./packages/host/directory-picker-browse" },