Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ A Bot inherits the optional global default, selects one complete shared template
## Sub-features

- `library`: Bot settings → Auto approval → Global default template (DSH Select), existing template library and Reviewer model. No global default means inherited review is off. Read failures remain errors.
- `editor`: New template requires Blank or one selected source; edit independent Always ask/Always allow rows in the same grouped card list as External identities/connectors (outer top/bottom corners, straight middle joins), plus free text; save alone or apply to a named Bot. Copy a custom or built-in template independently; shared-original editing lists actual users including global inheritors. Read back full content and selection through CLI.
- `editor`: New template requires Blank or one selected source; edit independent Always ask/Always allow rows in the same grouped card list as External identities/connectors (outer top/bottom corners, straight middle joins, distinct list fill and spaced headings); top-right and bottom add actions append a draft row and focus/reveal its input, plus free text; save alone or apply to a named Bot. Copy a custom or built-in template independently; shared-original editing lists actual users including global inheritors. Read back full content and selection through CLI.
- `cli`: `approval-template list --bot <bot>`, `approval-template-global-set <name|off>`, `approval-template-set <bot> <inherit|name|off>`; library create/edit commands retain existing Markdown contents.
- `select`: Channel settings → Auto approval, or composer Workspace Grants panel → Auto approval, uses the same DSH Select. Inheritance shows its effective global source. Specific selection replaces global; Off retains deterministic rules.
- `mobile`: Bot profile → Settings → Permissions → Workspace grants → Auto approval template, inside the existing iOS sheet / Android `ModalBottomSheet`. Inherit global shows the resolved global template (or Off); selecting Off then Inherit global writes null then @global through the same Host owner. Legacy Hosts without a global-selection field retain their supported choices.
Expand Down
11 changes: 11 additions & 0 deletions changes/4244-rule-number-alignment.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
section: Fixed
---

## en

