Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(telegram): make /new create a fresh task (#3915)

Chris Zhang54989d9c3220
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
index 1cd99229f0..d6fb0b8249 100644
--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
@@ -207,6 +207,7 @@ function makeDispatcher(overrides?: {
buildContextPrefix?: HookDispatcherDeps['buildContextPrefix'];
dialogue?: HookDispatcherDeps['dialogue'];
abortSession?: HookDispatcherDeps['abortSession'];
+ archiveSessionRow?: HookDispatcherDeps['archiveSessionRow'];
subscribeUiContinuation?: HookDispatcherDeps['subscribeUiContinuation'];
subscribeUiSessionIntervention?: HookDispatcherDeps['subscribeUiSessionIntervention'];
subscribeUiTurnDispatching?: HookDispatcherDeps['subscribeUiTurnDispatching'];
@@ -228,6 +229,7 @@ function makeDispatcher(overrides?: {
buildContextPrefix: overrides?.buildContextPrefix,
dialogue: overrides?.dialogue,
abortSession: overrides?.abortSession,
+ archiveSessionRow: overrides?.archiveSessionRow,
subscribeUiContinuation: overrides?.subscribeUiContinuation,
subscribeUiSessionIntervention: overrides?.subscribeUiSessionIntervention,
subscribeUiTurnDispatching: overrides?.subscribeUiTurnDispatching,
@@ -3235,6 +3237,51 @@ describe('options 透传(model/effort/agentKind/permissionMode)', () => {
});
describe('session.archive(/new 换代归档旧代会话)', () => {
+ it('creates and binds a blank new task before archiving the previous generation', async () => {
+ const previousId = 'old-session';
+ const previousKey = 'telegram:dm:bot:user:g1';
+ const nextKey = 'telegram:dm:bot:user:g2';
+ const bindings = memoryBindings();
+ bindings.set('conn-1', previousKey, previousId);
+ const calls: HookRunRequest[] = [];
+ const runner: HookSessionRunner = {
+ isBusy: () => false,
+ inspect: async (id) => (id === previousId ? { workingDir: WS_DIR, usable: true } : null),
+ run: async (req) => {
+ calls.push(req);
+ return { status: 'ok', finalText: '', errorMessage: null, durationMs: 1 };
+ },
+ };
+ const archived: string[] = [];
+ const { d } = makeDispatcher({
+ bindings,
+ runner,
+ archiveSessionRow: async (id) => void archived.push(id),
+ });
+
+ const result = await d.createSession('conn-1', {
+ previousExternalKey: previousKey,
+ externalKey: nextKey,
+ workspace: 'xdmaker',
+ options: { agentKind: 'pi', model: 'grok-4.6', permissionMode: 'bypassPermissions' },
+ source: { im: 'telegram', userText: '' },
+ });
+
+ expect(result.sessionId).not.toBe(previousId);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ sessionId: result.sessionId,
+ isNew: true,
+ createOnly: true,
+ agentKind: 'pi',
+ model: 'grok-4.6',
+ permissionMode: 'bypassPermissions',
+ });
+ expect(bindings.get('conn-1', nextKey)).toBe(result.sessionId);
+ expect(bindings.get('conn-1', previousKey)).toBeNull();
+ expect(archived).toEqual([previousId]);
+ });
+
it('安全接管旧 Slack 命名空间映射;跨白名单映射只清理不归档', async () => {
const safeSession = 'legacy-safe';
const unsafeSession = 'legacy-unsafe';
diff --git a/apps/desktop/src/main/hook-control/__tests__/queryResponder.test.ts b/apps/desktop/src/main/hook-control/__tests__/queryResponder.test.ts
index c954324a54..caf5f74553 100644
--- a/apps/desktop/src/main/hook-control/__tests__/queryResponder.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/queryResponder.test.ts
@@ -5,15 +5,13 @@
* 纯函数注入(规则 14), 无 Electron / maker。
*/
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { buildQueryResponse, type QueryResponderDeps } from '../queryResponder';
const DEPS: QueryResponderDeps = {
listWorkspaces: () => ['xdmaker', 'blog'],
- listSessions: () => [
- { id: 's1', title: 'Fix login', workspace: 'xdmaker', lastActiveAt: 10 },
- ],
+ listSessions: () => [{ id: 's1', title: 'Fix login', workspace: 'xdmaker', lastActiveAt: 10 }],
listAgentModels: () => [
{
agentKind: 'claude-code',
@@ -62,7 +60,13 @@ describe('buildQueryResponse', () => {
expect(res.agents?.[0]).toEqual({
agentKind: 'claude-code',
models: [
- { id: 'claude-opus-4-8', label: 'Opus 4.8', efforts: ['low', 'high'], defaultEffort: 'high', group: 'anthropic' },
+ {
+ id: 'claude-opus-4-8',
+ label: 'Opus 4.8',
+ efforts: ['low', 'high'],
+ defaultEffort: 'high',
+ group: 'anthropic',
+ },
],
permissionModes: [
{ id: 'ask', label: 'Ask permissions' },
@@ -98,6 +102,29 @@ describe('buildQueryResponse', () => {
expect(JSON.stringify(res)).not.toContain('workingDir');
});
+ it('session-new: waits for the task to exist and returns its id', async () => {
+ const createSession = vi.fn(async () => ({ sessionId: 'new-task-id' }));
+ const sessionNew = {
+ previousExternalKey: 'telegram:dm:1:g1',
+ externalKey: 'telegram:dm:1:g2',
+ workspace: 'xdmaker',
+ options: { agentKind: 'pi', model: 'grok-4.6', permissionMode: 'bypassPermissions' },
+ source: { im: 'telegram', userText: '' },
+ };
+ const res = await buildQueryResponse(
+ { ...DEPS, createSession },
+ { queryId: 'q-new', kind: 'session-new', sessionNew },
+ );
+ expect(createSession).toHaveBeenCalledWith(sessionNew);
+ expect(res).toEqual({
+ queryId: 'q-new',
+ kind: 'session-new',
+ ok: true,
+ error: null,
+ sessionId: 'new-task-id',
+ });
+ });
+
it('数据源抛错: ok=false + 原因, 不炸调用方', async () => {
const res = await buildQueryResponse(
{
@@ -113,7 +140,7 @@ describe('buildQueryResponse', () => {
it('异步数据源: Promise 解析后照常构造, reject 时 ok=false', async () => {
const ok = await buildQueryResponse(
- { ...DEPS, listAgentModels: async () => (await Promise.resolve(DEPS.listAgentModels())) },
+ { ...DEPS, listAgentModels: async () => await Promise.resolve(DEPS.listAgentModels()) },
{ queryId: 'q4', kind: 'models' },
);
expect(ok.ok).toBe(true);
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index bdecba4290..fc82da3b07 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -57,6 +57,7 @@ const h = vi.hoisted(() => {
}),
setSessionProvider: vi.fn(),
hydrateSessionProvider: vi.fn(),
+ createSessionRow: vi.fn(async () => undefined),
peekPendingHandoff: vi.fn(async () => null as string | null),
consumePendingHandoff: vi.fn(),
listProviders: vi.fn(async (): Promise<unknown[]> => []),
@@ -143,6 +144,9 @@ vi.mock('../../maker-host/session-provider-store.js', () => ({
setSessionProvider: h.setSessionProvider,
hydrateSessionProvider: h.hydrateSessionProvider,
}));
+vi.mock('../../maker-host/session-storage.js', () => ({
+ desktopSessionStorage: { create: h.createSessionRow },
+}));
vi.mock('../../maker-ipc/agentHandoffPendingSingleton.js', () => ({
agentHandoffPending: {
peek: h.peekPendingHandoff,
@@ -495,6 +499,35 @@ describe('真正要跑的那个 live session 的目录也要过映射', () => {
});
describe('hook session-runner 的 userSendAt 时序(未分类误判回归)', () => {
+ it('createOnly materializes and broadcasts a task without a synthetic user turn', async () => {
+ const runner = createMakerHookSessionRunner({ log });
+
+ const outcome = await runner.run(baseReq({ createOnly: true }));
+
+ expect(outcome).toMatchObject({ status: 'ok', finalText: '' });
+ expect(fakeMaker.createSession).not.toHaveBeenCalled();
+ expect(h.createSessionRow).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'sess-new', model: 'test-model' }),
+ );
+ expect(h.createMessage).not.toHaveBeenCalled();
+ expect(h.calls).toEqual(expect.arrayContaining(['touch:sess-new', 'created:sess-new']));
+ expect(h.touchUserSendInDb).toHaveBeenCalledTimes(1);
+ });
+
+ it('createOnly keeps the durable task when userSendAt enrichment fails', async () => {
+ h.touchUserSendInDb.mockRejectedValueOnce(new Error('db busy'));
+ const runner = createMakerHookSessionRunner({ log });
+
+ const outcome = await runner.run(baseReq({ createOnly: true }));
+
+ expect(outcome.status).toBe('ok');
+ expect(h.createSessionRow).toHaveBeenCalledTimes(1);
+ expect(h.calls).toContain('created:sess-new');
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining('create-only touchUserSend failed'),
+ );
+ });
+
it('isNew: touchUserSendInDb 在 sessions:created 广播之前落库, onAccepted 再 bump 一次', async () => {
const runner = createMakerHookSessionRunner({ log });
const outcome = await runner.run(baseReq({}));
diff --git a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts
index c8a2aa1af7..60aa4a67b4 100644
--- a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts
@@ -23,6 +23,7 @@ import {
HOOK_FEATURE_PROVIDER_TELEGRAM,
HOOK_FEATURE_PROVIDER_X,
HOOK_FEATURE_SESSION_PICKER,
+ HOOK_FEATURE_SESSION_NEW,
HOOK_FEATURE_SLACK_TOOLS,
HOOK_FEATURE_TURN_DELIVERY,
makeBindState,
@@ -183,6 +184,7 @@ describe('hook-control runtime capability gate', () => {
const handleTurnDelivery = vi.fn();
const dispatcher = {
handleDispatch: vi.fn(),
+ createSession: vi.fn(),
onConnected: vi.fn(),
onDisconnected: vi.fn(),
cancel: vi.fn(),
@@ -1510,6 +1512,7 @@ const TELEGRAM_FEATURES = [
HOOK_FEATURE_PROVIDER_PREFS,
HOOK_FEATURE_PROVIDER_TELEGRAM,
HOOK_FEATURE_SESSION_PICKER,
+ HOOK_FEATURE_SESSION_NEW,
];
const TELEGRAM_PENDING: ProviderBindStatusPayload = {
@@ -1582,6 +1585,7 @@ describe('Telegram provider capability, binding and prefs', () => {
const handleDispatch = vi.fn();
const dispatcher = {
handleDispatch,
+ createSession: vi.fn(),
onConnected: vi.fn(),
onDisconnected: vi.fn(),
onMessageOpResult: vi.fn(),
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index 1e4548a80a..d934946f98 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -56,6 +56,7 @@ import {
type TaskDispatchPayload,
type TaskRejectReason,
type TaskSource,
+ type QueryRequestPayload,
type TurnDeliveryPayload,
type TurnEndPayload,
} from '@cindy/slack-hook-protocol';
@@ -153,6 +154,8 @@ export interface HookRunRequest {
laneKind?: 'dm' | 'group';
/** true = 新建 session(workingDir/title 生效); false = 复用/接管已有。 */
isNew: boolean;
+ /** Create and expose the task without sending an Agent turn (`/new`). */
+ createOnly?: boolean;
/**
* 新建任务替换了哪条不可投递的旧任务。runner 用它从旧任务仍可读取的
* 本地消息构造一次性 Agent 交接;省略 = 普通新建,不补旧任务上下文。
@@ -390,6 +393,11 @@ export interface HookDispatcher {
* 走同一条串行链, 不与在途的会话定位竞争。
*/
handleSessionArchive(connectionId: string, externalKey: string): void;
+ /** Create the next provider task immediately and return only after it exists. */
+ createSession(
+ connectionId: string,
+ request: NonNullable<QueryRequestPayload['sessionNew']>,
+ ): Promise<{ sessionId: string }>;
/**
* interaction.decision: 交互卡按钮回流。归属校验(requestId 必须是本连接
* 正在执行的任务)后按 interactionId 配对 resolve; 未知 / 迟到的静默忽略。
@@ -691,7 +699,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
* 段的两帧在同一 tick 送达, 生产可达)。链式 promise 保证同 key 严格按序。
*/
const keyChains = new Map<string, Promise<void>>();
- function serializeByKey(key: string, fn: () => Promise<void>): void {
+ function serializeByKey(key: string, fn: () => Promise<void>): Promise<void> {
const prev = keyChains.get(key) ?? Promise.resolve();
const next = prev.then(fn, fn);
const stored = next.catch(() => undefined);
@@ -699,6 +707,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
void stored.finally(() => {
if (keyChains.get(key) === stored) keyChains.delete(key);
});
+ return next;
}
/** 同一 session 的受理段串行化,避免不同 externalKey 并发判断空闲并同时占槽。 */
const sessionAdmissionChains = new Map<string, Promise<void>>();
@@ -2567,6 +2576,85 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
}
});
},
+ async createSession(connectionId, request) {
+ if (!accountActive) throw new Error('hook account is disabled');
+ if (request.externalKey === request.previousExternalKey) {
+ throw new Error('new task external key must advance');
+ }
+ const admittedGeneration = accountGeneration;
+ const config = getConnection(connectionId);
+ if (!config?.enabled) throw new Error('hook connection is disabled');
+ const source = request.source === undefined ? undefined : normalizeTaskSource(request.source);
+ let createdSessionId: string | null = null;
+ const createAndRetire = async (): Promise<void> => {
+ await serializeByKey(`${connectionId} ${request.previousExternalKey}`, async () => {
+ await serializeByKey(`${connectionId} ${request.externalKey}`, async () => {
+ if (!isCurrentGeneration(admittedGeneration)) {
+ throw new Error('hook account changed while creating the task');
+ }
+ const resolved = await resolveTarget(
+ connectionId,
+ config,
+ {
+ requestId: randomUUID(),
+ externalKey: request.externalKey,
+ workspace: request.workspace,
+ sessionId: null,
+ prompt: '',
+ ...(request.options ? { options: request.options } : {}),
+ ...(source ? { source } : {}),
+ },
+ admittedGeneration,
+ );
+ if ('reject' in resolved) {
+ throw new Error(`session creation rejected: ${resolved.reject}`);
+ }
+ if (resolved.run.isNew) {
+ const outcome = await runner.run({
+ ...resolved.run,
+ createOnly: true,
+ ...(source ? { source } : {}),
+ });
+ if (outcome.status !== 'ok') {
+ bindings.remove(connectionId, request.externalKey);
+ awaitingPersist.delete(resolved.run.sessionId);
+ await resolved.cleanupWorktree?.().catch(() => undefined);
+ throw new Error(outcome.errorMessage || 'failed to create task');
+ }
+ awaitingPersist.delete(resolved.run.sessionId);
+ }
+ // A newer Telegram update may already have materialized this same
+ // generation while `/new` was waiting on the desktop. Reuse that
+ // task instead of creating a second one for the same external key.
+ createdSessionId = resolved.run.sessionId;
+ });
+
+ // The new binding is live before the old one is retired. A failure to
+ // archive history must never route subsequent messages back to it.
+ const previous = bindings.get(connectionId, request.previousExternalKey);
+ bindings.remove(connectionId, request.previousExternalKey);
+ staleTakeoverReplacements.delete(bindingKey(connectionId, request.previousExternalKey));
+ if (previous && previous !== createdSessionId && archiveSessionRow) {
+ const info = await runner.inspect(previous);
+ if (
+ isCurrentGeneration(admittedGeneration) &&
+ info?.usable === true &&
+ info.workingDir !== null &&
+ dirStillAllowed(connectionId, info.workingDir)
+ ) {
+ await archiveSessionRow(previous).catch((err) => {
+ log.warn(
+ `archive previous hook session ${previous} failed after /new: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ });
+ }
+ }
+ });
+ };
+ await createAndRetire();
+ if (!createdSessionId) throw new Error('task was not created');
+ return { sessionId: createdSessionId };
+ },
handleInteractionDecision(connectionId, payload) {
if (!accountActive) return;
// 归属校验: requestId 必须是本连接正在执行的任务(排队中的任务不可能有
diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.ts
index dd748b8f81..640fd1c6bb 100644
--- a/apps/desktop/src/main/hook-control/manager.ts
+++ b/apps/desktop/src/main/hook-control/manager.ts
@@ -29,6 +29,7 @@ import {
HOOK_FEATURE_PROVIDER_TELEGRAM,
HOOK_FEATURE_PROVIDER_X,
HOOK_FEATURE_SESSION_PICKER,
+ HOOK_FEATURE_SESSION_NEW,
HOOK_FEATURE_SLACK_TOOLS,
HOOK_FEATURE_TURN_DELIVERY,
makeBindRevoke,
@@ -692,6 +693,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont
// 只给 Telegram 声明: msg.op 目前只有 Telegram 的执行器, X 的渲染路径
// 不接入(#1855 的红线之一)。
HOOK_FEATURE_MESSAGE_OPS,
+ HOOK_FEATURE_SESSION_NEW,
],
isEnabled: () => store.get().telegramEnabled,
setEnabled: (enabled) => {
@@ -2442,6 +2444,17 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont
)
? (listRecentSessions?.() ?? [])
: Promise.reject(new Error('session-picker-v1 was not negotiated')),
+ createSession: (request) => {
+ if (
+ expectedProvider !== 'telegram' ||
+ lane === null ||
+ !lane.serverFeatures.includes(HOOK_FEATURE_SESSION_NEW) ||
+ !dispatcher
+ ) {
+ return Promise.reject(new Error('session-new-v1 was not negotiated'));
+ }
+ return dispatcher.createSession(dispatchId('telegram'), request);
+ },
},
msg.payload,
).then((response) => {
diff --git a/apps/desktop/src/main/hook-control/queryResponder.ts b/apps/desktop/src/main/hook-control/queryResponder.ts
index 68fe182bdc..782d70338f 100644
--- a/apps/desktop/src/main/hook-control/queryResponder.ts
+++ b/apps/desktop/src/main/hook-control/queryResponder.ts
@@ -41,6 +41,10 @@ export interface QueryResponderDeps {
listAgentModels: () => AgentModelSource[] | Promise<AgentModelSource[]>;
/** 当前账号、仅本地白名单内的隐私最小化 recent sessions。 */
listSessions?: () => QuerySessionEntry[] | Promise<QuerySessionEntry[]>;
+ /** Provider `/new`: create and bind a blank Cindy task immediately. */
+ createSession?: (
+ request: NonNullable<QueryRequestPayload['sessionNew']>,
+ ) => Promise<{ sessionId: string }>;
}
/** 构造 query.response payload; 数据源抛错 / reject 时回 ok:false + 原因。 */
@@ -68,6 +72,19 @@ export async function buildQueryResponse(
sessions,
};
}
+ if (request.kind === 'session-new') {
+ if (!request.sessionNew || !deps.createSession) {
+ throw new Error('session-new-v1 was not negotiated');
+ }
+ const created = await deps.createSession(request.sessionNew);
+ return {
+ queryId: request.queryId,
+ kind: 'session-new',
+ ok: true,
+ error: null,
+ sessionId: created.sessionId,
+ };
+ }
const agents: QueryAgentModels[] = (await deps.listAgentModels()).map((src) => ({
agentKind: src.agentKind,
models: src.models.map((m) => ({
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index f1056eddea..6512beba0f 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -50,6 +50,7 @@ import {
import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';
import { getMaker } from '../maker-host/index.js';
+import { desktopSessionStorage } from '../maker-host/session-storage.js';
import { resolveLenientRoute } from '../maker-host/model-route-guard.js';
import { resolveLenientSessionRoute } from '../maker-host/model-route-guard-live.js';
import {
@@ -646,6 +647,52 @@ export function createMakerHookSessionRunner(deps: {
: {}),
resumeSessionId,
};
+ if (req.createOnly) {
+ if (!req.isNew) return fail('create-only requires a new task');
+ try {
+ // `/new` only needs a durable, sidebar-visible task boundary. Do not
+ // start an Agent process here: that turns a local metadata mutation
+ // into a slow websocket RPC and can leave server/client state split
+ // if the response times out. The first real message cold-opens this
+ // same row through the ordinary reuse path.
+ await desktopSessionStorage.create({
+ id: req.sessionId,
+ agentKind: effectiveAgentKind,
+ workDir: workingDir,
+ title: req.title ?? 'New task',
+ model: effectiveModel,
+ ...(req.workspaceKind !== undefined ? { workspaceKind: req.workspaceKind } : {}),
+ ...(effort !== undefined ? { effort } : {}),
+ permissionMode,
+ });
+ if (providerId) {
+ setSessionProvider(req.sessionId, providerId);
+ await setSessionProviderIdInDb(req.sessionId, providerId);
+ }
+ if (req.source?.im === 'telegram' || req.source?.im === 'x') {
+ await setSessionSourceInDb(req.sessionId, req.source.im);
+ }
+ await touchUserSendInDb(req.sessionId).catch((err) => {
+ log.warn(
+ `hook create-only touchUserSend failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ });
+ const wtMeta = worktreeStore.get(req.sessionId);
+ if (wtMeta) await setWorktreePathInDb(req.sessionId, wtMeta.path);
+ broadcastSessionCreated(req.sessionId);
+ return {
+ status: 'ok',
+ finalText: '',
+ errorMessage: '',
+ durationMs: Date.now() - startedAt,
+ };
+ } catch (err) {
+ if (worktreeStore.get(req.sessionId)) {
+ void WorktreeManager.removeWorktreeForSession(req.sessionId).catch(() => undefined);
+ }
+ return fail(err instanceof Error ? err.message : String(err));
+ }
+ }
try {
await prepareUnhealthySessionForSend(req.sessionId);
session = await maker.createSession(createOpts);
diff --git a/apps/desktop/src/main/im/__tests__/binding.test.ts b/apps/desktop/src/main/im/__tests__/binding.test.ts
index 9a4b21cad6..74b2a3c536 100644
--- a/apps/desktop/src/main/im/__tests__/binding.test.ts
+++ b/apps/desktop/src/main/im/__tests__/binding.test.ts
@@ -183,6 +183,28 @@ describe('SqliteBindingStore single-owner reverse index', () => {
expect(mocks.deleteWhere).not.toHaveBeenCalled();
});
+ it('mirrors an externally committed detach without a second database delete', async () => {
+ const store = new SqliteBindingStore();
+ const events: BindingChangeEvent<string>[] = [];
+ store.onChange((event) => events.push(event));
+ await store.preload();
+ await store.attach(feishuIdentity, 'desktop-session');
+ mocks.deleteWhere.mockClear();
+
+ await expect(
+ store.applyPersistedDetach(feishuIdentity, 'desktop-session'),
+ ).resolves.toBe(true);
+
+ expect(store.get(feishuIdentity)).toBeNull();
+ expect(store.findByTarget('desktop-session')).toBeNull();
+ expect(mocks.deleteWhere).not.toHaveBeenCalled();
+ expect(events.at(-1)).toEqual({
+ identity: feishuIdentity,
+ value: null,
+ prevValue: 'desktop-session',
+ });
+ });
+
it('repairs persisted duplicate targets by keeping the latest takeover', async () => {
mocks.rows.push(
{
diff --git a/apps/desktop/src/main/im/binding.ts b/apps/desktop/src/main/im/binding.ts
index ea5aa46a02..0933feace3 100644
--- a/apps/desktop/src/main/im/binding.ts
+++ b/apps/desktop/src/main/im/binding.ts
@@ -338,6 +338,27 @@ export class SqliteBindingStore implements BindingStore<string> {
});
}
+ /**
+ * Mirror a detach that was committed by another localDb transaction. The
+ * expected target check preserves a newer concurrent takeover; this method
+ * intentionally performs no second database write.
+ */
+ applyPersistedDetach(identity: IdentityKey, expectedTargetSessionId: string): Promise<boolean> {
+ return this.enqueueMutation(async () => {
+ const k = keyOf(identity);
+ const oldSessionId = this.forward.get(k);
+ if (oldSessionId !== expectedTargetSessionId) return false;
+ this.forward.delete(k);
+ const reverseIdentity = this.reverse.get(oldSessionId);
+ if (reverseIdentity && keyOf(reverseIdentity) === k) {
+ this.reverse.delete(oldSessionId);
+ }
+ this.attachCardIds.delete(k);
+ this.emit({ identity, value: null, prevValue: oldSessionId });
+ return true;
+ });
+ }
+
onChange(listener: BindingChangeListener<string>): () => void {
this.listeners.add(listener);
return () => {
diff --git a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
index ddabdc6290..5743e5bfee 100644
--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
@@ -324,9 +324,11 @@ describe('feishu group lane adapter hooks', () => {
});
it('turnPolicyOptionalForMode: 仅完全访问档可选(护栏取缔), 其余档保持挂策略', () => {
- expect(adapter.turnPolicyOptionalForMode?.('bypassPermissions')).toBe(true);
- expect(adapter.turnPolicyOptionalForMode?.('auto')).toBe(false);
- expect(adapter.turnPolicyOptionalForMode?.('acceptEdits')).toBe(false);
+ const policy = adapter.turnPermissionPolicyFor?.(groupEvent());
+ expect(policy).toBeDefined();
+ expect(adapter.turnPolicyOptionalForMode?.('bypassPermissions', policy!)).toBe(true);
+ expect(adapter.turnPolicyOptionalForMode?.('auto', policy!)).toBe(false);
+ expect(adapter.turnPolicyOptionalForMode?.('acceptEdits', policy!)).toBe(false);
});
it('prepareAgentTurnText: 群 lane 拉历史拼上下文前缀(带时间标注), 剔除触发消息', async () => {
diff --git a/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
index 62fc9dd9ce..45fd666304 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest';
+import en from '../../../../renderer/i18n/locales/en/common.json';
+import ja from '../../../../renderer/i18n/locales/ja/common.json';
+import ko from '../../../../renderer/i18n/locales/ko/common.json';
+import zhCN from '../../../../renderer/i18n/locales/zh-CN/common.json';
+import zhTW from '../../../../renderer/i18n/locales/zh-TW/common.json';
+
import {
BOT_COMMANDS,
type BotCommandDefinition,
@@ -44,6 +50,22 @@ const OFFICIAL_SERVER_COMMANDS = [
] as const;
describe('bot command registry', () => {
+ it('Telegram /new menu copy says it creates a session/task in every locale', () => {
+ expect([
+ en.settings.telegramBot.commandMenu.new,
+ zhCN.settings.telegramBot.commandMenu.new,
+ zhTW.settings.telegramBot.commandMenu.new,
+ ja.settings.telegramBot.commandMenu.new,
+ ko.settings.telegramBot.commandMenu.new,
+ ]).toEqual([
+ 'Create a new session',
+ '创建新任务',
+ '建立新任務',
+ '新しいセッションを作成',
+ '새 세션 만들기',
+ ]);
+ });
+
it('个人 bot 菜单顺序、文案 key 与别名逐字节不变', () => {
expect(PERSONAL_BOT_COMMAND_LOCALE_POLICY).toBe('desktop-app');
expect(
diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
index cd3796485d..26b2bca862 100644
--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => {
insertConflict,
insertValues,
selectLimit,
+ tx: vi.fn(async () => ({ previousStatus: 'active' as const })),
webContentsSend: vi.fn(),
tapWindowBroadcast: vi.fn(),
retireDeletedPiSubagentState: vi.fn(async () => undefined),
@@ -38,6 +39,8 @@ const mocks = vi.hoisted(() => {
// 的 SET, 这里只看判据的形状 —— 它在真 SQLite 下的语义由
// sessionRepoWorkspaceKind.test.ts 覆盖。
vi.mock('drizzle-orm', () => ({
+ and: (...conditions: unknown[]) => ({ and: conditions }),
+ desc: (col: unknown) => ({ desc: col }),
eq: (col: unknown, val: unknown) => ({ col, val }),
sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({
sqlText: strings.raw
@@ -62,9 +65,15 @@ vi.mock('../../../logger', () => ({
}));
vi.mock('../../../localDb/client/current', () => ({
getDbClient: () => ({
+ tx: mocks.tx,
drizzle: {
select: () => ({
- from: () => ({ where: () => ({ limit: mocks.selectLimit }) }),
+ from: () => ({
+ where: () => ({
+ limit: mocks.selectLimit,
+ orderBy: () => ({ limit: mocks.selectLimit }),
+ }),
+ }),
}),
update: () => ({ set: mocks.updateSet }),
insert: () => ({ values: mocks.insertValues }),
@@ -76,6 +85,10 @@ vi.mock('../../../localDb/schema', () => ({
id: 'sessions.id',
workingDir: 'sessions.working_dir',
workspaceKind: 'sessions.workspace_kind',
+ source: 'sessions.source',
+ imBotContextId: 'sessions.im_bot_context_id',
+ imUserId: 'sessions.im_user_id',
+ createdAt: 'sessions.created_at',
},
}));
vi.mock('../../../localDb/ipc/piSubagentDeletion', () => ({
@@ -155,6 +168,7 @@ describe('sessionRepo.findActiveSession 软删行复活(#748)', () => {
mocks.selectLimit.mockReset();
mocks.selectLimit.mockResolvedValue([]);
mocks.retireDeletedPiSubagentState.mockClear();
+ mocks.tx.mockClear();
});
it.each(['archived', 'deleted'] as const)(
@@ -287,19 +301,14 @@ describe('sessionRepo workspaceKind(渠道声明 dialogue 归组时)', () => {
/** 开着 `/project` 的渠道(个人 Telegram): 归属可以按路径推断。 */
function makeDialogueRepo() {
- return createImSessionRepo(
- { agentKind: 'claude-code' } as ImOrchestratorConfig,
- dialogueNs,
- { projectSwitching: true },
- );
+ return createImSessionRepo({ agentKind: 'claude-code' } as ImOrchestratorConfig, dialogueNs, {
+ projectSwitching: true,
+ });
}
/** 没有 `/project` 的渠道(微信这类): 只有托管目录, 且它用户可改。 */
function makePlainDialogueRepo() {
- return createImSessionRepo(
- { agentKind: 'claude-code' } as ImOrchestratorConfig,
- dialogueNs,
- );
+ return createImSessionRepo({ agentKind: 'claude-code' } as ImOrchestratorConfig, dialogueNs);
}
beforeEach(() => {
@@ -400,3 +409,67 @@ describe('sessionRepo.prepareNewSession 权限档覆写钩子', () => {
expect(row.permissionMode).toBe('auto');
});
});
+
+describe('sessionRepo.createFreshSession', () => {
+ it('creates a new Telegram task from current defaults, preserves the project, and archives the old task', async () => {
+ const telegramNs: ImSessionNamespace = {
+ source: 'telegram',
+ createTaskOnNew: true,
+ sessionIdFor: () => 'telegram_bot_user',
+ defaultTitle: () => 'Telegram',
+ workspaceKind: 'dialogue',
+ ensureWorkingDir: () => '/tmp/telegram',
+ extraInsertColumns: (bot, user) => ({ imBotContextId: bot, imUserId: user }),
+ };
+ const old = {
+ ...dbRow('active'),
+ id: 'old-task',
+ source: 'telegram',
+ workingDir: '/projects/current',
+ workspaceKind: 'project' as const,
+ imBotContextId: 'bot',
+ imUserId: 'user',
+ createdAt: 1,
+ };
+ const prepared: ImSessionRow = {
+ ...preparedDefaults,
+ id: 'telegram_bot_user',
+ agentKind: 'pi',
+ model: 'grok-4.6',
+ providerId: 'xai',
+ permissionMode: 'bypassPermissions',
+ workingDir: '/tmp/telegram',
+ };
+ mocks.selectLimit.mockResolvedValueOnce([old]);
+ const repo = createImSessionRepo(
+ { agentKind: 'claude-code' } as ImOrchestratorConfig,
+ telegramNs,
+ { projectSwitching: true },
+ );
+
+ const result = await repo.createFreshSession!('bot', 'user', undefined, prepared);
+
+ expect(result.previous?.id).toBe('old-task');
+ expect(result.current.id).not.toBe('old-task');
+ expect(mocks.tx).toHaveBeenCalledWith(
+ 'im.rotateSession',
+ expect.objectContaining({
+ previousSessionId: 'old-task',
+ detachBinding: null,
+ session: expect.objectContaining({
+ id: result.current.id,
+ agentKind: 'pi',
+ model: 'grok-4.6',
+ providerId: 'xai',
+ permissionMode: 'bypassPermissions',
+ workingDir: '/projects/current',
+ workspaceKind: 'project',
+ imBotContextId: 'bot',
+ imUserId: 'user',
+ }),
+ }),
+ );
+ expect(routeLock).toHaveBeenCalledWith('telegram_bot_user', expect.any(Function));
+ expect(routeLock).toHaveBeenCalledWith('old-task', expect.any(Function));
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
index a8f811aa0f..bc0c7c8f53 100644
--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
getModelVisibilityOverride: vi.fn(),
getSessionProvider: vi.fn(),
getMaker: vi.fn(),
+ executeDetach: vi.fn(),
}));
vi.mock('../../../logger', () => ({ createLogger: () => mocks.logger }));
@@ -30,9 +31,10 @@ vi.mock('../../binding', () => ({
bindingStore: {
get: vi.fn(),
detach: vi.fn(),
+ applyPersistedDetach: vi.fn(),
listByIdentity: vi.fn(() => []),
},
- executeDetach: vi.fn(),
+ executeDetach: mocks.executeDetach,
}));
vi.mock('../controlProjects', () => ({
listProjectsForControl: vi.fn(async () => []),
@@ -75,6 +77,7 @@ function makeRepo(overrides: Partial<ImSessionRepo> = {}): ImSessionRepo {
peekSessionById: vi.fn(async () => null),
prepareNewSession: vi.fn(async () => defaultRow),
createSession: vi.fn(async () => defaultRow),
+ createFreshSession: vi.fn(async () => ({ current: defaultRow, previous: defaultRow })),
getDefaultEffortFor: vi.fn(() => 'high' as const),
...overrides,
};
@@ -158,6 +161,7 @@ describe('IM slash commands', () => {
permissionModes: [{ id: 'auto', displayName: 'Auto', description: 'Safe default' }],
}),
});
+ mocks.executeDetach.mockResolvedValue({ wasAttached: false, targetSessionId: null });
});
it('does not create or reset a session when /new defaults are unauthenticated', async () => {
@@ -294,22 +298,89 @@ describe('IM slash commands', () => {
expect(mocks.resetSessionToDefaults).not.toHaveBeenCalled();
});
- it('resets an existing session to the current defaults after /new', async () => {
- const prepared = { ...defaultRow, agentKind: 'codex' as const, model: 'gpt-5.5' };
- const repo = makeRepo({ prepareNewSession: vi.fn(async () => prepared) });
- const { handlers } = makeHarness({ repo });
+ it('creates a distinct Telegram task from the current Pi, Grok, provider, and Full access defaults after /new', async () => {
+ const { bindingStore } = await import('../../binding');
+ vi.mocked(bindingStore.get).mockReturnValueOnce('attached-desktop-task');
+ vi.mocked(bindingStore.applyPersistedDetach).mockResolvedValueOnce(true);
+ const prepared = {
+ ...defaultRow,
+ agentKind: 'pi' as const,
+ model: 'grok-4.6',
+ providerId: 'xai',
+ permissionMode: 'bypassPermissions' as const,
+ };
+ const fresh = { ...prepared, id: 'telegram-new-task' };
+ const createFreshSession = vi.fn(async () => ({ current: fresh, previous: defaultRow }));
+ const repo = makeRepo({
+ prepareNewSession: vi.fn(async () => prepared),
+ createFreshSession,
+ });
+ const { handlers, turnRunner } = makeHarness({
+ repo,
+ adapterOverrides: {
+ channel: 'telegram',
+ sessions: {
+ source: 'telegram',
+ sessionIdFor: () => 'telegram-legacy-task',
+ createTaskOnNew: true,
+ defaultTitle: () => 'Telegram',
+ ensureWorkingDir: () => '/tmp/telegram',
+ extraInsertColumns: () => ({}),
+ },
+ },
+ });
await handlers.handleSlashCommand('/new', { botContextId: 'bot', userId: 'ou_user' });
- expect(mocks.resetSessionToDefaults).toHaveBeenCalledWith(
- 'feishu-session',
- expect.anything(),
+ const identity = { channel: 'telegram', botContextId: 'bot', userId: 'ou_user' };
+ expect(createFreshSession).toHaveBeenCalledWith(
+ 'bot',
+ 'ou_user',
+ undefined,
prepared,
- 'feishu',
+ { identity, targetSessionId: 'attached-desktop-task' },
);
+ expect(createFreshSession.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(bindingStore.applyPersistedDetach).mock.invocationCallOrder[0]!,
+ );
+ expect(bindingStore.applyPersistedDetach).toHaveBeenCalledWith(
+ identity,
+ 'attached-desktop-task',
+ );
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
+ expect(mocks.resetSessionToDefaults).not.toHaveBeenCalled();
+ expect(turnRunner.disposeOneSession).toHaveBeenCalledWith(defaultRow.id);
expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.slash.new);
});
+ it('keeps /ctr attached when Telegram task rotation fails', async () => {
+ const createFreshSession = vi.fn(async () => {
+ throw new Error('db unavailable');
+ });
+ const repo = makeRepo({ createFreshSession });
+ const { handlers } = makeHarness({
+ repo,
+ adapterOverrides: {
+ channel: 'telegram',
+ sessions: {
+ source: 'telegram',
+ sessionIdFor: () => 'telegram-legacy-task',
+ createTaskOnNew: true,
+ defaultTitle: () => 'Telegram',
+ ensureWorkingDir: () => '/tmp/telegram',
+ extraInsertColumns: () => ({}),
+ },
+ },
+ });
+
+ await expect(
+ handlers.handleSlashCommand('/new', { botContextId: 'bot', userId: 'ou_user' }),
+ ).rejects.toThrow('db unavailable');
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
+ const { bindingStore } = await import('../../binding');
+ expect(bindingStore.applyPersistedDetach).not.toHaveBeenCalled();
+ });
+
it('does not send /model picker when creating the target session would fail auth', async () => {
const turnRunner = makeTurnRunner({
resolveRouteTarget: vi.fn(async () => null),
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index f8793db099..b0783d779b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1161,6 +1161,75 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
},
);
+ it.each([
+ {
+ capabilities: {} as Capabilities,
+ mode: 'ask' as const,
+ expected: 'AGENT_UNSUPPORTED_COPY',
+ },
+ {
+ capabilities: {
+ turnPermissionPolicy: {
+ supported: { supported: true },
+ unsupportedPermissionModes: ['bypassPermissions'],
+ },
+ } as unknown as Capabilities,
+ mode: 'bypassPermissions' as const,
+ expected: 'MODE_UNSUPPORTED_COPY:bypassPermissions',
+ },
+ ])(
+ 'maps policy rejection to the matching user guidance',
+ async ({ capabilities, mode, expected }) => {
+ const h = createSessionHarness(
+ async () => {
+ throw new TurnPermissionPolicyUnsupportedError('claude-code', mode);
+ },
+ 'feishu-session',
+ { capabilities },
+ );
+ mocks.getMaker.mockReturnValue(createMakerHarness(h.session));
+ const localRunner = createTurnRunner(
+ {
+ ...fakeAdapter,
+ ui: {
+ ...fakeAdapter.ui,
+ error: {
+ ...fakeAdapter.ui.error,
+ agentUnsupported: 'AGENT_UNSUPPORTED_COPY',
+ permissionModeUnsupported: (permissionMode: string) =>
+ `MODE_UNSUPPORTED_COPY:${permissionMode}`,
+ },
+ },
+ },
+ fakeRepo,
+ fakeCards,
+ );
+
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: `msg-policy-copy-${mode}`,
+ text: 'policy failure',
+ attachments: [],
+ turnPermissionPolicy: {
+ origin: { kind: 'im', channel: 'wechat' },
+ confirmationSurface: 'channel',
+ forceConfirmToolCall: () => false,
+ },
+ });
+
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
+ 'ou_user',
+ expected,
+ expect.anything(),
+ );
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ },
+ );
+
it('skips the turn policy when the channel declares the session mode optional (Full access guardrail removal)', async () => {
// feishu 渠道设置显式放行「完全访问」后: 该档位的群轮次不再挂强确认
// 策略, maker 不 fail-closed, 按用户选择直接执行。
@@ -1202,6 +1271,59 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
}
});
+ it('keeps a non-optional group policy in Full access so the turn fails closed', async () => {
+ mocks.peekSessionById.mockImplementationOnce(async () => ({
+ permissionMode: 'bypassPermissions',
+ } as unknown as ImSessionRow));
+ const h = createSessionHarness(
+ async () => {
+ throw new TurnPermissionPolicyUnsupportedError('pi', 'bypassPermissions');
+ },
+ 'telegram-guest-full-access',
+ {
+ capabilities: {
+ turnPermissionPolicy: {
+ supported: { supported: true },
+ unsupportedPermissionModes: ['bypassPermissions'],
+ },
+ } as unknown as Capabilities,
+ },
+ );
+ mocks.getMaker.mockReturnValue(createMakerHarness(h.session));
+ const turnPermissionPolicy: TurnPermissionPolicy = {
+ origin: { kind: 'im', channel: 'telegram', taskId: 'msg-guest-policy' },
+ confirmationSurface: 'channel',
+ forceConfirmToolCall: () => false,
+ };
+ const optionalForMode = vi.fn(() => false);
+ const localAdapter = {
+ ...fakeAdapter,
+ turnPolicyOptionalForMode: optionalForMode,
+ } as unknown as ImChannelAdapter;
+ const localRunner = createTurnRunner(localAdapter, fakeRepo, fakeCards, {});
+
+ try {
+ const dispatch = await localRunner.dispatchAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'g/-100/77',
+ userMessageId: 'msg-guest-policy',
+ text: 'guest full access group turn',
+ attachments: [],
+ queueMode: 'external',
+ beforeProviderStart: vi.fn(async () => undefined),
+ turnPermissionPolicy,
+ });
+
+ expect(optionalForMode).toHaveBeenCalledWith('bypassPermissions', turnPermissionPolicy);
+ expect(dispatch).toEqual({
+ kind: 'rejected',
+ reason: 'TURN_PERMISSION_POLICY_UNSUPPORTED:mode:bypassPermissions',
+ });
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ });
+
it('keeps the turn policy for other modes even with the optional-mode hook', async () => {
mocks.peekSessionById.mockImplementationOnce(
async () => ({ permissionMode: 'auto' } as unknown as ImSessionRow),
diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.ts
index 2853b1e770..d94a549d95 100644
--- a/apps/desktop/src/main/im/shared/sessionRepo.ts
+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts
@@ -2,16 +2,20 @@
* main/im/shared/sessionRepo.ts
* ---------------------------------------------------------------------------
* IM 渠道的 sessions DB 层(渠道无关)。`sessions` 表与 desktop UI 会话共用
- * (见 localDb/schema.ts);按确定性 session id 查找/创建属于 (botContextId,
- * userId) 的会话行。渠道差异(id 格式 / source 列值 / 默认 title / workingDir
- * 策略 / 渠道专属列)收敛在 ImSessionNamespace, 由 adapter 注入。
+ * (见 localDb/schema.ts);按渠道路由查找/创建属于 (botContextId, userId) 的
+ * 会话行。大多数渠道沿用确定性 id;Telegram `/new` 会轮换成新的任务 id。
+ * 渠道差异(id 格式 / source 列值 / 默认 title / workingDir 策略 / 渠道专属列)
+ * 收敛在 ImSessionNamespace, 由 adapter 注入。
*
* Manual INSERT (不走 maker 的 DesktopSessionStorage.create) — 为了预填渠道
* 专属列。Maker 的 `createSession({ id })` 经 storage.get() 看到行已存在,
* 只附加 SDK handle。
*/
-import { eq, sql } from 'drizzle-orm';
+import { randomUUID } from 'node:crypto';
+
+import { and, desc, eq, sql } from 'drizzle-orm';
+import type { IdentityKey } from '@cindy/im';
import type { AgentKind, Effort, PermissionMode } from '@cindy/maker-core';
import type { ProviderView } from '@cindy/model-providers';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
@@ -116,6 +120,17 @@ export interface ImSessionRepo {
scopeKey?: string,
prepared?: ImSessionRow,
): Promise<ImSessionRow>;
+ /**
+ * Create a distinct task from current channel defaults, then retire the
+ * previous channel-native task. Only namespaces with createTaskOnNew opt in.
+ */
+ createFreshSession?(
+ botContextId: string,
+ userId: string,
+ scopeKey?: string,
+ prepared?: ImSessionRow,
+ detachBinding?: { identity: IdentityKey; targetSessionId: string } | null,
+ ): Promise<{ current: ImSessionRow; previous: ImSessionRow | null }>;
/**
* 该渠道语境下 model 的默认 effort:
* 1. config.effortOverrides[modelId] — IM 产品决策
@@ -199,6 +214,32 @@ export function createImSessionRepo(
return workingDir === ns.ensureWorkingDir(botContextId) ? 'dialogue' : 'project';
}
+ async function selectChannelRow(
+ botContextId: string,
+ userId: string,
+ scopeKey?: string,
+ ): Promise<typeof sessions.$inferSelect | null> {
+ const db = getDbClient().drizzle;
+ if (ns.createTaskOnNew) {
+ const rows = await db
+ .select()
+ .from(sessions)
+ .where(
+ and(
+ eq(sessions.source, ns.source),
+ eq(sessions.imBotContextId, botContextId),
+ eq(sessions.imUserId, userId),
+ ),
+ )
+ .orderBy(desc(sessions.createdAt), desc(sessions.id))
+ .limit(1);
+ if (rows[0]) return rows[0];
+ }
+ const legacyId = ns.sessionIdFor(botContextId, userId, scopeKey);
+ const rows = await db.select().from(sessions).where(eq(sessions.id, legacyId)).limit(1);
+ return rows[0] ?? null;
+ }
+
return {
sessionIdFor: (botContextId, userId, scopeKey) =>
ns.sessionIdFor(botContextId, userId, scopeKey),
@@ -214,10 +255,7 @@ export function createImSessionRepo(
* 会用同 id INSERT 撞 UNIQUE(sessions.id),IM 消息从此全部报错(#748)。
*/
async peekSession(botContextId, userId, scopeKey) {
- const id = ns.sessionIdFor(botContextId, userId, scopeKey);
- const db = getDbClient().drizzle;
- const rows = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1);
- const row = rows[0];
+ const row = await selectChannelRow(botContextId, userId, scopeKey);
if (!row) return null;
return {
id: row.id,
@@ -235,11 +273,10 @@ export function createImSessionRepo(
},
async findActiveSession(botContextId, userId, scopeKey) {
- const id = ns.sessionIdFor(botContextId, userId, scopeKey);
+ const routeId = ns.sessionIdFor(botContextId, userId, scopeKey);
const db = getDbClient().drizzle;
- const result = await withSessionRouteLock(id, async () => {
- const rows = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1);
- const row = rows[0];
+ const result = await withSessionRouteLock(routeId, async () => {
+ const row = await selectChannelRow(botContextId, userId, scopeKey);
if (!row) return null;
const workspaceKind = readWorkspaceKind(
row.workingDir,
@@ -255,7 +292,7 @@ export function createImSessionRepo(
if (row.status === 'deleted') {
// Durable Subagent 墓碑与进行中的删除清理必须在翻回 active 之前撤掉,
// 否则确定性 id 复活后每次 spawn 仍判父任务已删除。
- await retireDeletedPiSubagentState(id);
+ await retireDeletedPiSubagentState(row.id);
}
const now = Date.now();
await db
@@ -267,7 +304,7 @@ export function createImSessionRepo(
// 渠道声明了归属分组时顺手校正老行, 但不碰用户 `/project` 切出去的行
...correctedWorkspaceKind(botContextId),
})
- .where(eq(sessions.id, id));
+ .where(eq(sessions.id, row.id));
revivedFrom = row.status;
} else if (workspaceKind !== null && workspaceKind !== row.workspaceKind) {
// 存量脏行**就地回写**, 不等下一次归档。sidebar 的分组直接投影 DB 那一列
@@ -279,7 +316,7 @@ export function createImSessionRepo(
await db
.update(sessions)
.set({ ...correctedWorkspaceKind(botContextId), updatedAt: Date.now() })
- .where(eq(sessions.id, id));
+ .where(eq(sessions.id, row.id));
workspaceKindCorrected = true;
}
return { row, workspaceKind, revivedFrom, workspaceKindCorrected };
@@ -378,7 +415,9 @@ export function createImSessionRepo(
.values({
id: row.id,
title: ns.defaultTitle(userId),
- ...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
+ ...(row.workspaceKind ?? ns.workspaceKind
+ ? { workspaceKind: row.workspaceKind ?? ns.workspaceKind }
+ : {}),
workingDir: row.workingDir,
model: row.model,
effort: row.effort,
@@ -461,6 +500,84 @@ export function createImSessionRepo(
}
return result;
},
+
+ async createFreshSession(botContextId, userId, scopeKey, prepared, detachBinding) {
+ if (!ns.createTaskOnNew) {
+ throw new Error(`${ns.source} does not create a new task for /new`);
+ }
+ const routeId = ns.sessionIdFor(botContextId, userId, scopeKey);
+ return withSessionRouteLock(routeId, async () => {
+ const previous = await this.peekSession(botContextId, userId, scopeKey);
+ const defaults = prepared ?? (await this.prepareNewSession(botContextId, userId, scopeKey));
+ const fresh: ImSessionRow = {
+ ...defaults,
+ id: randomUUID(),
+ // `/project` is a lane preference. `/new` changes the task and its
+ // model route, but must not unexpectedly move the lane elsewhere.
+ workingDir: previous?.workingDir ?? defaults.workingDir,
+ workspaceKind: previous?.workspaceKind ?? defaults.workspaceKind,
+ sdkSessionId: null,
+ };
+ const rotate = async (): Promise<{
+ current: ImSessionRow;
+ previous: ImSessionRow | null;
+ }> => {
+ const client = getDbClient();
+ const now = Date.now();
+ const markers = ns.extraInsertColumns(botContextId, userId);
+ const imBotContextId = markers.imBotContextId;
+ const imUserId = markers.imUserId;
+ if (typeof imBotContextId !== 'string' || typeof imUserId !== 'string') {
+ throw new Error(`${ns.source} fresh-task routing markers are invalid`);
+ }
+ const result = await client.tx('im.rotateSession', {
+ previousSessionId: previous?.id ?? null,
+ detachBinding: detachBinding
+ ? {
+ channel: detachBinding.identity.channel,
+ botContextId: detachBinding.identity.botContextId,
+ userId: detachBinding.identity.userId,
+ scopeKey: detachBinding.identity.scopeKey ?? '',
+ targetSessionId: detachBinding.targetSessionId,
+ }
+ : null,
+ session: {
+ id: fresh.id,
+ title: ns.defaultTitle(userId),
+ workingDir: fresh.workingDir,
+ workspaceKind: fresh.workspaceKind ?? ns.workspaceKind ?? 'project',
+ model: fresh.model,
+ effort: fresh.effort,
+ permissionMode: fresh.permissionMode,
+ fastMode: fresh.fastMode,
+ agentKind: toDbAgentKind(fresh.agentKind),
+ providerId: fresh.providerId,
+ source: ns.source,
+ imBotContextId,
+ imUserId,
+ },
+ now,
+ });
+ if (fresh.providerId) setSessionProvider(fresh.id, fresh.providerId);
+ log.info(
+ `created fresh ${ns.source} session id=${fresh.id} workingDir=${maskPath(fresh.workingDir)} ` +
+ `agent=${fresh.agentKind} model=${fresh.model} effort=${fresh.effort} ` +
+ `provider=${fresh.providerId ?? 'default'} permissionMode=${fresh.permissionMode}`,
+ );
+ broadcastSessionCreated(fresh.id);
+ if (previous && result.previousStatus !== 'deleted') {
+ broadcastSessionPatched(previous.id, { status: 'archived' });
+ }
+ return { current: fresh, previous };
+ };
+ // The deterministic lane lock serializes Telegram messages; the
+ // current UUID lock also serializes against Desktop archive/delete.
+ if (previous && previous.id !== routeId) {
+ return withSessionRouteLock(previous.id, rotate);
+ }
+ return rotate();
+ });
+ },
};
}
@@ -496,7 +613,8 @@ export async function touchUserSent(sessionId: string): Promise<void> {
}
/**
- * `/new` semantic: clear the conversation context but keep the session row.
+ * Legacy single-row channel `/new` semantic: clear the conversation context
+ * but keep the session row. Telegram uses createFreshSession instead.
*
* Implementation: null out `sdkSessionId` so the next `maker.createSession`
* for this id starts a fresh SDK conversation thread (no resume). Caller is
@@ -518,7 +636,8 @@ export async function clearContext(sessionId: string): Promise<void> {
}
/**
- * `/new` 语义:保留同一个 IM 会话行,但按当前渠道的 IM 默认重新开始一条新对话。
+ * 存量单行渠道的 `/new` 语义:保留同一个 IM 会话行,但按当前渠道的 IM 默认
+ * 重新开始一条新对话。Telegram 走 createFreshSession, 不调用这里。
*
* 这会同时重置 agent/model/effort/provider/permission/fast 和 sdkSessionId。也就是说
* 用户把飞书默认从 Claude Code 改成 Codex 后,在飞书里执行 `/new` 会按 Codex 开始,
diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.ts
index 6d220ef37a..0658b8e639 100644
--- a/apps/desktop/src/main/im/shared/slashCommands.ts
+++ b/apps/desktop/src/main/im/shared/slashCommands.ts
@@ -269,7 +269,36 @@ export function createSlashHandlers(
);
return true;
}
- // 找到当前 IM 会话行;没有历史会话时按已通过认证的默认值创建一行。
+ if (adapter.sessions.createTaskOnNew) {
+ if (!repo.createFreshSession) {
+ throw new Error(`${channel} session rotation is not available`);
+ }
+ const identity: IdentityKey = {
+ channel,
+ botContextId: ctx.botContextId,
+ userId: ctx.userId,
+ };
+ const attachedTargetSessionId = bindingStore.get(identity);
+ const { previous } = await repo.createFreshSession(
+ ctx.botContextId,
+ ctx.userId,
+ undefined,
+ prepared,
+ attachedTargetSessionId
+ ? { identity, targetSessionId: attachedTargetSessionId }
+ : null,
+ );
+ // Session rotation and the persisted `/ctr` detach commit in one
+ // SQLite transaction. Only mirror that committed deletion in memory;
+ // a newer concurrent takeover is preserved by the expected target.
+ if (attachedTargetSessionId) {
+ await bindingStore.applyPersistedDetach(identity, attachedTargetSessionId);
+ }
+ if (previous) await turnRunner.disposeOneSession(previous.id);
+ await safeSendText(ctx, ui.slash.new);
+ return true;
+ }
+ // Legacy single-row channels keep their established reset semantics.
const existing = await repo.findActiveSession(ctx.botContextId, ctx.userId);
const row =
existing ?? (await repo.createSession(ctx.botContextId, ctx.userId, undefined, prepared));
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 27101add97..c530dee6d3 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -970,9 +970,10 @@ export function createTurnRunner(
* 退回队首, 等下一个 done/error 或 retry timer 再派发, 不报错。
*/
/**
- * 群护栏取缔(feishu): 渠道通过 turnPolicyOptionalForMode 声明「该权限档下
- * 强确认策略可选」时, dispatch 前按会话当前权限档决定是否真正挂策略 —
- * 返回 undefined = 不挂, maker 不再 fail-closed, 按用户显式选择直接执行。
+ * 群护栏取缔: 渠道通过 turnPolicyOptionalForMode 声明「该权限档下本轮
+ * 强确认策略可选」时, dispatch 前按会话当前权限档与具体 policy 决定是否
+ * 真正挂策略 —— 返回 undefined = 不挂, maker 不再 fail-closed, 按用户显式
+ * 选择直接执行。
* 群上下文的防注入过滤与包裹独立于策略, 照常生效; 查档失败保持挂策略
* (fail-closed 兜底)。其它渠道不实现该钩子, 行为不变。
*/
@@ -984,7 +985,10 @@ export function createTurnRunner(
}
try {
const row = await repo.peekSessionById(item.rowId);
- if (row && adapter.turnPolicyOptionalForMode(row.permissionMode)) {
+ if (
+ row &&
+ adapter.turnPolicyOptionalForMode(row.permissionMode, item.turnPermissionPolicy)
+ ) {
log.info(
`turn policy skipped by channel (mode=${row.permissionMode}) session=${item.rowId.slice(-8)}`,
);
@@ -1072,7 +1076,7 @@ export function createTurnRunner(
)
: withHandoff;
- // 群护栏取缔(飞书): 按会话当前权限档决定是否真正挂强确认策略, 见
+ // 群护栏取缔: 按会话当前权限档决定是否真正挂强确认策略, 见
// resolveEffectiveTurnPolicy。不挂时走与 DM 轮次相同的无策略路径。
const effectiveTurnPolicy = await resolveEffectiveTurnPolicy(item);
@@ -2600,8 +2604,11 @@ export function createTurnRunner(
// 已由渠道设置显式放行, 实际只剩 acceptEdits)— 给用户能看懂的说法并
// 指路 /permission + 私聊修复卡, 而不是裸抛策略错误码。
const policyUnsupported = failure.reason.startsWith('TURN_PERMISSION_POLICY_UNSUPPORTED');
- const rejectedMode = failure.reason.split(':')[2] ?? '';
- const unsupportedCopy = adapter.ui.error?.permissionModeUnsupported;
+ const [, unsupportedKind = '', rejectedMode = ''] = failure.reason.split(':');
+ const unsupportedCopy =
+ unsupportedKind === 'agent'
+ ? adapter.ui.error?.agentUnsupported
+ : adapter.ui.error?.permissionModeUnsupported;
const message =
policyUnsupported && unsupportedCopy
? typeof unsupportedCopy === 'function'
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index f514b3cb45..7214e00ee8 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -68,6 +68,15 @@ export interface ImSessionNamespace {
* (feishu)忽略 scopeKey, 同一 (botContextId, userId) 恒同一 id。
*/
sessionIdFor(botContextId: string, userId: string, scopeKey?: string): string;
+ /**
+ * `/new` creates a separate Cindy task instead of clearing the SDK context on
+ * the deterministic legacy row. The active task is then resolved by the
+ * channel identity columns rather than by `sessionIdFor`.
+ *
+ * Telegram enables this. Other adapters keep their existing single-row
+ * semantics until their routing contracts are migrated deliberately.
+ */
+ createTaskOnNew?: boolean;
/** 新建 session 行的初始 title。 */
defaultTitle(userId: string): string;
/**
@@ -219,13 +228,16 @@ export interface ImChannelAdapter {
*/
turnPermissionPolicyFor?(event: IMMessageEvent): TurnPermissionPolicy | undefined;
/**
- * 群轮次强确认策略对指定权限档「可选」的渠道判定 — 返回 true 的档位在
- * dispatch 时不挂 turnPermissionPolicy(maker 不再 fail-closed, 按用户显式
- * 选择直接执行)。飞书用它在用户于渠道设置中显式选择「完全访问」后取缔
- * 群护栏; 群上下文的防注入过滤/包裹独立于权限档, 照常生效。其它渠道
- * 不实现即保持 fail-closed。
+ * 群轮次强确认策略对指定权限档「可选」的渠道判定 — 同时传入本轮 policy,
+ * 让渠道能把会话档位授权限定到具体触发者。返回 true 时 dispatch 不挂
+ * turnPermissionPolicy(maker 不再 fail-closed, 按用户显式选择直接执行)。
+ * 群上下文的防注入过滤/包裹独立于权限档, 照常生效。其它渠道不实现即保持
+ * fail-closed。
*/
- turnPolicyOptionalForMode?(permissionMode: PermissionMode): boolean;
+ turnPolicyOptionalForMode?(
+ permissionMode: PermissionMode,
+ turnPermissionPolicy: TurnPermissionPolicy,
+ ): boolean;
/** Telegram 每轮的群历史检索授权;其它渠道不实现即 fail closed。 */
groupHistoryAccessFor?(event: IMMessageEvent): GroupHistoryAccessScope | undefined;
}
diff --git a/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts b/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts
index 378df02c07..b6f71ecb2b 100644
--- a/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts
+++ b/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts
@@ -2,10 +2,54 @@ import { describe, expect, it } from 'vitest';
import type { IMMessageEvent } from '@cindy/im';
import { buildTelegramAdapter } from '../adapter';
+import { ui } from '../uiText';
describe('Telegram group history access scope', () => {
const adapter = buildTelegramAdapter({} as never, {} as never);
+ it('only lets owner-triggered group turns omit the policy in Full access', () => {
+ const groupEvent = {
+ messageId: 'm-policy',
+ speaker: { id: 'guest', name: 'Guest', isOwner: false },
+ } as unknown as IMMessageEvent;
+ const guestPolicy = adapter.turnPermissionPolicyFor?.(groupEvent);
+ const ownerPolicy = adapter.turnPermissionPolicyFor?.({
+ ...groupEvent,
+ messageId: 'm-owner-policy',
+ speaker: { id: 'owner', name: 'Owner', isOwner: true },
+ } as unknown as IMMessageEvent);
+
+ expect(guestPolicy).toMatchObject({
+ origin: { kind: 'im', channel: 'telegram', taskId: 'm-policy' },
+ confirmationSurface: 'channel',
+ });
+ expect(ownerPolicy).toBeDefined();
+ expect(adapter.turnPolicyOptionalForMode?.('bypassPermissions', guestPolicy!)).toBe(false);
+ expect(adapter.turnPolicyOptionalForMode?.('bypassPermissions', ownerPolicy!)).toBe(true);
+ expect(adapter.turnPolicyOptionalForMode?.('auto', ownerPolicy!)).toBe(false);
+ expect(adapter.turnPolicyOptionalForMode?.('ask', ownerPolicy!)).toBe(false);
+ });
+
+ it('does not attach a group confirmation policy to DMs', () => {
+ const groupEvent = {
+ messageId: 'm-policy',
+ speaker: { id: 'guest', name: 'Guest', isOwner: false },
+ } as unknown as IMMessageEvent;
+ expect(
+ adapter.turnPermissionPolicyFor?.({
+ ...groupEvent,
+ speaker: undefined,
+ } as unknown as IMMessageEvent),
+ ).toBeUndefined();
+ });
+
+ it('explains an unsupported permission mode without exposing the internal error code', () => {
+ const message = ui.error.permissionModeUnsupported;
+ expect(message).toContain('自动审批');
+ expect(message).toContain('/permission');
+ expect(message).not.toContain('TURN_PERMISSION_POLICY_UNSUPPORTED');
+ });
+
it('keeps every group turn lane-only — owner-triggered included (injection hardening)', () => {
const base = {
contextId: 'bot-1',
diff --git a/apps/desktop/src/main/im/telegram/__tests__/uiText.test.ts b/apps/desktop/src/main/im/telegram/__tests__/uiText.test.ts
new file mode 100644
index 0000000000..d7816eefec
--- /dev/null
+++ b/apps/desktop/src/main/im/telegram/__tests__/uiText.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { ui } from '../uiText';
+
+describe('Telegram user-facing task naming', () => {
+ it('describes /new as creating a visible task instead of clearing a chat context', () => {
+ expect(ui.slash.new).toContain('新任务已创建');
+ expect(ui.slash.new).toContain('任务列表');
+ expect(ui.slash.new).not.toContain('新对话');
+ expect(ui.slash.new).not.toContain('上下文清掉');
+
+ expect(ui.slash.help).toContain('/new 创建新任务');
+ expect(ui.slash.help).toContain('旧任务保留');
+ });
+});
diff --git a/apps/desktop/src/main/im/telegram/adapter.ts b/apps/desktop/src/main/im/telegram/adapter.ts
index 7d57d5abf9..828b19e91e 100644
--- a/apps/desktop/src/main/im/telegram/adapter.ts
+++ b/apps/desktop/src/main/im/telegram/adapter.ts
@@ -64,6 +64,10 @@ export function buildTelegramAdapter(
telegramIm: TelegramIM,
config: ImOrchestratorConfig,
): ImChannelAdapter {
+ // 同一条群任务会混入 owner 与非 owner 的消息。Full access 只能取缔 owner
+ // 触发轮次的逐轮策略;用对象身份记录这批 policy,避免把会话级权限误当成
+ // 整个群所有成员的授权。WeakSet 不延长排队 policy 的生命周期。
+ const ownerGroupTurnPolicies = new WeakSet<object>();
return {
channel: 'telegram',
im: telegramIm,
@@ -74,6 +78,7 @@ export function buildTelegramAdapter(
sessions: {
source: 'telegram',
sessionIdFor: (botId, userId) => `telegram_${botId}_${sessionSafeUserId(userId)}`,
+ createTaskOnNew: true,
defaultTitle: (userId) =>
decodeTelegramLaneUserId(userId)
? `[TG·群] ${userId.slice(-6)}`
@@ -93,13 +98,23 @@ export function buildTelegramAdapter(
// /project: 从 Telegram 把当前会话切到 desktop 项目目录(bot 原生会话)。
projectSwitching: true,
buildVendorOptions: (userId) => ({ telegramChatId: userId, source: 'telegram' }),
- // 一群一会话的权限收紧(D1 + 2026-07-30 review 修订): **所有群轮次**都挂
- // 破坏性操作强确认 — 不只成员触发的。群窗口/引用块把成员可控文本注入
+ // 一群一会话的权限收紧(D1 + 2026-07-30 review 修订): 除显式 Full access 外,
+ // 所有群轮次都挂破坏性操作强确认 — 不只成员触发的。群窗口/引用块把成员可控文本注入
// owner 触发的轮次, 提示注入可借 owner 轮次的宽松档执行危险操作; 统一
// 强确认后确认卡只认 owner 点击, owner 多一次点按换掉这条注入通路。
// DM(无 speaker)不挂, owner 私聊保持全速。
- turnPermissionPolicyFor: (event) =>
- event.speaker ? createTelegramGuestTurnPermissionPolicy(event.messageId) : undefined,
+ turnPermissionPolicyFor: (event) => {
+ if (!event.speaker) return undefined;
+ const policy = createTelegramGuestTurnPermissionPolicy(event.messageId);
+ if (event.speaker.isOwner) ownerGroupTurnPolicies.add(policy);
+ return policy;
+ },
+ // Full access 是 owner 对这条任务的明确授权。该档下各 Agent 的工具调用不会
+ // 冒泡到 host,逐轮强确认策略无法兑现;owner 触发时取缔策略,避免 provider
+ // 启动前报不支持。非 owner 仍保留策略并 fail-closed,不能借同一群任务的
+ // Full access 直接驱动工具。其它权限档与群上下文隔离都不受影响。
+ turnPolicyOptionalForMode: (mode, policy) =>
+ mode === 'bypassPermissions' && ownerGroupTurnPolicies.has(policy),
groupHistoryAccessFor: (event): GroupHistoryAccessScope => {
const lane = decodeTelegramLaneUserId(event.senderId);
const provider = `telegram-personal:${event.contextId}`;
diff --git a/apps/desktop/src/main/im/telegram/permissionPolicy.ts b/apps/desktop/src/main/im/telegram/permissionPolicy.ts
index 98aa2a359c..e296894011 100644
--- a/apps/desktop/src/main/im/telegram/permissionPolicy.ts
+++ b/apps/desktop/src/main/im/telegram/permissionPolicy.ts
@@ -4,15 +4,16 @@ import { channelForceConfirmToolCall } from '../shared/channelToolPolicy';
/**
* 群轮次的 per-turn 收紧(D1/D2, 2026-07-30 一群一会话版; review 修订后
- * **所有群轮次**都挂, 含 owner 触发 — 群窗口/引用块携带成员可控文本, 注入
+ * 除显式 Full access 外的所有群轮次都挂, 含 owner 触发 — 群窗口/引用块携带成员可控文本, 注入
* 可借 owner 轮次的宽松档执行危险操作)。读/搜/答自由通过; 破坏性调用与
* 不透明写(file_change / permissions 升权)强制弹确认卡, 而卡片点击只认
* owner — 即"谁都能问, 动手要主人拍板"。
*
* 判定逻辑与个人微信 / 钉钉共用 channelForceConfirmToolCall(嵌套解包覆盖
* Claude call_tool、Codex MCP elicitation 与 Pi 桥接 MCP / 二级分派插件)。
- * 会话权限档为 acceptEdits/bypassPermissions 时 maker 会拒绝本策略(fail-closed):
- * guest 轮次直接报错不跑, 不会放开。
+ * maker 不支持某个会话权限档时会拒绝本策略(fail-closed), 不会静默放开。
+ * 唯一例外是用户显式选择 Full access(bypassPermissions): adapter 会在 dispatch
+ * 前取缔本策略, 直接按该档执行;群历史 lane 隔离仍独立生效。
*/
export function createTelegramGuestTurnPermissionPolicy(taskId: string): TurnPermissionPolicy {
return {
diff --git a/apps/desktop/src/main/im/telegram/uiText.ts b/apps/desktop/src/main/im/telegram/uiText.ts
index ec1182a5e9..80d67cf049 100644
--- a/apps/desktop/src/main/im/telegram/uiText.ts
+++ b/apps/desktop/src/main/im/telegram/uiText.ts
@@ -18,10 +18,10 @@ export const ui = {
slash: {
start:
'👋 你好,我是你的个人 Cindy 助理~\n\n私聊直接发消息就行;群里 @ 我或回复我的消息才会触发。发 /help 看全部命令。',
- new: '🌱 新对话已开 — 之前的上下文清掉了,从头聊~',
+ new: '🌱 新任务已创建 — 已在任务列表显示,从头开始吧~',
help: `🤖 我能帮你做这些:
-/new 开个新对话(清掉当前上下文;群里发就重置这个群话题的上下文)
+/new 创建新任务(旧任务保留;群里按当前群话题创建)
/project 切到某个项目目录干活(在 bot 这边跑,不接管 desktop)
/session 列最近的 desktop 任务,点一个直接接管续聊
/model 换个模型上场
@@ -62,7 +62,7 @@ export const ui = {
const message = `⚠️ 当前 Telegram 对话使用供应商「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
- : `${message}\n“新对话配置”只影响新对话;修改后请发送 \`/new\`,再继续聊天。`;
+ : `${message}\n“新对话配置”会用于新任务;修改后请发送 \`/new\`,再继续聊天。`;
},
controlInProgress:
'🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
@@ -88,6 +88,12 @@ export const ui = {
`其它部分收到啦,正在处理~`,
},
+ error: {
+ agentUnsupported: '🤔 当前 Agent 无法在 Telegram 群里完成所需的权限确认,请换一个 Agent 再试。',
+ permissionModeUnsupported:
+ '🤔 当前权限设置无法用于这条 Telegram 群对话。发 /permission 换成「自动审批」后再试。',
+ },
+
cards: {
permission: {
title: (toolName: string) => `🔧 工具调用:${toolName}`,
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index c12b2163da..1682fbb606 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -42,6 +42,8 @@ CREATE TABLE sessions (
agent_kind TEXT NOT NULL DEFAULT 'cc',
orca_role TEXT,
source TEXT NOT NULL DEFAULT 'desktop',
+ im_bot_context_id TEXT,
+ im_user_id TEXT,
remote_host_id TEXT,
active_turn_started_at INTEGER,
last_turn_ended_at INTEGER,
@@ -2399,6 +2401,109 @@ describe('db worker tx handlers', () => {
});
});
+ it('im.rotateSession atomically inserts the new route and retires the previous task', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 'telegram-old');
+ await client.exec(
+ `UPDATE sessions
+ SET source = 'telegram', im_bot_context_id = 'bot', im_user_id = 'user'
+ WHERE id = 'telegram-old'`,
+ );
+ await client.exec(
+ `INSERT INTO im_bindings (
+ channel, bot_context_id, user_id, scope_key, target_session_id, attached_at
+ ) VALUES ('telegram', 'bot', 'user', '', 'telegram-old', 100)`,
+ );
+
+ const result = await client.tx('im.rotateSession', {
+ previousSessionId: 'telegram-old',
+ detachBinding: {
+ channel: 'telegram',
+ botContextId: 'bot',
+ userId: 'user',
+ scopeKey: '',
+ targetSessionId: 'telegram-old',
+ },
+ session: {
+ id: 'telegram-new',
+ title: 'TG · New',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ model: 'grok-4.6',
+ effort: 'high',
+ permissionMode: 'bypassPermissions',
+ fastMode: false,
+ agentKind: 'pi',
+ providerId: 'xai',
+ source: 'telegram',
+ imBotContextId: 'bot',
+ imUserId: 'user',
+ },
+ now: 500,
+ });
+
+ expect(result).toEqual({ previousStatus: 'active' });
+ await expect(
+ client.query(
+ `SELECT id, status, im_bot_context_id, im_user_id
+ FROM sessions WHERE id IN ('telegram-old', 'telegram-new') ORDER BY id`,
+ ),
+ ).resolves.toEqual([
+ {
+ id: 'telegram-new',
+ status: 'active',
+ im_bot_context_id: 'bot',
+ im_user_id: 'user',
+ },
+ {
+ id: 'telegram-old',
+ status: 'archived',
+ im_bot_context_id: null,
+ im_user_id: null,
+ },
+ ]);
+ await expect(client.query('SELECT * FROM im_bindings')).resolves.toEqual([]);
+ });
+ });
+
+ it('im.rotateSession never revives a concurrently deleted previous task', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 'telegram-deleted');
+ await client.exec(
+ `UPDATE sessions
+ SET status = 'deleted', source = 'telegram',
+ im_bot_context_id = 'bot', im_user_id = 'user'
+ WHERE id = 'telegram-deleted'`,
+ );
+
+ const result = await client.tx('im.rotateSession', {
+ previousSessionId: 'telegram-deleted',
+ detachBinding: null,
+ session: {
+ id: 'telegram-after-delete',
+ title: 'TG · New',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ model: 'grok-4.6',
+ effort: 'high',
+ permissionMode: 'bypassPermissions',
+ fastMode: false,
+ agentKind: 'pi',
+ providerId: 'xai',
+ source: 'telegram',
+ imBotContextId: 'bot',
+ imUserId: 'user',
+ },
+ now: 600,
+ });
+
+ expect(result).toEqual({ previousStatus: 'deleted' });
+ await expect(
+ client.queryOne('SELECT status FROM sessions WHERE id = ?', ['telegram-deleted']),
+ ).resolves.toEqual({ status: 'deleted' });
+ });
+ });
+
it('im.deleteBindings rolls back every startup cleanup when a later delete fails', async () => {
await withClient(async (client) => {
await seedSession(client, 'desktop-target');
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 75d8789426..73252ccbfd 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -29,6 +29,7 @@ export type DbTxName =
| 'message.delete'
| 'im.deleteBindings'
| 'im.replaceBinding'
+ | 'im.rotateSession'
| 'wechatActivateBindingEpoch'
| 'wechatCommitPollBatch'
| 'wechatLeaseNextTask'
@@ -806,6 +807,37 @@ export interface WechatUnbindCleanupResult {
filePaths: string[];
}
+export interface ImRotateSessionArgs {
+ previousSessionId: string | null;
+ detachBinding: {
+ channel: string;
+ botContextId: string;
+ userId: string;
+ scopeKey: string;
+ targetSessionId: string;
+ } | null;
+ session: {
+ id: string;
+ title: string;
+ workingDir: string;
+ workspaceKind: 'project' | 'dialogue';
+ model: string;
+ effort: string;
+ permissionMode: string;
+ fastMode: boolean;
+ agentKind: string;
+ providerId: string | null;
+ source: string;
+ imBotContextId: string;
+ imUserId: string;
+ };
+ now: number;
+}
+
+export interface ImRotateSessionResult {
+ previousStatus: 'active' | 'archived' | 'deleted' | null;
+}
+
export type DbTxArgsByName = {
'codex.importMessages': CodexImportMessagesArgs;
'claude.importMessages': ClaudeImportMessagesArgs;
@@ -837,6 +869,7 @@ export type DbTxArgsByName = {
'message.delete': MessageDeleteArgs;
'im.deleteBindings': ImDeleteBindingsArgs;
'im.replaceBinding': ImReplaceBindingArgs;
+ 'im.rotateSession': ImRotateSessionArgs;
wechatActivateBindingEpoch: WechatActivateBindingEpochArgs;
wechatCommitPollBatch: WechatCommitPollBatchArgs;
wechatLeaseNextTask: WechatLeaseNextTaskArgs;
@@ -888,6 +921,7 @@ export type DbTxResultByName = {
'message.delete': MessageDeleteResult;
'im.deleteBindings': undefined;
'im.replaceBinding': undefined;
+ 'im.rotateSession': ImRotateSessionResult;
wechatActivateBindingEpoch: WechatActivateBindingEpochResult;
wechatCommitPollBatch: WechatCommitPollBatchResult;
wechatLeaseNextTask: WechatLeasedTask | null;
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 6fda1f95e1..af60dadee0 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -96,6 +96,8 @@ export function tx(db: Database.Database, args: unknown): unknown {
return imDeleteBindings(db, txArgs);
case 'im.replaceBinding':
return imReplaceBinding(db, txArgs);
+ case 'im.rotateSession':
+ return imRotateSession(db, txArgs);
case 'wechatActivateBindingEpoch':
return wechatActivateBindingEpoch(db, txArgs);
case 'wechatCommitPollBatch':
@@ -852,6 +854,77 @@ function compactSessionToolResults(
})();
}
+function imRotateSession(
+ db: Database.Database,
+ args: unknown,
+): { previousStatus: 'active' | 'archived' | 'deleted' | null } {
+ const payload = asRecord(args, 'im.rotateSession args');
+ const session = asRecord(payload.session, 'im.rotateSession session');
+ const previousSessionId = nullableString(payload.previousSessionId);
+ const detachBinding = payload.detachBinding === null
+ ? null
+ : asRecord(payload.detachBinding, 'im.rotateSession detachBinding');
+ const now = expectNumber(payload.now, 'now');
+ const readPrevious = db.prepare('SELECT status FROM sessions WHERE id = ? LIMIT 1');
+ const insertCurrent = db.prepare(
+ `INSERT INTO sessions (
+ id, title, working_dir, workspace_kind, model, effort, permission_mode,
+ fast_mode, status, agent_kind, provider_id, source, im_bot_context_id,
+ im_user_id, created_at, updated_at, user_send_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?)`,
+ );
+ const retirePrevious = db.prepare(
+ `UPDATE sessions
+ SET status = CASE WHEN status = 'deleted' THEN 'deleted' ELSE 'archived' END,
+ im_bot_context_id = NULL,
+ im_user_id = NULL,
+ updated_at = ?
+ WHERE id = ?`,
+ );
+ const deleteBinding = db.prepare(
+ `DELETE FROM im_bindings
+ WHERE channel = ? AND bot_context_id = ? AND user_id = ? AND scope_key = ?
+ AND target_session_id = ?`,
+ );
+ return db.transaction(() => {
+ const previous = previousSessionId === null
+ ? undefined
+ : readPrevious.get(previousSessionId) as { status: string } | undefined;
+ insertCurrent.run(
+ expectString(session.id, 'session.id'),
+ expectString(session.title, 'session.title'),
+ expectString(session.workingDir, 'session.workingDir'),
+ expectString(session.workspaceKind, 'session.workspaceKind'),
+ expectString(session.model, 'session.model'),
+ expectString(session.effort, 'session.effort'),
+ expectString(session.permissionMode, 'session.permissionMode'),
+ session.fastMode === true ? 1 : 0,
+ expectString(session.agentKind, 'session.agentKind'),
+ nullableString(session.providerId),
+ expectString(session.source, 'session.source'),
+ expectString(session.imBotContextId, 'session.imBotContextId'),
+ expectString(session.imUserId, 'session.imUserId'),
+ now,
+ now,
+ now,
+ );
+ if (previousSessionId !== null) retirePrevious.run(now, previousSessionId);
+ if (detachBinding !== null) {
+ deleteBinding.run(
+ expectString(detachBinding.channel, 'detachBinding.channel'),
+ expectString(detachBinding.botContextId, 'detachBinding.botContextId'),
+ expectString(detachBinding.userId, 'detachBinding.userId'),
+ expectString(detachBinding.scopeKey, 'detachBinding.scopeKey'),
+ expectString(detachBinding.targetSessionId, 'detachBinding.targetSessionId'),
+ );
+ }
+ const status = previous?.status;
+ const previousStatus: 'active' | 'archived' | 'deleted' | null =
+ status === 'active' || status === 'archived' || status === 'deleted' ? status : null;
+ return { previousStatus };
+ })();
+}
+
function codexImportMessages(db: Database.Database, args: unknown): { changed: number } {
const payload = asRecord(args, 'codex.importMessages args');
const sessionId = expectString(payload.sessionId, 'sessionId');
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f1d8d9a58f..2463091646 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2473,7 +2473,7 @@
},
"commandMenu": {
"start": "Welcome and usage",
- "new": "Start a new chat",
+ "new": "Create a new session",
"help": "Show command help",
"stop": "Stop the current task",
"session": "Recent sessions, pick one to continue",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 30d76c846c..f229828f4a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2472,7 +2472,7 @@
},
"commandMenu": {
"start": "ようこそと使い方を表示",
- "new": "新しい会話を開始",
+ "new": "新しいセッションを作成",
"help": "コマンドヘルプを表示",
"stop": "現在のタスクを停止",
"session": "最近のセッション一覧から続行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 863e8ffda7..c074ce994b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2472,7 +2472,7 @@
},
"commandMenu": {
"start": "환영 메시지와 사용법 보기",
- "new": "새 대화 시작",
+ "new": "새 세션 만들기",
"help": "명령어 도움말 보기",
"stop": "현재 작업 중지",
"session": "최근 세션 목록에서 이어서 대화",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 27827f0727..3815cdec2f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2472,7 +2472,7 @@
},
"commandMenu": {
"start": "查看欢迎信息和用法",
- "new": "开启新对话",
+ "new": "创建新任务",
"help": "查看命令帮助",
"stop": "中止当前执行",
"session": "最近任务列表,选中即续聊",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index b7a656a568..0b1695c08d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2472,7 +2472,7 @@
},
"commandMenu": {
"start": "檢視歡迎資訊和用法",
- "new": "開啟新對話",
+ "new": "建立新任務",
"help": "檢視命令幫助",
"stop": "中止當前執行",
"session": "最近任務列表,選中即續聊",
diff --git a/docs/product-rules/task-and-conversation-naming.md b/docs/product-rules/task-and-conversation-naming.md
index 266ab2a31c..b6eeffd1bb 100644
--- a/docs/product-rules/task-and-conversation-naming.md
+++ b/docs/product-rules/task-and-conversation-naming.md
@@ -487,30 +487,30 @@ renderer 的 `$` 指令展开、`ghost_list`、`ghost_info` 与 `ghost_call` 都
`exempt`**。所以改成「从对话中生成新记忆并在**后续对话**中召回」——用户视角真实、不含禁用
词、也不暗示任何多余动作。**遇到 reviewer 意见相反时,先看是不是这个名词本身选错了。**
-#### 6.0.3 `/new` 不产生新任务:按落库行为定名,不按命令名字
+#### 6.0.3 `/new` 按各渠道的落库行为定名,不按命令名字
-IM 渠道的 `/new` 看着像「新建」,实际走 `im/shared/sessionRepo.ts::resetSessionToDefaults` ——
-`db.update(sessions).where(eq(sessions.id, …))`:**保留同一条 session 行**,只清 `sdkSessionId`、
-按渠道默认重置工作目录与上下文。侧边栏里的条目数不变,也没有新条目可以单独打开。
+`/new` 已经不是所有 IM 共用一种落库语义:
-所以凡是描述这条路径的中文,一律说**「新对话」**。说「新任务」会让用户去侧边栏找一条根本不
-存在的新条目。这条不变量的全部对称路径:
+- 两个 Telegram bot 都会 `INSERT` 一条新的 session 行、归档旧任务,并立即把新任务显示在
+ 任务列表里。因此 Telegram 的成功提示、帮助与命令菜单一律说**「新任务」**;英文用
+ `new session`,日文、韩文也使用各自的 Session 术语。
+- 其它 IM 渠道仍走 `im/shared/sessionRepo.ts::resetSessionToDefaults`:
+ `db.update(sessions).where(eq(sessions.id, …))`,保留同一条 session 行,只清 `sdkSessionId`、
+ 按渠道默认重置工作目录与上下文。侧边栏条目数不变,所以这些渠道继续说**「新对话」**。
+
+这条不变量的全部对称路径:
| 触点 | 底层 | 说法 |
|---|---|---|
| IM 平台**首次**私聊 | `INSERT` 新 session 行 | 确实是新任务 |
-| 已有私聊发 `/new` | `UPDATE` 原行 | **不是**新任务 |
+| Telegram 已有私聊/群聊发 `/new` | `INSERT` 新 session 行并归档旧任务 | **新任务** |
+| 其它 IM 已有私聊发 `/new` | `UPDATE` 原行 | **新对话,不是新任务** |
| 消息操作菜单 fork | `INSERT` 新 session 行 | 确实是新任务(「开启一个新任务」) |
| `/ctr` → ➕ 新建 | `INSERT` 新 session 行 | 确实是新任务 |
-前两条**共用同一份设置、同一句文案**,所以文案必须取两者都成立的说法 = 「新对话」。落地时
-这一族被指出过三轮,每轮漏一处:`settings.imBot.defaults.*`(设置项标题)→
-`settings.wechatBot.workingDir.*` 与 `toasts.workingDir*`(工作目录那组)→
-`settings.telegramBot.commandMenu.new`(Telegram 斜杠菜单说明)。**判据一律回到落库行为。**
-
-英文侧同理:`Start a new session` 也不准确,已一并改成 `Start a new chat`(ja「新しい会話を
-開始」/ ko「새 대화 시작」)。en 的 `session` 词义比中文「任务」宽、读起来不刺眼,但既然中文
-已按落库行为定名,四语就该说同一件事(§4.2)。
+设置项可以继续描述跨渠道共用的「新对话配置」,但 Telegram 的执行结果必须明确是新任务;
+其它 IM 的 `/new` 文案不得跟随 Telegram 一起改成「新任务」。**判据一律回到各渠道当前的落库
+行为。**
#### 6.0.4 兄弟渠道必须成组改:一处 IM 文案改动 = 四个包一起过
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 25dc7a0053..3b51fd43ac 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -97,11 +97,20 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
过程阶段的载体差异(个人在聊天记录里、官方私聊在输入框草稿里)已经裁决过,见下节。
+`/new` 是两侧共同的不变量:命令成功时必须已经创建一个新的 Cindy **任务**并立刻出现在
+任务列表,随后消息路由到这个新任务;旧任务保留为历史,不得复用原任务 ID、只清 SDK
+上下文,也不得拖到下一条普通消息才落任务。新任务的 agent、模型、来源、思考强度和权限档
+均在执行 `/new` 时从各自入口的当前默认配置重新解析;当前项目目录作为 lane 偏好保留。
+两侧的成功提示、帮助与命令菜单都必须按这个真实结果称为「新任务」,不得沿用旧的
+「新对话/清掉上下文」说法。
+官方 bot 通过 `session-new-v1` 双向能力协商执行立即创建,滚动升级时旧 Desktop 才退回旧的
+“下一条消息懒创建”行为。
+
## 三、有意不同(已裁决,不要"统一")
| 差异 | 官方 | 个人 | 裁决与理由 |
|---|---|---|---|
-| 群轮次权限档 | 完全按用户配的走 | 所有群轮次强制确认破坏性操作 | Chris 2026-08-03 实踩裁决:用户选了「完全访问」,官方 bot 却在群里静默跑 `ask` 并弹卡,设置与实际对不上。**完全访问就是完全访问**,不得在运行期另起一套隐式权限配置。官方 bot 的群聊定位是引导用户装自己的个人 bot,不承担「群里多人共用一个 bot」的权限模型——那套已在个人 bot 里设计过。见 `hook-control/session-runner.ts` |
+| 群轮次权限档 | 完全按用户配的走 | 除「完全访问」外仍强制确认破坏性操作;「完全访问」只让 owner 触发的轮次按该档直接执行,非 owner 的群消息继续保留逐轮策略并 fail-closed | Chris 2026-09-04 实踩裁决:个人 bot 的群任务已经明确设成 Pi + Grok + Full access,Cindy 侧能继续对话,Telegram 却因额外挂的逐轮策略与 Full access 互斥而在模型启动前拒绝每条消息。**owner 明确选择的完全访问必须正常执行,但不能把这份授权扩给同群其他成员**;个人侧在 `bypassPermissions` 下仅对 owner 触发的 policy 通过 `turnPolicyOptionalForMode` 取缔逐轮策略,非 owner、其它权限档的群护栏与群历史 lane 隔离照常保留。官方侧继续完全按用户配置,不改服务端行为。见 `hook-control/session-runner.ts`、`im/telegram/adapter.ts` 与 `im/shared/turnRunner.ts` |
| 私聊过程态的载体 | Telegram **草稿**(`sendDraft`),终稿一发草稿自然消失 | 真实消息,原地 `editMessageText` 覆盖 | 草稿只有官方路径拿得到。个人栈**不是零推送**:惰性占位让「没有真实内容就不建消息」,但**第一帧真实内容那次 `sendMessage` 会推送**,之后的编辑才不推送。`presentationCapabilities.ts` 的 `progressSilent: true` 说的是「过程帧不额外推送」,不是「整轮零推送」 |
| `/status` | 有 | 无 | 官方 bot 经服务端中继,链路可断,所以有「关联状态」可看;个人 bot 由桌面直连 Bot API,没有等价概念。见注册表 `parityNote` |
| `/unlink` | 有 | 无 | 官方 bot 的关联由服务端持有;个人 bot 的 token 是用户自填的,解绑入口在桌面设置页 |
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts
index e393e6968c..5a9550323d 100644
--- a/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts
@@ -170,6 +170,28 @@ describe('v2 新帧 round-trip', () => {
roundTrip(
makeQueryResponse({ queryId: 'q-3', kind: 'models', ok: false, error: 'device busy' }),
);
+ roundTrip(
+ makeQueryRequest({
+ queryId: 'q-new',
+ kind: 'session-new',
+ sessionNew: {
+ previousExternalKey: 'telegram:dm:1:g1',
+ externalKey: 'telegram:dm:1:g2',
+ workspace: 'cindy',
+ options: { agentKind: 'pi', model: 'grok-4.6', permissionMode: 'bypassPermissions' },
+ source: { im: 'telegram', userText: '' },
+ },
+ }),
+ );
+ roundTrip(
+ makeQueryResponse({
+ queryId: 'q-new',
+ kind: 'session-new',
+ ok: true,
+ error: null,
+ sessionId: 'new-task-id',
+ }),
+ );
});
it('task.cancel', () => {
diff --git a/packages/slack-hook-protocol/src/parse.ts b/packages/slack-hook-protocol/src/parse.ts
index e10cca7f76..83373558cc 100644
--- a/packages/slack-hook-protocol/src/parse.ts
+++ b/packages/slack-hook-protocol/src/parse.ts
@@ -782,6 +782,27 @@ function validateQueryRequest(p: Record<string, unknown>): string | null {
if (!QUERY_KINDS.includes(p.kind as never)) {
return `query.request.kind must be one of: ${QUERY_KINDS.join(', ')}`;
}
+ if (p.kind === 'session-new') {
+ if (!isPlainObject(p.sessionNew)) {
+ return 'query.request.sessionNew must be an object when kind is session-new';
+ }
+ const request = p.sessionNew;
+ if (!isNonEmptyString(request.previousExternalKey)) {
+ return 'query.request.sessionNew.previousExternalKey must be a non-empty string';
+ }
+ if (!isNonEmptyString(request.externalKey)) {
+ return 'query.request.sessionNew.externalKey must be a non-empty string';
+ }
+ if (request.externalKey === request.previousExternalKey) {
+ return 'query.request.sessionNew.externalKey must differ from previousExternalKey';
+ }
+ if (!isNonEmptyString(request.workspace)) {
+ return 'query.request.sessionNew.workspace must be a non-empty string';
+ }
+ const optErr = validateDispatchOptions(request.options);
+ if (optErr) return optErr;
+ return validateSource(request.source);
+ }
return null;
}
@@ -881,7 +902,10 @@ function validateQueryResponse(p: Record<string, unknown>): string | null {
return null;
}
if (kind === 'models') return validateAgentModels(p.agents);
- return validateQuerySessions(p.sessions);
+ if (kind === 'sessions') return validateQuerySessions(p.sessions);
+ return isNonEmptyString(p.sessionId)
+ ? null
+ : 'query.response.sessionId must be a non-empty string when kind is session-new';
}
function validateTaskCancel(p: Record<string, unknown>): string | null {
diff --git a/packages/slack-hook-protocol/src/types.ts b/packages/slack-hook-protocol/src/types.ts
index 2a689b01da..acea063867 100644
--- a/packages/slack-hook-protocol/src/types.ts
+++ b/packages/slack-hook-protocol/src/types.ts
@@ -854,7 +854,7 @@ export type ProviderBindStatePayload = ProviderBindStatusPayload;
// ── 阶段 6(v2): 实时问答 ────────────────────────────────────────────────────
/** 可查询的清单种类。 */
-export const QUERY_KINDS = ['workspaces', 'models', 'sessions'] as const;
+export const QUERY_KINDS = ['workspaces', 'models', 'sessions', 'session-new'] as const;
export type QueryKind = (typeof QUERY_KINDS)[number];
/**
@@ -864,6 +864,14 @@ export type QueryKind = (typeof QUERY_KINDS)[number];
export interface QueryRequestPayload {
queryId: string;
kind: QueryKind;
+ /** kind=session-new: create and bind a blank task immediately for `/new`. */
+ sessionNew?: {
+ previousExternalKey: string;
+ externalKey: string;
+ workspace: string;
+ options?: TaskDispatchOptions;
+ source?: TaskSource;
+ };
}
/**
@@ -926,6 +934,8 @@ export interface QueryResponsePayload {
agents?: QueryAgentModels[];
/** kind=sessions 且 ok 时必填: at most 20 privacy-minimised entries. */
sessions?: QuerySessionEntry[];
+ /** kind=session-new 且 ok 时必填。 */
+ sessionId?: string;
}
// ── 阶段 7(v2): 任务取消 ────────────────────────────────────────────────────
@@ -1269,6 +1279,9 @@ export const HOOK_FEATURE_PROVIDER_BEHAVIOR = 'provider-behavior-v1';
/** Both peers must advertise this before query.kind=sessions is used. */
export const HOOK_FEATURE_SESSION_PICKER = 'session-picker-v1';
+/** Both peers support immediate blank-task creation for provider `/new`. */
+export const HOOK_FEATURE_SESSION_NEW = 'session-new-v1';
+
/** Server capability announcing that its provider registry enables Telegram. */
export const HOOK_FEATURE_PROVIDER_TELEGRAM = 'provider:telegram';