Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(work): show branch and state icon on GitHub Work cards (#22242)

AmAzing-86a436a80b3b
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.md
index 80b88863eb4..b32cc36ee1f 100644
--- a/.agents/skills/agent-work/SKILL.md
+++ b/.agents/skills/agent-work/SKILL.md
@@ -102,6 +102,8 @@ The whole scan returns `{attempted, failed}` and the completion backstop (`Compl
- **`owner/repo#number` is the canonical github identity**, not node_id: the gh CLI surface never returns node_id, and the same entity touched via REST tools and CLI must land on one Work row.
- **stdout is the source of truth for identity** on the CLI path (`gh … create/edit` prints the entity URL); the command's edit target is the fallback. The LAST gh create/edit segment of a chained command owns the trailing URL.
- **Persisted URLs are http(s)-allowlisted** (`sanitizeExternalUrl`): gh stdout / tool results are member-controlled and the URL reaches `shell.openExternal` on desktop.
+- **Partial registrations merge version metadata too.** With `patchFields`, `registerWorkVersion` spreads the new `metadata` over the current version's, so a GitHub PR's `headBranch` / `baseBranch` (from `--head` / `--base` or REST `head.ref` / `base.ref`) survive an edit that names neither. A key cannot be cleared on that path; a provider that needs to unset one must send a complete registration.
+- **GitHub state is drawn, not written.** The card's icon carries open / draft / merged / closed (`GITHUB_STATES` in `src/features/Work/descriptors.tsx`), so GitHub descriptions never fall back to the status word. The stored status only changes on create/edit registrations; a merge does not register, so a merged PR keeps its last registered state.
- **The tokenizer is deliberately hand-rolled** (no `shell-quote` dep): a real parser would expand what must stay literal, and the worst failure mode is skipping a bookkeeping registration.
- **Error-terminated runs skip the completion scan** (same success gate as file Works): a `gh` create that succeeds before a later terminal failure registers no Work that round. Accepted — bounded cost, missing card only.
- **Hetero Works register after the terminal snapshot** (`agent_runtime_end` publishes before `completeOperation`), so a hetero-created card appears on the next refetch, not in the terminal snapshot. Accepted for now.
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 4cbabe65bea..e700adcf7aa 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -255,6 +255,7 @@
"metaCard.detached": "Detached HEAD at {{sha}}",
"metaCard.goal": "Linked goal",
"metaCard.pr.closed": "Closed",
+ "metaCard.pr.draft": "Draft",
"metaCard.pr.merged": "Merged",
"metaCard.pr.open": "Open",
"newTopic": "New Topic",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index a2440e0c54f..c2c91765e0c 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -255,6 +255,7 @@
"metaCard.detached": "游离 HEAD 于 {{sha}}",
"metaCard.goal": "关联目标",
"metaCard.pr.closed": "已关闭",
+ "metaCard.pr.draft": "草稿",
"metaCard.pr.merged": "已合并",
"metaCard.pr.open": "开放中",
"newTopic": "新话题",
diff --git a/packages/database/src/models/work/__tests__/github.test.ts b/packages/database/src/models/work/__tests__/github.test.ts
index d9cc7efcb5b..e4edf2b28c5 100644
--- a/packages/database/src/models/work/__tests__/github.test.ts
+++ b/packages/database/src/models/work/__tests__/github.test.ts
@@ -412,4 +412,48 @@ describe('WorkModel · github', () => {
const workRows = await serverDB.select().from(works).where(eq(works.type, 'external'));
expect(workRows).toHaveLength(2);
});
+
+ it('keeps the PR branches captured at create across edits that do not name them', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+ const gh = (command: string, toolCallId: string, rootOperationId: string) =>
+ workModel.handleSkillToolResult({
+ provider: 'github',
+ data: { command, exitCode: 0, output: 'https://github.com/lobehub/lobehub/pull/31\n' },
+ rootOperationId,
+ toolCallId,
+ toolName: 'runCommand',
+ topicId,
+ });
+
+ const created = await gh(
+ 'gh pr create --repo lobehub/lobehub --head feat/branch-card --base canary --title "Branch card" --body-file /tmp/body.md',
+ 'tool-call-pr-branch-create',
+ 'op-pr-branch-create',
+ );
+ await gh(
+ 'gh pr edit 31 --repo lobehub/lobehub --title "Branch card, retitled"',
+ 'tool-call-pr-branch-retitle',
+ 'op-pr-branch-retitle',
+ );
+ await gh(
+ 'gh pr edit 31 --repo lobehub/lobehub --base main',
+ 'tool-call-pr-branch-retarget',
+ 'op-pr-branch-retarget',
+ );
+
+ const versions = await workModel.listVersions(created!.id);
+ expect(versions.map((item) => [item.version, item.metadata])).toEqual([
+ [3, { baseBranch: 'main', headBranch: 'feat/branch-card' }],
+ [2, { baseBranch: 'canary', headBranch: 'feat/branch-card' }],
+ [1, { baseBranch: 'canary', headBranch: 'feat/branch-card' }],
+ ]);
+
+ // Summary cards render the current version, so an older message's card
+ // shows the latest branches too.
+ const byOperation = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-pr-branch-retitle'],
+ });
+ const summary = expectExternalSummaryItem(byOperation['op-pr-branch-retitle']?.[0]);
+ expect(summary.event.metadata).toEqual({ baseBranch: 'main', headBranch: 'feat/branch-card' });
+ });
});
diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
index 2f7b693e7c9..7f3c3600bd8 100644
--- a/packages/database/src/models/work/__tests__/githubToolResult.test.ts
+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
@@ -486,6 +486,33 @@ describe('normalizeGithubToolResult (structured REST results)', () => {
expect(operation?.params.url).toBe('https://github.com/lobehub/lobehub/issues/5');
});
+ it('reads PR branches from the REST `head` / `base` refs, falling back to the args', () => {
+ const fromRefs = structured(
+ {
+ base: { ref: 'canary' },
+ head: { label: 'lobehub:feat/x', ref: 'feat/x' },
+ number: 21,
+ repository_full_name: 'lobehub/lobehub',
+ },
+ undefined,
+ 'create_pull_request',
+ );
+ expect(fromRefs?.params.metadata).toEqual({ baseBranch: 'canary', headBranch: 'feat/x' });
+
+ const fromArgs = structured(
+ { number: 22, repository_full_name: 'lobehub/lobehub' },
+ { base: 'main', head: 'feat/y' },
+ 'create_pull_request',
+ );
+ expect(fromArgs?.params.metadata).toEqual({ baseBranch: 'main', headBranch: 'feat/y' });
+
+ const issue = structured(
+ { base: { ref: 'main' }, number: 23, repository_full_name: 'lobehub/lobehub' },
+ { head: 'feat/z' },
+ );
+ expect(issue?.params.metadata).toBeUndefined();
+ });
+
it('collapses merged and draft into the display status', () => {
const merged = structured({ merged: true, number: 5, repository_full_name: 'o/r' });
expect(merged?.params.status).toBe('merged');
@@ -660,6 +687,38 @@ describe('normalizeGithubToolResult (gh CLI edge cases)', () => {
});
});
+ it('captures the PR branches from --head / --base, long and short forms', () => {
+ const long = runCommand(
+ `gh pr create --repo lobehub/lobehub --head feat/work-branch --base=canary --title 'T' --body-file /tmp/body.md`,
+ 'https://github.com/lobehub/lobehub/pull/11',
+ );
+ expect(long?.params.metadata).toEqual({ baseBranch: 'canary', headBranch: 'feat/work-branch' });
+
+ const short = runCommand(
+ `gh pr create -R lobehub/lobehub -H fork-owner:fix/x -B main -t 'T'`,
+ 'https://github.com/lobehub/lobehub/pull/12',
+ );
+ expect(short?.params.metadata).toEqual({ baseBranch: 'main', headBranch: 'fork-owner:fix/x' });
+ });
+
+ it('records only the base a `gh pr edit --base` changes, and nothing without branch flags', () => {
+ const retarget = runCommand(`gh pr edit 13 --repo lobehub/lobehub --base main`);
+ expect(retarget?.params.metadata).toEqual({ baseBranch: 'main' });
+
+ const retitle = runCommand(`gh pr edit 13 --repo lobehub/lobehub --title 'Retitled'`);
+ expect(retitle?.params.metadata).toBeUndefined();
+ });
+
+ it('never attaches branches to an issue', () => {
+ const operation = runCommand(
+ `gh issue create --repo lobehub/lobehub --title 'T' -H stray -B stray`,
+ 'https://github.com/lobehub/lobehub/issues/14',
+ );
+
+ expect(operation?.params.resourceType).toBe('github_issue');
+ expect(operation?.params.metadata).toBeUndefined();
+ });
+
it('skips a create command that leaves no resolvable identity', () => {
expect(
normalizeGithubToolResult({
diff --git a/packages/database/src/models/work/displayWork.ts b/packages/database/src/models/work/displayWork.ts
index 46c26a8a366..a39640b702c 100644
--- a/packages/database/src/models/work/displayWork.ts
+++ b/packages/database/src/models/work/displayWork.ts
@@ -50,7 +50,7 @@ export const registerExternalWork = async (
visibility: 'private',
},
params,
- () => ({ display, patchFields: params.patchFields }),
+ () => ({ display, metadata: params.metadata, patchFields: params.patchFields }),
);
};
diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.ts
index 5f249c451dc..83955a68f63 100644
--- a/packages/database/src/models/work/githubToolResult.ts
+++ b/packages/database/src/models/work/githubToolResult.ts
@@ -3,6 +3,7 @@ import type {
RegisterExternalWorkParams,
SkillToolResultWorkInput,
WorkDisplayField,
+ WorkVersionMetadata,
} from '@lobechat/types';
import { WORK_DESCRIPTION_PREVIEW_LENGTH } from './internal';
@@ -201,6 +202,26 @@ const hasStatusSignal = (record: Record<string, unknown>) =>
typeof record.merged === 'boolean' ||
typeof record.draft === 'boolean';
+/** PR branches as version metadata; `undefined` when neither is known. */
+const branchMetadata = (
+ head: string | null,
+ base: string | null,
+): WorkVersionMetadata | undefined => {
+ if (!head && !base) return undefined;
+
+ return { ...(head && { headBranch: head }), ...(base && { baseBranch: base }) };
+};
+
+/**
+ * A REST pull request carries `head` / `base` as `{ ref }` objects; the
+ * `create_pull_request` arguments name them as plain strings.
+ */
+const resolveBranch = (
+ record: Record<string, unknown>,
+ args: Record<string, unknown>,
+ key: 'base' | 'head',
+): string | null => fromRecord(toRecord(record[key]) ?? {}, ['ref']) ?? fromRecord(args, [key]);
+
const githubResourceType = (entityType: GithubWorkEntityType): GithubWorkResourceType =>
entityType === 'issue' ? 'github_issue' : 'github_pull_request';
@@ -235,6 +256,10 @@ const buildParams = (
identifier: repo && number !== null ? `${repo}#${number}` : null,
resourceType: githubResourceType(tool.entityType),
messageId: params.messageId ?? null,
+ metadata:
+ tool.entityType === 'pull_request'
+ ? branchMetadata(resolveBranch(record, args, 'head'), resolveBranch(record, args, 'base'))
+ : undefined,
rootOperationId: params.rootOperationId ?? null,
status: patch('status', hasStatusSignal(record), resolveStatus(record)),
threadId: params.threadId ?? null,
@@ -315,9 +340,13 @@ const parseGithubEntityUrls = (text: string | null): GithubEntityRef[] => {
interface ParsedGhCommand {
action: 'create' | 'edit';
+ /** `--base`: set on `gh pr create`, or changed by `gh pr edit`. */
+ base: string | null;
body: string | null;
draft: boolean;
entityType: GithubWorkEntityType;
+ /** `--head`, `gh pr create` only; without it gh uses the checked-out branch, which the command text does not name. */
+ head: string | null;
repo: string | null;
targetNumber: number | null;
targetRef: GithubEntityRef | null;
@@ -332,8 +361,10 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
if (noun !== 'issue' && noun !== 'pr') return null;
if (action !== 'create' && action !== 'edit') return null;
+ let base: string | null = null;
let body: string | null = null;
let draft = false;
+ let head: string | null = null;
let repoFlag: string | null = null;
let title: string | null = null;
const positionals: string[] = [];
@@ -379,6 +410,16 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
draft = true;
break;
}
+ case '-B':
+ case '--base': {
+ base = value;
+ break;
+ }
+ case '-H':
+ case '--head': {
+ head = value;
+ break;
+ }
default: {
// Other value flags had their value consumed above; other boolean
// flags (--web, --fill, ...) carry nothing we snapshot.
@@ -398,11 +439,16 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
else if (/^\d+$/.test(positional)) targetNumber = Number(positional);
}
+ // Issues have no branches; drop any stray `-B` / `-H` values.
+ const isPullRequest = noun === 'pr';
+
return {
action,
+ base: isPullRequest ? base : null,
body,
draft,
- entityType: noun === 'issue' ? 'issue' : 'pull_request',
+ entityType: isPullRequest ? 'pull_request' : 'issue',
+ head: isPullRequest ? head : null,
repo,
targetNumber,
targetRef,
@@ -472,6 +518,7 @@ const normalizeGithubCliResult = (
resourceId: identifier,
resourceType: githubResourceType(ref.entityType),
messageId: params.messageId ?? null,
+ metadata: branchMetadata(parsed.head, parsed.base),
rootOperationId: params.rootOperationId ?? null,
// gh only exposes --draft on create; an edit carries no status signal.
status: patch('status', parsed.action === 'create', parsed.draft ? 'draft' : 'open'),
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
index 4a03754c637..a8be6df8b84 100644
--- a/packages/database/src/models/work/writes.ts
+++ b/packages/database/src/models/work/writes.ts
@@ -7,6 +7,7 @@ import type {
WorkMetadata,
WorkResourceType,
WorkType,
+ WorkVersionMetadata,
WorkVisibility,
} from '@lobechat/types';
import { and, eq, inArray, sql } from 'drizzle-orm';
@@ -110,6 +111,20 @@ const buildVersionSnapshot = (
return snapshot;
};
+/**
+ * Version metadata follows the display snapshot: a partial registration keeps
+ * the current version's keys and overrides only the ones it carries, so a
+ * `gh pr edit` without `--head` does not drop the branch captured at create.
+ */
+const buildVersionMetadata = (
+ input: CreateVersionInput,
+ currentMetadata?: WorkVersionMetadata | null,
+): WorkVersionMetadata | null => {
+ if (!input.patchFields || !currentMetadata) return input.metadata ?? null;
+
+ return { ...currentMetadata, ...input.metadata };
+};
+
/**
* Shared registration pipeline: find-or-create the Work identity, dedupe by
* toolCallId, allocate the next version number, insert the complete immutable
@@ -201,9 +216,9 @@ export const registerWorkVersion = async (
if (dedupedUnderLock) return locked;
const input = await buildInput(txCtx);
- const [currentSnapshot] = locked.currentVersionId
+ const [currentVersion] = locked.currentVersionId
? await tx
- .select(versionSnapshotSelection)
+ .select({ ...versionSnapshotSelection, metadata: workVersions.metadata })
.from(workVersions)
.where(
and(
@@ -213,6 +228,7 @@ export const registerWorkVersion = async (
)
.limit(1)
: [];
+ const { metadata: currentMetadata, ...currentSnapshot } = currentVersion ?? {};
const snapshot = buildVersionSnapshot(input, currentSnapshot);
const now = new Date();
@@ -238,7 +254,7 @@ export const registerWorkVersion = async (
description: snapshot.description,
identifier: snapshot.identifier,
messageId: params.messageId ?? null,
- metadata: input.metadata ?? null,
+ metadata: buildVersionMetadata(input, currentMetadata),
changeType: params.changeType,
rootOperationId: params.rootOperationId ?? null,
status: snapshot.status,
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 3d5285d07a3..a6e995626d5 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -106,6 +106,7 @@ export default {
'metaCard.detached': 'Detached HEAD at {{sha}}',
'metaCard.goal': 'Linked goal',
'metaCard.pr.closed': 'Closed',
+ 'metaCard.pr.draft': 'Draft',
'metaCard.pr.merged': 'Merged',
'metaCard.pr.open': 'Open',
'filter.allTopics': 'All',
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index bb384c1473b..924705c05b9 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -114,6 +114,8 @@ export interface CanvasStorageItem {
export interface WorkVersionMetadata {
agentDocumentId?: string;
+ /** `external` GitHub PR Work — the branch the pull request merges into. */
+ baseBranch?: string;
canvas?: CanvasWorkVersionMetadata;
/**
* `file` Work — the edited file's identity in the file store, when the entity
@@ -131,6 +133,12 @@ export interface WorkVersionMetadata {
goalReport?: GoalReportMetadata;
/** `goal_report` Work — the report as an HTML page: a `custom/html` document id. */
goalReportPageId?: string;
+ /**
+ * `external` GitHub PR Work — the pull request's source branch as the tool
+ * named it: REST `head.ref` is the bare branch, while `gh --head` may carry
+ * `owner:branch` for a fork.
+ */
+ headBranch?: string;
/** `file` Work — lines added by this version's edit (0 when the source tool reports none). */
linesAdded?: number;
/** `file` Work — lines deleted by this version's edit (0 when the source tool reports none). */
@@ -481,6 +489,12 @@ export interface RegisterExternalWorkParams {
description?: string | null;
identifier?: string | null;
messageId?: string | null;
+ /**
+ * Provider facts outside the display columns (a PR's branches). With
+ * `patchFields`, keys merge over the current version's metadata, so an edit
+ * that names no branch keeps the one captured at create.
+ */
+ metadata?: WorkVersionMetadata | null;
patchFields?: WorkDisplayField[];
/**
* Canonical resource identity (`owner/repo#number`, a linear id, …). Required:
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 2f81109490e..f2130f3601c 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -3,7 +3,7 @@
import type { WorkSummaryItem } from '@lobechat/types';
import { formatUsageValue } from '@lobechat/utils';
import { Center, createStaticStyles, cx, Flexbox, Icon as LobeIcon, Text } from '@lobehub/ui';
-import { CircleDollarSignIcon, CoinsIcon } from 'lucide-react';
+import { CircleDollarSignIcon, CoinsIcon, GitBranchIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,7 +12,12 @@ import { getWorkVersionTotalTokens } from '@/utils/workCumulativeUsage';
import { formatWorkVersionCost } from '@/utils/workVersionCost';
import CanvasWorkCard from './CanvasWorkCard';
-import { getWorkTypeDescriptor, isSafeExternalUrl } from './descriptors';
+import {
+ getWorkTypeDescriptor,
+ isSafeExternalUrl,
+ type WorkBranch,
+ type WorkIcon,
+} from './descriptors';
import { useResourceDeletedPrompt } from './useResourceDeletedPrompt';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -34,6 +39,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillQuaternary};
}
`,
+ branch: css`
+ flex: 1 1 0;
+ min-width: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
cost: css`
flex-shrink: 0;
font-family: ${cssVar.fontFamilyCode};
@@ -41,13 +51,29 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
color: ${cssVar.colorTextTertiary};
`,
description: css`
+ flex: 1 1 0;
min-width: 0;
+ font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
- identifier: css`
+ dot: css`
flex-shrink: 0;
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ identifier: css`
+ /* The short resource key keeps its width; the branch / description truncates first. */
+ flex: 0 0 auto;
+
+ max-width: 60%;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
+ identifierIcon: css`
+ flex-shrink: 0;
+ `,
icon: css`
flex-shrink: 0;
@@ -59,6 +85,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillTertiary};
`,
+ inlineBranch: css`
+ flex: 1 1 0;
+ min-width: 0;
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
inline: css`
overflow: hidden;
@@ -103,8 +135,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-size: 11px;
color: ${cssVar.colorTextTertiary};
`,
- inlineMeta: css`
+ meta: css`
+ min-width: 0;
+ `,
+ /** Monospace text inside an identifier / branch group, truncating within it. */
+ metaText: css`
min-width: 0;
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: inherit;
+ color: inherit;
`,
inlineIcon: css`
flex-shrink: 0;
@@ -122,6 +161,79 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+interface WorkMetaLineProps {
+ branch: WorkBranch | null;
+ description: string | null;
+ /** `null` when the title already fell back to it. */
+ identifier: string | null;
+ /** Brand mark before the identifier (GitHub), see `getIdentifierIcon`. */
+ identifierIcon: WorkIcon | null;
+ variant: 'card' | 'inline';
+}
+
+/**
+ * The second line of both variants: the resource key, then the PR's head
+ * branch, or the description when no branch is known. Keeping the key here
+ * leaves the first line to the title, so a long `owner/repo#n` can't squeeze it.
+ */
+const WorkMetaLine = ({
+ branch,
+ description,
+ identifier,
+ identifierIcon: IdentifierIcon,
+ variant,
+}: WorkMetaLineProps) => {
+ const inline = variant === 'inline';
+ const detail = branch ? branch.head : description;
+ if (!identifier && !detail) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.meta} gap={4}>
+ {identifier && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={inline ? styles.inlineIdentifier : styles.identifier}
+ gap={3}
+ title={identifier}
+ >
+ {IdentifierIcon && (
+ <IdentifierIcon className={styles.identifierIcon} size={inline ? 11 : 12} />
+ )}
+ <Text ellipsis className={styles.metaText}>
+ {identifier}
+ </Text>
+ </Flexbox>
+ )}
+ {identifier && detail && <span className={inline ? styles.inlineDot : styles.dot}>·</span>}
+ {branch ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={inline ? styles.inlineBranch : styles.branch}
+ gap={3}
+ title={branch.base ? `${branch.head} → ${branch.base}` : branch.head}
+ >
+ <LobeIcon icon={GitBranchIcon} size={inline ? 11 : 12} />
+ <Text ellipsis className={styles.metaText}>
+ {branch.head}
+ </Text>
+ </Flexbox>
+ ) : (
+ description && (
+ <Text
+ ellipsis
+ className={inline ? styles.inlineDescription : styles.description}
+ title={description}
+ >
+ {description}
+ </Text>
+ )
+ )}
+ </Flexbox>
+ );
+};
+
interface WorkSummaryCardProps {
className?: string;
item: WorkSummaryItem;
@@ -146,6 +258,7 @@ interface WorkSummaryCardProps {
const WorkSummaryCard = memo<WorkSummaryCardProps>(
({ className, item, onOpen, variant = 'card' }) => {
const { t } = useTranslation('chat');
+ const { t: tTopic } = useTranslation('topic');
const openCanvas = useChatStore((s) => s.openCanvas);
const openDocument = useChatStore((s) => s.openDocument);
const openFilePreview = useChatStore((s) => s.openFilePreview);
@@ -166,6 +279,8 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
const descriptor = getWorkTypeDescriptor(item);
const Icon = descriptor.getIcon(item);
+ const stateLabelKey = descriptor.getStateLabelKey?.(item);
+ const stateLabel = stateLabelKey ? tTopic(stateLabelKey) : undefined;
const title =
descriptor.getTitle(item)?.trim() ||
descriptor.getIdentifier(item) ||
@@ -175,7 +290,9 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
// (e.g. `QA-1989`, `owner/repo#2`) on the card itself, unless the title
// already fell back to it.
const identifier = descriptor.getIdentifier(item);
- const showIdentifier = !!identifier && identifier !== title;
+ const metaIdentifier = identifier && identifier !== title ? identifier : null;
+ const identifierIcon = descriptor.getIdentifierIcon?.(item) ?? null;
+ const branch = descriptor.getBranch?.(item) ?? null;
const description = descriptor.getDescription(item);
const openTarget = descriptor.getOpenTarget(item);
// The backing resource (task / document) was deleted outside the tool path:
@@ -240,10 +357,9 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
gap={10}
onClick={clickable ? handleOpen : undefined}
>
- <Icon className={styles.inlineIcon} size={17} />
- {/* The sidebar is narrow: the title owns the first line (sharing it only
- with the short usage badge), and the identifier drops to the meta line
- with the description so a long `owner/repo#n` can't squeeze the title. */}
+ <Center className={styles.inlineIcon} title={stateLabel}>
+ <Icon size={17} />
+ </Center>
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
<Text ellipsis className={styles.inlineTitle} style={{ flex: 1 }} title={title}>
@@ -256,21 +372,13 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
</Center>
)}
</Flexbox>
- {(showIdentifier || description) && (
- <Flexbox horizontal align={'center'} className={styles.inlineMeta} gap={4}>
- {showIdentifier && (
- <Text ellipsis className={styles.inlineIdentifier} title={identifier}>
- {identifier}
- </Text>
- )}
- {showIdentifier && description && <span className={styles.inlineDot}>·</span>}
- {description && (
- <Text ellipsis className={styles.inlineDescription} title={description}>
- {description}
- </Text>
- )}
- </Flexbox>
- )}
+ <WorkMetaLine
+ branch={branch}
+ description={description}
+ identifier={metaIdentifier}
+ identifierIcon={identifierIcon}
+ variant={'inline'}
+ />
</Flexbox>
</Flexbox>
);
@@ -284,21 +392,14 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
gap={12}
onClick={clickable ? handleOpen : undefined}
>
- <Flexbox align={'center'} className={styles.icon} justify={'center'}>
+ <Flexbox align={'center'} className={styles.icon} justify={'center'} title={stateLabel}>
<Icon size={18} />
</Flexbox>
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <Text ellipsis className={styles.title}>
- {title}
- </Text>
- {showIdentifier && (
- <Text code className={styles.identifier} fontSize={12}>
- {identifier}
- </Text>
- )}
- </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis className={styles.title} style={{ flex: 1 }} title={title}>
+ {title}
+ </Text>
{usage && (
<Center horizontal className={styles.cost} gap={2} title={usageTitle}>
<LobeIcon icon={usage.icon} />
@@ -306,11 +407,13 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
</Center>
)}
</Flexbox>
- {description && (
- <Text ellipsis className={styles.description} fontSize={12}>
- {description}
- </Text>
- )}
+ <WorkMetaLine
+ branch={branch}
+ description={description}
+ identifier={metaIdentifier}
+ identifierIcon={identifierIcon}
+ variant={'card'}
+ />
</Flexbox>
</Flexbox>
);
diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.ts
index 98bdb231f99..b6f72bff62b 100644
--- a/src/features/Work/descriptors.test.ts
+++ b/src/features/Work/descriptors.test.ts
@@ -129,4 +129,98 @@ describe('getWorkTypeDescriptor', () => {
});
});
});
+
+ describe('external GitHub state and branch', () => {
+ const githubItem = (overrides: Record<string, unknown> = {}) =>
+ ({
+ description: null,
+ id: 'work-gh-1',
+ identifier: 'lobehub/lobehub#1',
+ resourceId: 'lobehub/lobehub#1',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ title: 'A PR',
+ type: 'external',
+ ...overrides,
+ }) as any;
+
+ it('draws each PR state with its own stable glyph and keeps the brand icon otherwise', () => {
+ const iconOf = (overrides: Record<string, unknown>) => {
+ const item = githubItem(overrides);
+ return getWorkTypeDescriptor(item).getIcon(item);
+ };
+
+ const states = ['open', 'draft', 'merged', 'closed'].map((status) => iconOf({ status }));
+ expect(new Set(states).size).toBe(4);
+ // Stable identity: the card must not remount its icon on every render.
+ expect(iconOf({ status: 'open' })).toBe(states[0]);
+ // GraphQL-style uppercase states resolve the same way.
+ expect(iconOf({ status: 'MERGED' })).toBe(states[2]);
+
+ const brand = iconOf({ status: null });
+ expect(states).not.toContain(brand);
+ expect(iconOf({ status: 'constructor' })).toBe(brand);
+ expect(iconOf({ resourceType: 'github_issue', status: 'open' })).not.toBe(brand);
+ });
+
+ it('labels the drawn state for the icon tooltip, and nothing when the icon is the brand', () => {
+ const labelOf = (overrides: Record<string, unknown>) => {
+ const item = githubItem(overrides);
+ return getWorkTypeDescriptor(item).getStateLabelKey?.(item);
+ };
+
+ expect(labelOf({ status: 'draft' })).toBe('metaCard.pr.draft');
+ expect(labelOf({ status: 'merged' })).toBe('metaCard.pr.merged');
+ expect(labelOf({ resourceType: 'github_issue', status: 'closed' })).toBe(
+ 'metaCard.pr.closed',
+ );
+ expect(labelOf({ status: null })).toBeNull();
+ });
+
+ it('marks every GitHub identifier with the GitHub logo, and no other provider', () => {
+ const markOf = (overrides: Record<string, unknown>) => {
+ const item = githubItem(overrides);
+ return getWorkTypeDescriptor(item).getIdentifierIcon?.(item);
+ };
+
+ const prMark = markOf({ status: 'open' });
+ expect(prMark).toBeTruthy();
+ // Same mark whether the main icon is a state glyph or already the brand logo.
+ expect(markOf({ status: null })).toBe(prMark);
+ expect(markOf({ resourceType: 'github_issue', status: 'closed' })).toBe(prMark);
+ expect(markOf({ resourceType: 'linear_issue', status: 'In Progress' })).toBeNull();
+ });
+
+ it('reads the head/base branch from the summary metadata only for pull requests', () => {
+ const withBranch = githubItem({
+ event: { metadata: { baseBranch: 'canary', headBranch: 'feat/x' } },
+ });
+ const descriptor = getWorkTypeDescriptor(withBranch);
+
+ expect(descriptor.getBranch?.(withBranch)).toEqual({ base: 'canary', head: 'feat/x' });
+ expect(descriptor.getBranch?.(githubItem())).toBeNull();
+ expect(
+ descriptor.getBranch?.(
+ githubItem({
+ event: { metadata: { headBranch: 'feat/x' } },
+ resourceType: 'github_issue',
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('drops the status fallback from the GitHub description but keeps it for Linear', () => {
+ const github = githubItem();
+ expect(getWorkTypeDescriptor(github).getDescription(github)).toBeNull();
+
+ const linear = {
+ description: null,
+ id: 'work-linear-1',
+ resourceType: 'linear_issue',
+ status: 'In Progress',
+ type: 'external',
+ } as any;
+ expect(getWorkTypeDescriptor(linear).getDescription(linear)).toBe('In Progress');
+ });
+ });
});
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
index d0185f3bd82..1dca17de5cc 100644
--- a/src/features/Work/descriptors.tsx
+++ b/src/features/Work/descriptors.tsx
@@ -1,5 +1,6 @@
import { classifyEditedFile, getBasename } from '@lobechat/builtin-tools/fileEditScan';
import {
+ type ExternalWorkResourceType,
type ListedWorkType,
type WorkListItem,
workProviderOfResourceType,
@@ -9,13 +10,17 @@ import {
type WorkVersionMetadata,
} from '@lobechat/types';
import { Github } from '@lobehub/icons';
-import { FileTypeIcon as FileTypeBadge } from '@lobehub/ui';
+import { cssVar, FileTypeIcon as FileTypeBadge } from '@lobehub/ui';
+import type { LucideIcon } from 'lucide-react';
import {
+ CircleCheckIcon,
+ CircleDotIcon,
ClipboardListIcon,
FileBoxIcon,
FileSpreadsheetIcon,
FileTextIcon,
FileTypeIcon,
+ GitPullRequestDraftIcon,
LinkIcon,
PanelsTopLeftIcon,
PresentationIcon,
@@ -23,10 +28,15 @@ import {
import type { ComponentType } from 'react';
import { mimeTypeMap } from '@/components/FileIcon/config';
+import {
+ MERGED_PURPLE,
+ PR_STATE_VISUAL,
+ type PullRequestStateVisual,
+} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
import LinearIcon from './icons/LinearIcon';
-type WorkIcon = ComponentType<{ className?: string; size?: number }>;
+export type WorkIcon = ComponentType<{ className?: string; size?: number }>;
/**
* Brand icon per skill provider for the unified `external` Work type. An
@@ -38,6 +48,73 @@ const PROVIDER_ICONS: Record<WorkSkillProvider, WorkIcon> = {
linear: LinearIcon,
};
+/** Bind a color at module level so `getIcon` keeps a stable component identity. */
+const tintIcon = (Glyph: LucideIcon, color: string): WorkIcon => {
+ const TintedIcon: WorkIcon = ({ className, size }) => (
+ <Glyph className={className} color={color} size={size} />
+ );
+ return TintedIcon;
+};
+
+/** `topic` namespace label of a GitHub state, the tooltip of its glyph. */
+export type WorkStateLabelKey = PullRequestStateVisual['labelKey'] | 'metaCard.pr.draft';
+
+interface GithubStateVisual {
+ icon: WorkIcon;
+ labelKey: WorkStateLabelKey;
+}
+
+const prState = (state: keyof typeof PR_STATE_VISUAL): GithubStateVisual => ({
+ icon: tintIcon(PR_STATE_VISUAL[state].icon, PR_STATE_VISUAL[state].color),
+ labelKey: PR_STATE_VISUAL[state].labelKey,
+});
+
+/**
+ * GitHub state glyphs, matching the topic PR card: the icon's shape and color
+ * carry open / draft / merged / closed instead of a status word on the card.
+ * Keys are the `status` values the github normalizer writes; any other status
+ * keeps the brand icon.
+ */
+const GITHUB_STATES: Partial<Record<ExternalWorkResourceType, Map<string, GithubStateVisual>>> = {
+ github_issue: new Map([
+ [
+ 'closed',
+ { icon: tintIcon(CircleCheckIcon, MERGED_PURPLE), labelKey: PR_STATE_VISUAL.closed.labelKey },
+ ],
+ [
+ 'open',
+ {
+ icon: tintIcon(CircleDotIcon, cssVar.colorSuccess),
+ labelKey: PR_STATE_VISUAL.open.labelKey,
+ },
+ ],
+ ]),
+ github_pull_request: new Map([
+ ['closed', prState('closed')],
+ [
+ 'draft',
+ {
+ icon: tintIcon(GitPullRequestDraftIcon, cssVar.colorTextTertiary),
+ labelKey: 'metaCard.pr.draft',
+ },
+ ],
+ ['merged', prState('merged')],
+ ['open', prState('open')],
+ ]),
+};
+
+const getGithubState = (
+ item: Pick<WorkListItem, 'resourceType' | 'status'>,
+): GithubStateVisual | undefined =>
+ item.status
+ ? GITHUB_STATES[item.resourceType as ExternalWorkResourceType]?.get(item.status.toLowerCase())
+ : undefined;
+
+export interface WorkBranch {
+ base: string | null;
+ head: string;
+}
+
/**
* Where opening a Work should lead. Components map this to their own action
* (chat portal, preview modal, router navigate, `window.open`) — the descriptor
@@ -80,6 +157,12 @@ type WorkItemOfType<T extends WorkType> =
Extract<WorkListItem, { type: T }> | Extract<WorkSummaryItem, { type: T }>;
interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
+ /**
+ * A pull request's branches, from the summary row's version metadata. Cards
+ * show the head branch in place of the description; `null` for every other
+ * Work and for PRs registered without a known branch.
+ */
+ getBranch?: (item: Item) => WorkBranch | null;
/**
* Summary preview text. Summary payloads slim long free-text server-side
* (linear content / github body / task instruction capped), so prefer the
@@ -88,7 +171,8 @@ interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
getDescription: (item: Item) => string | null;
/**
* The icon for one item. Constant for document/task; the `external` type
- * resolves a per-provider brand icon from the item's resourceType.
+ * resolves a GitHub state glyph when the status is known, else a
+ * per-provider brand icon from the item's resourceType.
*/
getIcon: (item: Item) => WorkIcon;
/**
@@ -97,8 +181,16 @@ interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
* further to `resourceId` when this is also null.
*/
getIdentifier: (item: Item) => string | null;
+ /**
+ * Brand mark drawn before the identifier on the card's second line. GitHub
+ * cards spend their main icon on the issue/PR state, so the mark keeps
+ * `owner/repo#n` recognizable as a GitHub repository.
+ */
+ getIdentifierIcon?: (item: Item) => WorkIcon | null;
/** Where a click should lead, or `null` when the Work is not clickable. */
getOpenTarget: (item: Item) => WorkOpenTarget | null;
+ /** Label of the state `getIcon` draws, for its tooltip; `null` when the icon carries no state. */
+ getStateLabelKey?: (item: Item) => WorkStateLabelKey | null;
/**
* Display title straight from the `works` row (task name is live from the
* tasks join). No synthesized fallback here: a nameless resource deliberately
@@ -237,19 +329,38 @@ export const WORK_TYPE_DESCRIPTORS: {
},
},
external: {
- getDescription: (item) => (item.description || item.status)?.trim() ?? null,
- // Resolve the brand icon from the item's provider; unknown providers fall
- // back to a generic link glyph (forward-compat).
+ getBranch: (item) => {
+ if (item.resourceType !== 'github_pull_request' || !('event' in item)) return null;
+ const metadata = item.event?.metadata;
+ return metadata?.headBranch
+ ? { base: metadata.baseBranch ?? null, head: metadata.headBranch }
+ : null;
+ },
+ // GitHub state is drawn by the icon, so only Linear falls back to its status text.
+ getDescription: (item) =>
+ (workProviderOfResourceType(item.resourceType) === 'github'
+ ? item.description
+ : item.description || item.status
+ )?.trim() ?? null,
+ // A GitHub issue/PR with a known state takes its state glyph; otherwise
+ // the provider's brand icon. Unknown providers fall back to a generic link
+ // glyph (forward-compat).
getIcon: (item) => {
const provider = workProviderOfResourceType(item.resourceType);
- return provider ? PROVIDER_ICONS[provider] : LinkIcon;
+ if (!provider) return LinkIcon;
+ return getGithubState(item)?.icon ?? PROVIDER_ICONS[provider];
},
getIdentifier: (item) => item.identifier,
+ // Every GitHub card carries the mark, including a brand-icon card with an
+ // unknown state, so the identifiers line up in a list.
+ getIdentifierIcon: (item) =>
+ workProviderOfResourceType(item.resourceType) === 'github' ? Github : null,
// External works registered from CLI/tool results may carry no URL (or a
// member-planted non-http(s) scheme) — those cards have nothing safe to
// open, so drop the click affordance entirely.
getOpenTarget: (item) =>
isSafeExternalUrl(item.url) ? { kind: 'external', url: item.url } : null,
+ getStateLabelKey: (item) => getGithubState(item)?.labelKey ?? null,
getTitle: (item) => item.title,
},
task: {
diff --git a/src/features/WorkGallery/WorkPreview.tsx b/src/features/WorkGallery/WorkPreview.tsx
index 28ab7767cf6..f076580631d 100644
--- a/src/features/WorkGallery/WorkPreview.tsx
+++ b/src/features/WorkGallery/WorkPreview.tsx
@@ -2,7 +2,7 @@
import type { WorkSummaryItem } from '@lobechat/types';
import { Github } from '@lobehub/icons';
-import { createStaticStyles, cssVar, Flexbox, Tag, Text } from '@lobehub/ui';
+import { Center, createStaticStyles, cssVar, Flexbox, Tag, Text } from '@lobehub/ui';
import { CheckCircle2Icon, GitPullRequestIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -169,8 +169,11 @@ interface WorkPreviewProps {
const WorkPreview = memo<WorkPreviewProps>(({ item, title }) => {
const { t } = useTranslation('file');
+ const { t: tTopic } = useTranslation('topic');
const descriptor = getWorkTypeDescriptor(item);
const DescriptorIcon = descriptor.getIcon(item);
+ // The PR state is drawn by its glyph; the description no longer falls back to it.
+ const stateLabelKey = descriptor.getStateLabelKey?.(item);
const description = descriptor.getDescription(item);
const identifier = descriptor.getIdentifier(item);
const displayIdentifier =
@@ -207,9 +210,14 @@ const WorkPreview = memo<WorkPreviewProps>(({ item, title }) => {
) : (
<div className={styles.previewBody}>
<Flexbox horizontal align={'center'} gap={6}>
- {item.resourceType === 'github_pull_request' && (
- <GitPullRequestIcon color={cssVar.colorTextTertiary} size={11} />
- )}
+ {item.resourceType === 'github_pull_request' &&
+ (stateLabelKey ? (
+ <Center title={tTopic(stateLabelKey)}>
+ <DescriptorIcon size={11} />
+ </Center>
+ ) : (
+ <GitPullRequestIcon color={cssVar.colorTextTertiary} size={11} />
+ ))}
<span className={styles.previewIdentifier}>
{previewIdentifier || item.resourceType}
</span>