- Improved approval-template rule lists with aligned numbers, clearer section spacing and surfaces, and top/bottom add actions that focus the new row ([#4244](https://github.com/BotHarness/DeepSeekBot/issues/4244)).

## zh

- 改善审批模板规则列表:序号对齐文字,增加标题间距和底色区分,顶部与底部均可添加并聚焦新条目([#4244](https://github.com/BotHarness/DeepSeekBot/issues/4244))。
150 changes: 98 additions & 52 deletions packages/client/src/client/approval-template-library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
type BridgeCall,
} from './bridge.js';
import { Callout } from './ds/callout.js';
import { Field, FieldStack, TextAreaField, TextField } from './ds/field.js';
import { FieldStack, TextAreaField, TextField } from './ds/field.js';
import { ConfirmDialog, DangerTextButton, FormDialog } from './ds/form-dialog.js';
import { Note } from './ds/note.js';
import { ReadFailure } from './ds/read-failure.js';
Expand Down Expand Up @@ -52,6 +52,22 @@ const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;

const styles = stylex.create({
meta: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: space.x2 },
ruleSection: { margin: 0, padding: 0, borderWidth: 0, minWidth: 0 },
ruleLegend: { width: '100%', padding: 0, marginBottom: space.x3 },
ruleHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: space.x3,
color: color.fg,
fontSize: text.bodySize,
lineHeight: text.bodyLine,
fontWeight: text.strong,
},
ruleList: { backgroundColor: color.surface },
freeTextLabel: { display: 'inline-block', paddingBottom: space.x2 },
ruleMain: { alignItems: 'baseline' },
ruleNumber: { fontSize: text.bodySize, lineHeight: text.bodyLine },
ruleInput: {
boxSizing: 'border-box',
width: '100%',
Expand Down Expand Up @@ -100,6 +116,7 @@ function GuidanceFields({
onChange(text: string): void;
t: BotHarnessTranslate;
}): ReactElement {
const focusAddedRow = useRef<{ section: 'alwaysAsk' | 'alwaysAllow'; index: number }>();
const parts = decodeApprovalTemplateGuidance(text);
const update = (next: ApprovalTemplateGuidance): void =>
onChange(encodeApprovalTemplateGuidance(next));
Expand All @@ -112,62 +129,91 @@ function GuidanceFields({
? 'autoApproval.library.alwaysAsk'
: 'autoApproval.library.alwaysAllow',
);
const addRow = (): void => {
focusAddedRow.current = { section: key, index: parts[key].length };
update({ ...parts, [key]: [...parts[key], ''] });
};
const addLabel = t('autoApproval.library.addRow', { section: label });
return (
<Field key={key} label={label} group>
{() => (
<SidebarCardList label={label}>
{parts[key].map((row, index) => {
const rowLabel = label + ' ' + String(index + 1);
return (
<SidebarCardRow
key={index}
leading={<span aria-hidden>{index + 1}</span>}
title={
<Input
aria-label={rowLabel}
className={stylex.props(styles.ruleInput).className ?? ''}
value={row}
onChange={(event) =>
update({
...parts,
[key]: parts[key].map((item, position) =>
position === index ? event.currentTarget.value : item,
),
})
}
/>
}
trailing={
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t('autoApproval.library.removeRow') + ' · ' + rowLabel}
onClick={() =>
update({
...parts,
[key]: parts[key].filter((_, position) => position !== index),
})
<fieldset key={key} aria-label={label} {...stylex.props(styles.ruleSection)}>
<legend {...stylex.props(styles.ruleLegend)}>
<span {...stylex.props(styles.ruleHeader)}>
<span>{label}</span>
<Button
type="button"
variant="ghost"
size="sm"
aria-label={addLabel}
data-approval-guidance-add={key}
onClick={addRow}
>
<ChannelSidebarIcon name="plus" size={16} />
{t('autoApproval.library.add')}
</Button>
</span>
</legend>
<SidebarCardList label={label} className={stylex.props(styles.ruleList).className}>
{parts[key].map((row, index) => {
const rowLabel = label + ' ' + String(index + 1);
return (
<SidebarCardRow
key={index}
mainClassName={stylex.props(styles.ruleMain).className}
leading={
<span aria-hidden {...stylex.props(styles.ruleNumber)}>
{index + 1}
</span>
}
title={
<Input
ref={(input) => {
const pending = focusAddedRow.current;
if (input && pending?.section === key && pending.index === index) {
focusAddedRow.current = undefined;
input.focus();
}
>
<ChannelSidebarIcon name="x" size={16} />
</Button>
}
/>
);
})}
<SidebarCardRow
icon="plus"
title={t('autoApproval.library.addRow', { section: label })}
onClick={() => update({ ...parts, [key]: [...parts[key], ''] })}
/>
</SidebarCardList>
)}
</Field>
}}
aria-label={rowLabel}
className={stylex.props(styles.ruleInput).className ?? ''}
value={row}
onChange={(event) =>
update({
...parts,
[key]: parts[key].map((item, position) =>
position === index ? event.currentTarget.value : item,
),
})
}
/>
}
trailing={
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t('autoApproval.library.removeRow') + ' · ' + rowLabel}
onClick={() =>
update({
...parts,
[key]: parts[key].filter((_, position) => position !== index),
})
}
>
<ChannelSidebarIcon name="x" size={16} />
</Button>
}
/>
);
})}
<SidebarCardRow icon="plus" title={addLabel} onClick={addRow} />
</SidebarCardList>
</fieldset>
);
})}
<TextAreaField
label={t('autoApproval.library.freeText')}
label={
<span {...stylex.props(styles.freeTextLabel)}>{t('autoApproval.library.freeText')}</span>
}
hint={t('autoApproval.library.freeTextHint')}
value={parts.freeText}
rows={8}
Expand Down
2 changes: 2 additions & 0 deletions packages/client/src/client/locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4469,6 +4469,7 @@ export const zh = {
'autoApproval.library.guidanceHint':
'这些是 Reviewer 的自然语言指导,不保证模型判断。总是询问优先;冲突、未覆盖或不确定时交给你。修改仅影响后续审批。',
'autoApproval.library.removeRow': '移除此行',
'autoApproval.library.add': '添加',
'autoApproval.library.addRow': '添加{section}项',
'autoApproval.library.saveChoice': '保存方式',
'autoApproval.library.saveOnly': '仅保存',
Expand Down Expand Up @@ -10579,6 +10580,7 @@ My relationship with you, established lore and topics to avoid: [fill in].
'autoApproval.library.guidanceHint':
'Natural-language Reviewer guidance cannot guarantee model decisions. Always ask takes priority; conflicts, missing coverage and uncertainty go to you. Edits affect future Reviews.',
'autoApproval.library.removeRow': 'Remove row',
'autoApproval.library.add': 'Add',
'autoApproval.library.addRow': 'Add {section} row',
'autoApproval.library.saveChoice': 'Save behavior',
'autoApproval.library.saveOnly': 'Save only',
Expand Down
76 changes: 70 additions & 6 deletions packages/client/test/approval-template-library.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import { zhTranslate as t } from '../src/client/locale.js';
import { createStore } from '../src/client/store.js';

vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({
...(await import('./primitive-mocks.js')).dialogPrimitives(),
...(await import('./primitive-mocks.js')).comboboxPrimitives(),
...(await import('./primitive-mocks.js')).dialogPrimitives(),
Tag: ({ children }: { children: ReactNode }) => createElement('span', null, children),
Menu: ({
items,
Expand Down Expand Up @@ -337,6 +337,7 @@ it.each(['immediate', 'retry'] as const)(
let deleted = false;
let writes = 0;
let reads = 0;
let absentPreviews = 0;
const call: BridgeCall = async (endpoint) => {
if (endpoint === 'approvalTemplates') {
reads++;
Expand All @@ -349,10 +350,16 @@ it.each(['immediate', 'retry'] as const)(
},
};
}
if (endpoint === 'approvalTemplateDeletePreview')
return deleted
? { ok: false, error: { code: 'unknown-template', message: 'removed', details: {} } }
: { ok: true, value: { preview: deletePreview } };
if (endpoint === 'approvalTemplateDeletePreview') {
if (deleted) {
absentPreviews++;
return {
ok: false,
error: { code: 'unknown-template', message: 'removed', details: {} },
};
}
return { ok: true, value: { preview: deletePreview } };
}
if (endpoint === 'approvalTemplateDelete') {
writes++;
deleted = true;
Expand All @@ -365,14 +372,20 @@ it.each(['immediate', 'retry'] as const)(
expect(writes).toBe(1);
if (recovery === 'retry') {
expect(trigger().textContent).toContain('读取失败');
const retry = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
const dialog = confirmDeletion().closest('[role="dialog"]');
if (!dialog) throw new Error('Missing deletion dialog');
const retry = [...dialog.querySelectorAll<HTMLButtonElement>('button')].find(
(b) => b.textContent === t('autoApproval.reload'),
);
if (!retry) throw new Error('Missing read recovery');
await act(async () => retry.click());
}
expect(host.querySelector('[data-approval-template="night-shift"]')).toBeNull();
expect(trigger().textContent).toContain(t('autoApproval.off'));
expect(document.body.textContent).not.toContain(
t('autoApproval.library.deleteTitle', { title: 'Night shift' }),
);
expect(absentPreviews).toBe(1);
expect(writes).toBe(1);
},
);
Expand Down Expand Up @@ -542,6 +555,57 @@ it('keeps the visible View action in accessible template names', async () => {
}
});

it.each(['alwaysAsk', 'alwaysAllow'] as const)(
'adds and focuses a %s rule from either end without saving or changing other sections',
async (section) => {
const parts = {
alwaysAsk: Array.from({ length: 20 }, (_, index) => 'Ask ' + String(index + 1)),
alwaysAllow: Array.from({ length: 20 }, (_, index) => 'Allow ' + String(index + 1)),
freeText: 'Keep this note.',
};
const calls: string[] = [];
const template = { ...customTemplate, usedBy: [], text: encodeApprovalTemplateGuidance(parts) };
const call: BridgeCall = async (endpoint) => {
calls.push(endpoint);
if (endpoint === 'approvalTemplates')
return { ok: true, value: { templates: [template], globalDefault: null } };
throw new Error('Adding a draft row must not write to the Host');
};
await render(call);
const edit = host.querySelector<HTMLButtonElement>(
'[data-approval-template="night-shift"] button',
);
if (!edit) throw new Error('Missing template');
await act(async () => edit.click());
const top = document.querySelector<HTMLButtonElement>(
'button[data-approval-guidance-add="' + section + '"]',
);
if (!top) throw new Error('Missing top add action');
const label = t(
section === 'alwaysAsk'
? 'autoApproval.library.alwaysAsk'
: 'autoApproval.library.alwaysAllow',
);
await act(async () => top.click());
const added = document.querySelector<HTMLInputElement>('input[aria-label="' + label + ' 21"]');
expect(added?.value).toBe('');
expect(document.activeElement).toBe(added);
await clickText(t('autoApproval.library.addRow', { section: label }));
const last = document.querySelector<HTMLInputElement>('input[aria-label="' + label + ' 22"]');
expect(last?.value).toBe('');
expect(document.activeElement).toBe(last);
const other = t(
section === 'alwaysAsk'
? 'autoApproval.library.alwaysAllow'
: 'autoApproval.library.alwaysAsk',
);
expect(document.querySelector('input[aria-label="' + other + ' 21"]')).toBeNull();
expect(document.querySelector('textarea')?.value).toBe(parts.freeText);
expect(calls).toEqual(['approvalTemplates']);
expect(decodeApprovalTemplateGuidance(template.text)).toEqual(parts);
},
);

it('edits and removes independent guidance cards without changing neighbouring rules or applying', async () => {
let template = {
name: 'qa-rules',
Expand Down
12 changes: 6 additions & 6 deletions packages/core/test/team-approvals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1173,12 +1173,12 @@ describe('M5 approval projections and decisions', () => {
expect(() =>
f.team.approvals.requireRequest(bob, memberDm.id, request.messageId),
).toThrow();
masked(
f.team.approvals.project(bob, {
channelId: memberDm.id,
message: f.channels.message(memberDm.id, request.messageId),
}),
);
const projection = f.team.approvals.project(bob, {
channelId: memberDm.id,
message: f.channels.message(memberDm.id, request.messageId),
});
masked(projection);
expect(JSON.stringify(projection)).not.toContain('PARTICIPANT_PRIVATE_INPUT');
}
expect(JSON.stringify(f.channels.readMessages(principalDm.id))).not.toContain(
'PARTICIPANT_',
Expand Down
21 changes: 18 additions & 3 deletions packages/core/test/tob-cli-invocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,23 +419,38 @@ describe('owned model-free Tob CLI invocation', () => {
const f = await fixture();
let shouldDelegate = false;
let captured: ToolExecution | undefined;
let retainedExpiry: Promise<void> | undefined;
let resumeExpired: (() => void) | undefined;
const expiryReady = new Promise<void>((resolve) => {
resumeExpired = resolve;
});
f.ctx.on(
'tools/pre-execute',
async (execution) => {
captured = execution;
expect(f.authority.delegate(execution)).toBe(shouldDelegate ? 'delegated' : 'refused');
if (shouldDelegate) {
expect(() => f.authority.require(execution)).not.toThrow();
retainedExpiry = (async () => {
await expiryReady;
expect(() => f.authority.require(execution)).toThrow();
})();
}
return { kind: 'deny', reason: 'Origin probe completed before body' };
},
{ global: true, prepend: true },
);
await f.native();
shouldDelegate = true;
await f.authority.run(f.input, () => f.native());
if (!captured) throw new Error('Native executor did not enter policy');
const admitted = captured;
expect(() => f.authority.require(admitted)).toThrow();
if (!retainedExpiry || !resumeExpired) throw new Error('Missing retained invocation context');
resumeExpired();
await retainedExpiry;
shouldDelegate = false;
await f.native();
if (!captured) throw new Error('Native executor did not enter policy');
const expired = captured;
expect(() => f.authority.require(expired)).toThrow();
expect(f.runHost).not.toHaveBeenCalled();
});

Expand Down
Loading