Create GitHub issues with markdown and metadata (#3947)

* Create GitHub issues with markdown and metadata

- Add a reusable rich markdown composer for GitHub issue bodies and comments
- Let new GitHub issues include selected labels and assignees through IPC/RPC
- Preserve created issue metadata in the task list and cover the new API path with tests

* fix: address review findings
This commit is contained in:
Jinjing
2026-05-30 18:25:31 -07:00
committed by GitHub
parent bb6b872386
commit 9ca42f5582
16 changed files with 857 additions and 434 deletions
@@ -526,9 +526,9 @@ describe('AgentBrowserBridge', () => {
expect(wc.on).toHaveBeenCalledWith('did-finish-load', expect.any(Function))
})
const finishListener = wc.on.mock.calls.find(
([event]) => event === 'did-finish-load'
)?.[1] as (() => void) | undefined
const finishListener = wc.on.mock.calls.find(([event]) => event === 'did-finish-load')?.[1] as
| (() => void)
| undefined
const failListener = wc.on.mock.calls.find(([event]) => event === 'did-fail-load')?.[1] as
| (() => void)
| undefined
+40
View File
@@ -126,6 +126,46 @@ describe('issue source operations', () => {
)
})
it('creates issues with labels and assignees', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 925,
html_url: 'https://github.com/stablyai/orca/issues/925'
})
})
await expect(
createIssue('/repo-root', 'New issue', 'Body', undefined, undefined, {
labels: ['bug', 'frontend'],
assignees: ['octo']
})
).resolves.toEqual({
ok: true,
number: 925,
url: 'https://github.com/stablyai/orca/issues/925'
})
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
[
'api',
'-X',
'POST',
'repos/stablyai/orca/issues',
'--raw-field',
'title=New issue',
'--raw-field',
'body=Body',
'--raw-field',
'labels[]=bug',
'--raw-field',
'labels[]=frontend',
'--raw-field',
'assignees[]=octo'
],
{ cwd: '/repo-root' }
)
})
it('updates issue body through the REST issue endpoint', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' })
+21 -14
View File
@@ -5,6 +5,7 @@ surface is broad. */
import type {
ClassifiedError,
GitHubAssignableUser,
GitHubCreateIssueFields,
GitHubCommentResult,
GitHubIssueUpdate,
IssueInfo,
@@ -150,7 +151,8 @@ export async function createIssue(
title: string,
body: string,
preference?: IssueSourcePreference,
connectionId?: string | null
connectionId?: string | null,
fields?: GitHubCreateIssueFields
): Promise<{ ok: true; number: number; url: string } | { ok: false; error: string }> {
const trimmedTitle = title.trim()
if (!trimmedTitle) {
@@ -164,19 +166,24 @@ export async function createIssue(
}
await acquire()
try {
const { stdout } = await ghExecFileAsync(
[
'api',
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues`,
'--raw-field',
`title=${trimmedTitle}`,
'--raw-field',
`body=${body}`
],
ghOptions
)
const args = [
'api',
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues`,
'--raw-field',
`title=${trimmedTitle}`,
'--raw-field',
`body=${body}`
]
for (const label of fields?.labels ?? []) {
args.push('--raw-field', `labels[]=${label}`)
}
for (const assignee of fields?.assignees ?? []) {
args.push('--raw-field', `assignees[]=${assignee}`)
}
const { stdout } = await ghExecFileAsync(args, ghOptions)
const data = JSON.parse(stdout) as { number?: number; html_url?: string; url?: string }
if (typeof data.number !== 'number') {
return { ok: false, error: 'Unexpected response from GitHub' }
+8 -2
View File
@@ -6,6 +6,7 @@ import { ipcMain, webContents } from 'electron'
import { resolve } from 'path'
import type {
Repo,
GitHubCreateIssueFields,
GitHubIssueUpdate,
GitHubOwnerRepo,
GitHubPullRequestStateUpdate,
@@ -282,14 +283,19 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi
ipcMain.handle(
'gh:createIssue',
(_event, args: { repoPath: string; title: string; body: string }) => {
(_event, args: { repoPath: string; title: string; body: string } & GitHubCreateIssueFields) => {
const repo = assertRegisteredRepo(args, store)
const fields =
args.labels !== undefined || args.assignees !== undefined
? { labels: args.labels, assignees: args.assignees }
: undefined
return createIssue(
repo.path,
args.title,
args.body,
repo.issueSourcePreference,
repoConnectionId(repo)
repoConnectionId(repo),
fields
)
}
)
+5 -2
View File
@@ -36,6 +36,7 @@ import type {
ForceDeleteWorktreeBranchResult,
GitPushTarget,
GitWorktreeInfo,
GitHubCreateIssueFields,
GitHubOwnerRepo,
GlobalSettings,
PersistedUIState,
@@ -6507,7 +6508,8 @@ export class OrcaRuntimeService {
async createRepoIssue(
repoSelector: string,
title: string,
body: string
body: string,
fields?: GitHubCreateIssueFields
): Promise<Awaited<ReturnType<typeof createIssue>>> {
const repo = await this.resolveRepoSelector(repoSelector)
return createIssue(
@@ -6515,7 +6517,8 @@ export class OrcaRuntimeService {
title,
body,
repo.issueSourcePreference,
repo.connectionId ?? null
repo.connectionId ?? null,
fields
)
}
@@ -461,6 +461,30 @@ describe('github RPC methods', () => {
expect(response).toMatchObject({ ok: true, result: { ok: true, number: 3 } })
})
it('creates issues with metadata on the runtime server', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
createRepoIssue: vi.fn().mockResolvedValue({ ok: true, number: 4, url: 'https://gh/4' })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: GITHUB_METHODS })
const response = await dispatcher.dispatch(
makeRequest('github.createIssue', {
repo: 'repo-1',
title: 'Bug',
body: 'Body',
labels: ['bug'],
assignees: ['octo']
})
)
expect(runtime.createRepoIssue).toHaveBeenCalledWith('repo-1', 'Bug', 'Body', {
labels: ['bug'],
assignees: ['octo']
})
expect(response).toMatchObject({ ok: true, result: { ok: true, number: 4 } })
})
it('updates issues on the runtime server', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
+12 -3
View File
@@ -148,7 +148,9 @@ const RemovePrReviewers = RepoSelector.extend({
const CreateIssue = RepoSelector.extend({
title: requiredString('Missing title'),
body: z.string()
body: z.string(),
labels: z.array(z.string()).optional(),
assignees: z.array(z.string()).optional()
})
const IssueUpdate = z.object({
@@ -478,8 +480,15 @@ export const GITHUB_METHODS: RpcMethod[] = [
defineMethod({
name: 'github.createIssue',
params: CreateIssue,
handler: async (params, { runtime }) =>
runtime.createRepoIssue(params.repo, params.title, params.body)
handler: async (params, { runtime }) => {
const fields =
params.labels !== undefined || params.assignees !== undefined
? { labels: params.labels, assignees: params.assignees }
: undefined
return fields
? runtime.createRepoIssue(params.repo, params.title, params.body, fields)
: runtime.createRepoIssue(params.repo, params.title, params.body)
}
}),
defineMethod({
name: 'github.updateIssue',
+2
View File
@@ -959,6 +959,8 @@ export type PreloadApi = {
repoId?: string
title: string
body: string
labels?: string[]
assignees?: string[]
}) => Promise<{ ok: true; number: number; url: string } | { ok: false; error: string }>
countWorkItems: (args: { repoPath: string; repoId?: string; query?: string }) => Promise<number>
listWorkItems: (args: {
+2
View File
@@ -890,6 +890,8 @@ const api = {
repoId?: string
title: string
body: string
labels?: string[]
assignees?: string[]
}): Promise<{ ok: true; number: number; url: string } | { ok: false; error: string }> =>
ipcRenderer.invoke('gh:createIssue', args),
@@ -59,6 +59,34 @@
color: var(--foreground);
}
.github-markdown-composer .rich-markdown-editor-toolbar {
padding: 6px 8px;
background: color-mix(in srgb, var(--background) 92%, transparent);
}
.github-markdown-composer-editor {
min-height: 8rem;
padding: 12px 14px 18px;
font-size: 13px;
line-height: 1.55;
}
.github-markdown-composer-editor p,
.github-markdown-composer-editor ul,
.github-markdown-composer-editor ol,
.github-markdown-composer-editor blockquote {
margin: 0.55em 0;
}
.github-markdown-composer-image-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-bottom: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
background: color-mix(in srgb, var(--muted) 38%, var(--background));
}
.orca-diff-comment-add-btn.rich-markdown-comment-add-btn {
display: flex;
width: 22px;
+20 -347
View File
@@ -69,7 +69,6 @@ import {
} from '@/components/ui/dropdown-menu'
import CommentMarkdown from '@/components/sidebar/CommentMarkdown'
import { detectLanguage } from '@/lib/language-detect'
import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut'
import { cn } from '@/lib/utils'
import { DiffSectionItem } from '@/components/editor/DiffSectionItem'
import type { DecoratedDiffComment } from '@/components/diff-comments/useDiffCommentDecorator'
@@ -108,6 +107,7 @@ import { useAllWorktrees } from '@/store/selectors'
import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
import { useRepoLabels, useRepoAssignees, useImmediateMutation } from '@/hooks/useIssueMetadata'
import { useRepoLabelsBySlug, useRepoAssigneesBySlug } from '@/hooks/useGitHubSlugMetadata'
import { GitHubMarkdownComposer } from '@/components/github/GitHubMarkdownComposer'
import IssueSourceIndicator, { sameGitHubOwnerRepo } from '@/components/github/IssueSourceIndicator'
import {
getGitHubPRReviewerRows,
@@ -172,18 +172,6 @@ const MonacoCodeExcerpt = lazy(() => import('@/components/editor/MonacoCodeExcer
export type ItemDialogTab = 'conversation' | 'checks' | 'files'
type MentionOption = {
login: string
name?: string | null
avatarUrl?: string
source: string
}
type MentionQuery = {
atIndex: number
query: string
}
const CODE_CONTEXT_EXPAND_STEP = 5
const CODE_CONTEXT_FALLBACK_LINES = 20
const CODE_CONTEXT_MAX_BLOCK_LINES = CODE_CONTEXT_FALLBACK_LINES * 2 + 1
@@ -267,80 +255,6 @@ function formatRelativeTime(input: string): string {
return formatter.format(diffDays, 'day')
}
function findMentionQuery(value: string, caret: number): MentionQuery | null {
const beforeCaret = value.slice(0, caret)
const match = /(^|[\s([{,])@([A-Za-z0-9-]*)$/.exec(beforeCaret)
if (!match) {
return null
}
const query = match[2] ?? ''
return {
atIndex: beforeCaret.length - query.length - 1,
query
}
}
function buildMentionOptions({
item,
comments,
participants,
assignableUsers
}: {
item: GitHubWorkItem
comments: PRComment[]
participants: GitHubAssignableUser[]
assignableUsers: GitHubAssignableUser[]
}): MentionOption[] {
const byLogin = new Map<string, MentionOption>()
const add = (
login: string | null | undefined,
source: string,
avatarUrl?: string,
name?: string | null
): void => {
if (!login || login === 'ghost') {
return
}
const key = login.toLowerCase()
const existing = byLogin.get(key)
if (existing) {
if (!existing.avatarUrl && avatarUrl) {
existing.avatarUrl = avatarUrl
}
if (!existing.name && name) {
existing.name = name
}
return
}
byLogin.set(key, { login, source, avatarUrl, name })
}
add(item.author, item.type === 'pr' ? 'PR author' : 'Issue author')
for (const comment of comments) {
add(comment.author, 'Commenter', comment.authorAvatarUrl)
}
for (const user of participants) {
add(user.login, 'Participant', user.avatarUrl, user.name)
}
for (const user of assignableUsers) {
add(user.login, 'Team member', user.avatarUrl, user.name)
}
return Array.from(byLogin.values())
}
function filterMentionOptions(options: MentionOption[], query: string): MentionOption[] {
const normalizedQuery = query.toLowerCase()
const filtered = normalizedQuery
? options.filter(
(option) =>
option.login.toLowerCase().includes(normalizedQuery) ||
(option.name ?? '').toLowerCase().includes(normalizedQuery)
)
: options
return filtered.slice(0, 8)
}
function getStateLabel(item: GitHubWorkItem): string {
if (item.type === 'pr') {
if (item.state === 'merged') {
@@ -2333,7 +2247,6 @@ function ConversationTab({
loading,
detailsLoaded,
checks,
participants: detailsParticipants,
localState,
onStateChange,
projectOrigin,
@@ -2354,7 +2267,6 @@ function ConversationTab({
loading: boolean
detailsLoaded: boolean
checks: GitHubWorkItemDetails['checks']
participants: GitHubAssignableUser[]
localState: GitHubWorkItem['state']
onStateChange: (state: GitHubWorkItem['state']) => void
projectOrigin: GitHubItemDialogProjectOrigin | undefined
@@ -2370,32 +2282,12 @@ function ConversationTab({
const [bodyDraft, setBodyDraft] = useState(body)
const [bodyEditing, setBodyEditing] = useState(false)
const [bodySaving, setBodySaving] = useState(false)
const bodyTextareaRef = useRef<HTMLTextAreaElement>(null)
const bodyTextareaFocusFrameRef = useRef<number | null>(null)
const repoAssignees = useRepoAssignees(repoPath, item.repoId)
const commentCounts = useMemo(() => getPRCommentAudienceCounts(comments), [comments])
const visibleComments = useMemo(
() => filterPRCommentsByAudience(comments, commentFilter),
[commentFilter, comments]
)
const visibleCommentGroups = useMemo(() => groupPRComments(visibleComments), [visibleComments])
const mentionOptions = useMemo(
() =>
buildMentionOptions({
item,
comments,
participants: detailsParticipants,
assignableUsers: repoAssignees.data
}),
[comments, detailsParticipants, item, repoAssignees.data]
)
const cancelBodyTextareaFocusFrame = useCallback((): void => {
if (bodyTextareaFocusFrameRef.current !== null) {
cancelAnimationFrame(bodyTextareaFocusFrameRef.current)
bodyTextareaFocusFrameRef.current = null
}
}, [])
useEffect(() => {
if (replyingTo !== null && !visibleComments.some((comment) => comment.id === replyingTo)) {
@@ -2409,19 +2301,6 @@ function ConversationTab({
}
}, [body, bodyEditing, item.id])
useEffect(() => {
if (!bodyEditing) {
cancelBodyTextareaFocusFrame()
return cancelBodyTextareaFocusFrame
}
cancelBodyTextareaFocusFrame()
bodyTextareaFocusFrameRef.current = requestAnimationFrame(() => {
bodyTextareaFocusFrameRef.current = null
bodyTextareaRef.current?.focus()
})
return cancelBodyTextareaFocusFrame
}, [bodyEditing, cancelBodyTextareaFocusFrame])
const bodySlug = useMemo(() => parseOwnerRepoFromItemUrl(item.url), [item.url])
const markdownGitHubRepo = useMemo(
() => (projectOrigin ? { owner: projectOrigin.owner, repo: projectOrigin.repo } : bodySlug),
@@ -2625,7 +2504,6 @@ function ConversationTab({
placeholder={
comment.path ? 'Reply in this review thread' : `Reply to @${comment.author}`
}
mentionOptions={mentionOptions}
onCancel={() => setReplyingTo(null)}
onSubmit={(replyBody) => handleReply(comment, replyBody)}
/>
@@ -2748,27 +2626,14 @@ function ConversationTab({
<LoaderCircle className="size-4 animate-spin text-muted-foreground" />
</div>
) : bodyEditing ? (
<MentionTextarea
textareaRef={bodyTextareaRef}
<GitHubMarkdownComposer
value={bodyDraft}
onValueChange={setBodyDraft}
onKeyDown={(event) => {
if (event.key === 'Escape') {
event.preventDefault()
setBodyDraft(body)
setBodyEditing(false)
return
}
if (isScreenSubmitShortcut(event)) {
event.preventDefault()
void handleSaveBody()
}
}}
onChange={setBodyDraft}
placeholder="Description"
rows={12}
mentionOptions={mentionOptions}
wrapperClassName="flex min-h-64 w-full items-stretch"
className="scrollbar-sleek block min-h-64 w-full resize-y rounded-md border border-input bg-background px-3 py-2 font-mono text-[13px] leading-5 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
disabled={bodySaving}
autoFocus
minHeightClassName="min-h-64"
onSubmitShortcut={() => void handleSaveBody()}
/>
) : body.trim() ? (
<CommentMarkdown
@@ -2841,7 +2706,6 @@ function ConversationTab({
repoId={item.repoId}
issueNumber={item.number}
itemType={item.type}
mentionOptions={mentionOptions}
onCommentAdded={onCommentAdded}
/>
)}
@@ -3124,25 +2988,18 @@ function CommentReactions({
function CommentReplyForm({
className,
placeholder,
mentionOptions,
onCancel,
onSubmit
}: {
className?: string
placeholder: string
mentionOptions: MentionOption[]
onCancel: () => void
onSubmit: (body: string) => Promise<boolean>
}): React.JSX.Element {
const [body, setBody] = useState('')
const [submitting, setSubmitting] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const mountedRef = useMountedRef()
useEffect(() => {
textareaRef.current?.focus()
}, [])
const submit = useCallback(async () => {
const trimmed = body.trim()
if (!trimmed || submitting) {
@@ -3166,25 +3023,14 @@ function CommentReplyForm({
return (
<div className={cn('rounded-md border border-border/50 bg-background/60 p-2', className)}>
<MentionTextarea
textareaRef={textareaRef}
<GitHubMarkdownComposer
value={body}
onValueChange={setBody}
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
return
}
if (isScreenSubmitShortcut(e)) {
e.preventDefault()
void submit()
}
}}
onChange={setBody}
placeholder={placeholder}
rows={3}
mentionOptions={mentionOptions}
className="scrollbar-sleek min-h-20 w-full resize-y rounded-md border border-input bg-transparent px-3 py-2 text-[13px] placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
disabled={submitting}
autoFocus
minHeightClassName="min-h-24"
onSubmitShortcut={() => void submit()}
/>
<div className="mt-2 flex justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onCancel}>
@@ -4049,149 +3895,6 @@ function ChecksTab({
)
}
function MentionTextarea({
value,
onValueChange,
onKeyDown,
placeholder,
rows,
className,
wrapperClassName,
mentionOptions,
textareaRef
}: {
value: string
onValueChange: (value: string) => void
onKeyDown?: (event: React.KeyboardEvent<HTMLTextAreaElement>) => void
placeholder: string
rows: number
className?: string
wrapperClassName?: string
mentionOptions: MentionOption[]
textareaRef: React.RefObject<HTMLTextAreaElement | null>
}): React.JSX.Element {
const [mentionQuery, setMentionQuery] = useState<MentionQuery | null>(null)
const [activeIndex, setActiveIndex] = useState(0)
const suggestions = useMemo(
() => (mentionQuery ? filterMentionOptions(mentionOptions, mentionQuery.query) : []),
[mentionOptions, mentionQuery]
)
const showSuggestions = mentionQuery !== null && suggestions.length > 0
const syncMentionQuery = useCallback((textarea: HTMLTextAreaElement): void => {
const nextQuery = findMentionQuery(textarea.value, textarea.selectionStart)
setMentionQuery(nextQuery)
setActiveIndex(0)
}, [])
const insertMention = useCallback(
(option: MentionOption): void => {
const textarea = textareaRef.current
const caret = textarea?.selectionStart ?? value.length
const query = textarea ? findMentionQuery(value, caret) : mentionQuery
if (!query) {
return
}
const suffix = value[caret] && !/\s/.test(value[caret]) ? ' ' : ''
const inserted = `@${option.login}${suffix}`
const nextValue = `${value.slice(0, query.atIndex)}${inserted}${value.slice(caret)}`
const nextCaret = query.atIndex + inserted.length
onValueChange(nextValue)
setMentionQuery(null)
requestAnimationFrame(() => {
textarea?.focus()
textarea?.setSelectionRange(nextCaret, nextCaret)
})
},
[mentionQuery, onValueChange, textareaRef, value]
)
return (
<div className={cn('relative min-w-0 flex-1', wrapperClassName)}>
{showSuggestions && (
<div className="absolute right-0 bottom-[calc(100%+6px)] left-0 z-50 max-h-64 overflow-y-auto rounded-md border border-border/70 bg-popover p-1 text-popover-foreground shadow-lg scrollbar-sleek">
{suggestions.map((option, index) => (
<button
key={option.login}
type="button"
onMouseDown={(event) => {
event.preventDefault()
insertMention(option)
}}
className={cn(
'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-[12px]',
index === activeIndex && 'bg-accent text-accent-foreground'
)}
>
{option.avatarUrl ? (
<img src={option.avatarUrl} alt="" className="size-5 shrink-0 rounded-full" />
) : (
<div className="flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-medium text-muted-foreground">
{option.login.slice(0, 1).toUpperCase()}
</div>
)}
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className="shrink-0 font-medium">@{option.login}</span>
{option.name && (
<>
<span className="shrink-0 text-muted-foreground">|</span>
<span className="truncate text-muted-foreground">{option.name}</span>
</>
)}
<span className="shrink-0 text-muted-foreground">|</span>
<span className="shrink-0 text-[11px] text-muted-foreground">{option.source}</span>
</span>
</button>
))}
</div>
)}
<textarea
ref={textareaRef}
value={value}
onChange={(event) => {
onValueChange(event.target.value)
syncMentionQuery(event.currentTarget)
}}
onClick={(event) => syncMentionQuery(event.currentTarget)}
onKeyUp={(event) => {
if (!['ArrowDown', 'ArrowUp', 'Enter', 'Tab', 'Escape'].includes(event.key)) {
syncMentionQuery(event.currentTarget)
}
}}
onBlur={() => setMentionQuery(null)}
onKeyDown={(event) => {
if (showSuggestions) {
if (event.key === 'ArrowDown') {
event.preventDefault()
setActiveIndex((current) => (current + 1) % suggestions.length)
return
}
if (event.key === 'ArrowUp') {
event.preventDefault()
setActiveIndex((current) => (current - 1 + suggestions.length) % suggestions.length)
return
}
if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault()
insertMention(suggestions[activeIndex] ?? suggestions[0])
return
}
if (event.key === 'Escape') {
event.preventDefault()
setMentionQuery(null)
return
}
}
onKeyDown?.(event)
}}
placeholder={placeholder}
rows={rows}
className={className}
/>
</div>
)
}
// Why: when the dialog opens for a Project row whose repo differs from the
// active workspace, mutations must target the row's actual repo via
// slug-addressed IPCs. Otherwise edits silently apply to the workspace's
@@ -5119,7 +4822,6 @@ function GHCommentComposer({
repoId,
issueNumber,
itemType,
mentionOptions,
onCommentAdded
}: {
className?: string
@@ -5127,23 +4829,12 @@ function GHCommentComposer({
repoId?: string | null
issueNumber: number
itemType: 'issue' | 'pr'
mentionOptions: MentionOption[]
onCommentAdded: (comment: PRComment) => void
}): React.JSX.Element {
const [body, setBody] = useState('')
const [submitting, setSubmitting] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const mountedRef = useMountedRef()
const autoGrow = useCallback(() => {
const el = textareaRef.current
if (!el) {
return
}
el.style.height = 'auto'
el.style.height = `${Math.max(80, Math.min(el.scrollHeight, 240))}px`
}, [])
const handleSubmit = useCallback(async () => {
const trimmed = body.trim()
if (!trimmed) {
@@ -5163,7 +4854,6 @@ function GHCommentComposer({
}
if (result.ok) {
setBody('')
requestAnimationFrame(autoGrow)
// Why: use the comment returned by GitHub so the optimistic row shows
// the real login/avatar immediately instead of waiting for a reopen.
onCommentAdded(result.comment)
@@ -5179,33 +4869,18 @@ function GHCommentComposer({
setSubmitting(false)
}
}
}, [autoGrow, body, mountedRef, repoPath, repoId, issueNumber, itemType, onCommentAdded])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (isScreenSubmitShortcut(e)) {
e.preventDefault()
handleSubmit()
}
},
[handleSubmit]
)
}, [body, mountedRef, repoPath, repoId, issueNumber, itemType, onCommentAdded])
return (
<div className={cn('flex flex-col items-start gap-2', className)}>
<MentionTextarea
textareaRef={textareaRef}
<GitHubMarkdownComposer
value={body}
onValueChange={(nextValue) => {
setBody(nextValue)
requestAnimationFrame(autoGrow)
}}
onKeyDown={handleKeyDown}
onChange={setBody}
placeholder="Add a comment…"
rows={4}
mentionOptions={mentionOptions}
wrapperClassName="flex min-h-20 w-full items-stretch"
className="scrollbar-sleek block h-20 max-h-[240px] min-h-20 w-full resize-none overflow-y-auto rounded-md border border-input bg-card px-3 py-2 text-[13px] leading-5 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
disabled={submitting}
minHeightClassName="min-h-28"
className="w-full"
onSubmitShortcut={() => void handleSubmit()}
/>
<Button
onClick={handleSubmit}
@@ -6050,7 +5725,6 @@ export default function GitHubItemDialog({
loading={loading}
detailsLoaded={detailsLoaded}
checks={checks}
participants={details?.participants ?? []}
localState={localState}
onStateChange={setLocalState}
projectOrigin={projectOrigin}
@@ -6169,7 +5843,6 @@ export default function GitHubItemDialog({
loading={loading}
detailsLoaded={detailsLoaded}
checks={checks}
participants={details?.participants ?? []}
localState={localState}
onStateChange={setLocalState}
projectOrigin={projectOrigin}
+272 -26
View File
@@ -98,6 +98,7 @@ import {
getLinearOrganizationUrlKeyFromIssueUrl
} from '../../../shared/linear-links'
import PRFilterDropdowns, { type PRFilterChange } from '@/components/github/PRFilterDropdowns'
import { GitHubMarkdownComposer } from '@/components/github/GitHubMarkdownComposer'
import { buildGitHubRepoUrl, parseGitHubIssueOrPRLink } from '@/lib/github-links'
import {
findGithubWorkItemWorkspaceAttachment,
@@ -162,7 +163,13 @@ import type {
} from '../../../shared/types'
import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard'
import { getScreenSubmitShortcutLabel, isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut'
import { useTeamStates, useTeamMembers, useTeamLabels } from '@/hooks/useIssueMetadata'
import {
useRepoAssignees,
useRepoLabels,
useTeamStates,
useTeamMembers,
useTeamLabels
} from '@/hooks/useIssueMetadata'
import {
linearCreateIssue,
linearGetIssue,
@@ -224,18 +231,6 @@ function getGitHubTaskKindPresets(kind: GitHubTaskKind): TaskQueryPreset[] {
return kind === 'prs' ? PR_TASK_QUERY_PRESETS : ISSUE_TASK_QUERY_PRESETS
}
function getRuntimeTargetForRepoId(repoId: string | null | undefined) {
if (!repoId) {
return null
}
const state = useAppStore.getState()
const target = getActiveRuntimeTarget(state.settings)
if (target.kind !== 'environment') {
return null
}
return state.repos.some((repo) => repo.id === repoId) ? target : null
}
type SourceOption = {
id: TaskSource
label: string
@@ -930,6 +925,197 @@ function GitHubAssigneeAvatar({ assignee }: { assignee: GitHubAssignableUser }):
)
}
function GitHubIssueLabelSelector({
labels,
selectedLabels,
loading,
error,
disabled,
onChange
}: {
labels: string[]
selectedLabels: string[]
loading: boolean
error: string | null
disabled: boolean
onChange: (labels: string[]) => void
}): React.JSX.Element {
const selectedSet = useMemo(() => new Set(selectedLabels), [selectedLabels])
const toggleLabel = useCallback(
(label: string) => {
onChange(
selectedSet.has(label)
? selectedLabels.filter((name) => name !== label)
: [...selectedLabels, label]
)
},
[onChange, selectedLabels, selectedSet]
)
return (
<div className="flex min-w-0 flex-col gap-1">
<label className="text-[11px] font-medium text-muted-foreground">Labels</label>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className="h-auto min-h-9 justify-start gap-2 px-3 py-2 text-left"
>
{selectedLabels.length === 0 ? (
<span className="text-muted-foreground">None</span>
) : (
<span className="flex min-w-0 flex-wrap gap-1.5">
{selectedLabels.map((label) => (
<span
key={label}
className="rounded-full border border-border/50 bg-muted/40 px-2 py-0.5 text-[11px] font-medium"
>
{label}
</span>
))}
</span>
)}
{loading ? <LoaderCircle className="ml-auto size-3.5 animate-spin" /> : null}
</Button>
</PopoverTrigger>
<PopoverContent className="popover-scroll-content scrollbar-sleek w-64 p-1" align="start">
{error ? (
<div className="px-2 py-2 text-xs text-destructive">{error}</div>
) : labels.length === 0 ? (
<div className="px-2 py-2 text-xs text-muted-foreground">No labels.</div>
) : (
labels.map((label) => (
<button
key={label}
type="button"
onClick={() => toggleLabel(label)}
className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs hover:bg-accent"
>
<span
className={cn(
'flex size-3.5 shrink-0 items-center justify-center rounded-sm border',
selectedSet.has(label)
? 'border-primary bg-primary text-primary-foreground'
: 'border-input'
)}
>
{selectedSet.has(label) ? <Check className="size-2.5" /> : null}
</span>
<span className="min-w-0 truncate">{label}</span>
</button>
))
)}
</PopoverContent>
</Popover>
</div>
)
}
function GitHubIssueAssigneeSelector({
assignees,
selectedAssignees,
loading,
error,
disabled,
onChange
}: {
assignees: GitHubAssignableUser[]
selectedAssignees: GitHubAssignableUser[]
loading: boolean
error: string | null
disabled: boolean
onChange: (assignees: GitHubAssignableUser[]) => void
}): React.JSX.Element {
const selectedLogins = useMemo(
() => new Set(selectedAssignees.map((assignee) => assignee.login.toLowerCase())),
[selectedAssignees]
)
const toggleAssignee = useCallback(
(assignee: GitHubAssignableUser) => {
const key = assignee.login.toLowerCase()
onChange(
selectedLogins.has(key)
? selectedAssignees.filter((current) => current.login.toLowerCase() !== key)
: [...selectedAssignees, assignee]
)
},
[onChange, selectedAssignees, selectedLogins]
)
return (
<div className="flex min-w-0 flex-col gap-1">
<label className="text-[11px] font-medium text-muted-foreground">Assignees</label>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className="h-auto min-h-9 justify-start gap-2 px-3 py-2 text-left"
>
{selectedAssignees.length === 0 ? (
<span className="text-muted-foreground">Unassigned</span>
) : (
<span className="flex min-w-0 items-center gap-1.5">
<span className="flex -space-x-1">
{selectedAssignees.slice(0, 3).map((assignee) => (
<GitHubAssigneeAvatar key={assignee.login} assignee={assignee} />
))}
</span>
<span className="min-w-0 truncate text-xs">
{selectedAssignees.map((assignee) => assignee.login).join(', ')}
</span>
</span>
)}
{loading ? <LoaderCircle className="ml-auto size-3.5 animate-spin" /> : null}
</Button>
</PopoverTrigger>
<PopoverContent className="popover-scroll-content scrollbar-sleek w-72 p-1" align="start">
{error ? (
<div className="px-2 py-2 text-xs text-destructive">{error}</div>
) : assignees.length === 0 ? (
<div className="px-2 py-2 text-xs text-muted-foreground">No assignable users.</div>
) : (
assignees.map((assignee) => {
const selected = selectedLogins.has(assignee.login.toLowerCase())
return (
<button
key={assignee.login}
type="button"
onClick={() => toggleAssignee(assignee)}
className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs hover:bg-accent"
>
<span
className={cn(
'flex size-3.5 shrink-0 items-center justify-center rounded-sm border',
selected
? 'border-primary bg-primary text-primary-foreground'
: 'border-input'
)}
>
{selected ? <Check className="size-2.5" /> : null}
</span>
<GitHubAssigneeAvatar assignee={assignee} />
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{assignee.login}</span>
{assignee.name ? (
<span className="block truncate text-[11px] text-muted-foreground">
{assignee.name}
</span>
) : null}
</span>
</button>
)
})
)}
</PopoverContent>
</Popover>
</div>
)
}
function GHAssigneesCell({
item,
repo
@@ -2474,6 +2660,8 @@ export default function TaskPage(): React.JSX.Element {
const [newIssueOpen, setNewIssueOpen] = useState(false)
const [newIssueTitle, setNewIssueTitle] = useState('')
const [newIssueBody, setNewIssueBody] = useState('')
const [newIssueLabels, setNewIssueLabels] = useState<string[]>([])
const [newIssueAssignees, setNewIssueAssignees] = useState<GitHubAssignableUser[]>([])
const [newIssueSubmitting, setNewIssueSubmitting] = useState(false)
const [newIssueRepoId, setNewIssueRepoId] = useState<string | null>(null)
@@ -2484,6 +2672,31 @@ export default function TaskPage(): React.JSX.Element {
() => selectedRepos.find((r) => r.id === newIssueRepoId) ?? selectedRepos[0] ?? null,
[selectedRepos, newIssueRepoId]
)
const newIssueRuntimeTarget = useMemo(() => {
if (!newIssueTargetRepo?.id) {
return null
}
const target = getActiveRuntimeTarget(settings)
if (target.kind !== 'environment') {
return null
}
return repos.some((repo) => repo.id === newIssueTargetRepo.id) ? target : null
}, [newIssueTargetRepo?.id, repos, settings])
const newIssueRepoLabels = useRepoLabels(
newIssueOpen ? (newIssueTargetRepo?.path ?? null) : null,
newIssueOpen ? (newIssueTargetRepo?.id ?? null) : null,
{ runtimeEnvironmentId: newIssueOpen ? (newIssueRuntimeTarget?.environmentId ?? null) : null }
)
const newIssueRepoAssignees = useRepoAssignees(
newIssueOpen ? (newIssueTargetRepo?.path ?? null) : null,
newIssueOpen ? (newIssueTargetRepo?.id ?? null) : null,
{ runtimeEnvironmentId: newIssueOpen ? (newIssueRuntimeTarget?.environmentId ?? null) : null }
)
useEffect(() => {
setNewIssueLabels([])
setNewIssueAssignees([])
}, [newIssueTargetRepo?.id])
const [selectedLinearIssueId, setSelectedLinearIssueId] = useState<string | null>(null)
const [selectedLinearIssueFallback, setSelectedLinearIssueFallback] =
@@ -4147,19 +4360,26 @@ export default function TaskPage(): React.JSX.Element {
}
setNewIssueSubmitting(true)
try {
const target = getRuntimeTargetForRepoId(newIssueTargetRepo.id)
const result = target
const result = newIssueRuntimeTarget
? await callRuntimeRpc<Awaited<ReturnType<typeof window.api.gh.createIssue>>>(
target,
newIssueRuntimeTarget,
'github.createIssue',
{ repo: newIssueTargetRepo.id, title, body: newIssueBody },
{
repo: newIssueTargetRepo.id,
title,
body: newIssueBody,
labels: newIssueLabels,
assignees: newIssueAssignees.map((assignee) => assignee.login)
},
{ timeoutMs: 30_000 }
)
: await window.api.gh.createIssue({
repoPath: newIssueTargetRepo.path,
repoId: newIssueTargetRepo.id,
title,
body: newIssueBody
body: newIssueBody,
labels: newIssueLabels,
assignees: newIssueAssignees.map((assignee) => assignee.login)
})
if (!result.ok) {
toast.error(result.error || 'Failed to create issue.')
@@ -4176,6 +4396,8 @@ export default function TaskPage(): React.JSX.Element {
setNewIssueOpen(false)
setNewIssueTitle('')
setNewIssueBody('')
setNewIssueLabels([])
setNewIssueAssignees([])
// Why: bump the nonce so the list refetches and shows the new issue.
setTaskRefreshNonce((current) => current + 1)
@@ -4190,15 +4412,16 @@ export default function TaskPage(): React.JSX.Element {
title,
state: 'open',
url: result.url,
labels: [],
labels: newIssueLabels,
assignees: newIssueAssignees,
updatedAt: new Date().toISOString(),
author: null
}
openGitHubDetailPage(stub)
const stubRepoId = newIssueTargetRepo.id
const fullIssuePromise = target
const fullIssuePromise = newIssueRuntimeTarget
? callRuntimeRpc<Awaited<ReturnType<typeof window.api.gh.workItem>>>(
target,
newIssueRuntimeTarget,
'github.workItem',
{ repo: newIssueTargetRepo.id, number: result.number, type: 'issue' },
{ timeoutMs: 30_000 }
@@ -4226,6 +4449,9 @@ export default function TaskPage(): React.JSX.Element {
}
}, [
newIssueBody,
newIssueAssignees,
newIssueLabels,
newIssueRuntimeTarget,
newIssueSubmitting,
newIssueTargetRepo,
newIssueTitle,
@@ -5155,6 +5381,8 @@ export default function TaskPage(): React.JSX.Element {
onClick={() => {
setNewIssueTitle('')
setNewIssueBody('')
setNewIssueLabels([])
setNewIssueAssignees([])
setNewIssueRepoId(primaryRepo?.id ?? null)
setNewIssueOpen(true)
}}
@@ -7112,7 +7340,7 @@ export default function TaskPage(): React.JSX.Element {
}}
>
<DialogContent
className="sm:max-w-lg"
className="sm:max-w-2xl"
onKeyDown={(event) => {
if (isScreenSubmitShortcut(event)) {
event.preventDefault()
@@ -7235,13 +7463,31 @@ export default function TaskPage(): React.JSX.Element {
<label className="text-[11px] font-medium text-muted-foreground">
Description (optional, markdown)
</label>
<textarea
<GitHubMarkdownComposer
value={newIssueBody}
onChange={(e) => setNewIssueBody(e.target.value)}
onChange={setNewIssueBody}
placeholder="What's going on?"
rows={6}
disabled={newIssueSubmitting}
className="w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 resize-none max-h-60 overflow-y-auto scrollbar-sleek"
minHeightClassName="min-h-40"
onSubmitShortcut={() => void handleCreateNewIssue()}
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<GitHubIssueLabelSelector
labels={newIssueRepoLabels.data}
selectedLabels={newIssueLabels}
loading={newIssueRepoLabels.loading}
error={newIssueRepoLabels.error}
disabled={newIssueSubmitting || !newIssueTargetRepo}
onChange={setNewIssueLabels}
/>
<GitHubIssueAssigneeSelector
assignees={newIssueRepoAssignees.data}
selectedAssignees={newIssueAssignees}
loading={newIssueRepoAssignees.loading}
error={newIssueRepoAssignees.error}
disabled={newIssueSubmitting || !newIssueTargetRepo}
onChange={setNewIssueAssignees}
/>
</div>
<p className="text-[10px] text-muted-foreground">{submitShortcutLabel} to submit.</p>
@@ -0,0 +1,348 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { EditorContent, useEditor } from '@tiptap/react'
import type { Editor } from '@tiptap/react'
import Placeholder from '@tiptap/extension-placeholder'
import { ImageIcon } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut'
import { createRichMarkdownExtensions } from '@/components/editor/rich-markdown-extensions'
import { RichMarkdownToolbar } from '@/components/editor/RichMarkdownToolbar'
import {
getLinkBubblePosition,
RichMarkdownLinkBubble,
type LinkBubbleState
} from '@/components/editor/RichMarkdownLinkBubble'
import { encodeRawMarkdownHtmlForRichEditor } from '@/components/editor/raw-markdown-html'
import { normalizeSoftBreaks } from '@/components/editor/rich-markdown-normalize'
type GitHubMarkdownComposerProps = {
value: string
onChange: (value: string) => void
placeholder: string
minHeightClassName?: string
className?: string
disabled?: boolean
autoFocus?: boolean
onSubmitShortcut?: () => void
}
function isHttpImageUrl(value: string): boolean {
try {
const parsed = new URL(value)
return parsed.protocol === 'https:' || parsed.protocol === 'http:'
} catch {
return false
}
}
export function GitHubMarkdownComposer({
value,
onChange,
placeholder,
minHeightClassName = 'min-h-32',
className,
disabled = false,
autoFocus = false,
onSubmitShortcut
}: GitHubMarkdownComposerProps): React.JSX.Element {
const rootRef = useRef<HTMLDivElement | null>(null)
const editorRef = useRef<Editor | null>(null)
const applyingExternalValueRef = useRef(false)
const lastSyncedMarkdownRef = useRef(value)
const onChangeRef = useRef(onChange)
const onSubmitShortcutRef = useRef(onSubmitShortcut)
const disabledRef = useRef(disabled)
const isEditingLinkRef = useRef(false)
const imageInputOpenRef = useRef(false)
const [linkBubble, setLinkBubble] = useState<LinkBubbleState | null>(null)
const [isEditingLink, setIsEditingLink] = useState(false)
const [imageInputOpen, setImageInputOpen] = useState(false)
const [imageUrl, setImageUrl] = useState('')
const imageInputRef = useRef<HTMLInputElement | null>(null)
onChangeRef.current = onChange
onSubmitShortcutRef.current = onSubmitShortcut
disabledRef.current = disabled
isEditingLinkRef.current = isEditingLink
imageInputOpenRef.current = imageInputOpen
const extensions = useMemo(
() => [
...createRichMarkdownExtensions(),
Placeholder.configure({
includeChildren: true,
placeholder
})
],
[placeholder]
)
const openLinkEditor = useCallback(() => {
const editor = editorRef.current
if (!editor || disabledRef.current) {
return
}
const position = getLinkBubblePosition(editor, rootRef.current)
if (!position) {
editor.commands.focus()
return
}
const href = editor.isActive('link') ? String(editor.getAttributes('link').href ?? '') : ''
setLinkBubble({ href, ...position })
setIsEditingLink(true)
}, [])
const editor = useEditor({
immediatelyRender: false,
extensions,
editable: !disabled,
content: encodeRawMarkdownHtmlForRichEditor(value),
contentType: 'markdown',
editorProps: {
attributes: {
class: cn('rich-markdown-editor github-markdown-composer-editor', minHeightClassName),
spellcheck: 'true'
},
handleKeyDown: (_view, event) => {
if (isScreenSubmitShortcut(event)) {
const submit = onSubmitShortcutRef.current
if (submit) {
event.preventDefault()
event.stopPropagation()
submit()
return true
}
}
const isMac = navigator.userAgent.includes('Mac')
const mod = isMac ? event.metaKey : event.ctrlKey
if (mod && event.key.toLowerCase() === 'k') {
event.preventDefault()
event.stopPropagation()
openLinkEditor()
return true
}
if (event.key === 'Escape' && imageInputOpenRef.current) {
event.preventDefault()
event.stopPropagation()
setImageInputOpen(false)
return true
}
return false
}
},
onCreate: ({ editor: nextEditor }) => {
editorRef.current = nextEditor
normalizeSoftBreaks(nextEditor)
lastSyncedMarkdownRef.current = value
if (autoFocus) {
requestAnimationFrame(() => nextEditor.commands.focus('end'))
}
},
onDestroy: () => {
editorRef.current = null
},
onUpdate: ({ editor: nextEditor }) => {
if (applyingExternalValueRef.current) {
return
}
const markdown = nextEditor.getMarkdown()
lastSyncedMarkdownRef.current = markdown
onChangeRef.current(markdown)
},
onSelectionUpdate: ({ editor: nextEditor }) => {
if (isEditingLinkRef.current) {
return
}
if (nextEditor.isActive('link')) {
const position = getLinkBubblePosition(nextEditor, rootRef.current)
if (position) {
setLinkBubble({
href: String(nextEditor.getAttributes('link').href ?? ''),
...position
})
return
}
}
setLinkBubble(null)
}
})
useEffect(() => {
if (!editor) {
return
}
editorRef.current = editor
editor.setEditable(!disabled)
}, [disabled, editor])
useEffect(() => {
if (!editor) {
return
}
if (value === lastSyncedMarkdownRef.current || value === editor.getMarkdown()) {
lastSyncedMarkdownRef.current = value
return
}
applyingExternalValueRef.current = true
try {
editor.commands.setContent(encodeRawMarkdownHtmlForRichEditor(value), {
contentType: 'markdown',
emitUpdate: false
})
normalizeSoftBreaks(editor)
lastSyncedMarkdownRef.current = value
} finally {
applyingExternalValueRef.current = false
}
}, [editor, value])
useEffect(() => {
if (imageInputOpen) {
requestAnimationFrame(() => imageInputRef.current?.focus())
}
}, [imageInputOpen])
const handleLinkSave = useCallback((href: string) => {
const editor = editorRef.current
if (!editor) {
return
}
if (href) {
if (editor.isActive('link')) {
editor.chain().focus().extendMarkRange('link').setLink({ href }).run()
} else if (editor.state.selection.empty) {
editor
.chain()
.focus()
.insertContent({
type: 'text',
text: href,
marks: [{ type: 'link', attrs: { href } }]
})
.run()
} else {
editor.chain().focus().setLink({ href }).run()
}
} else if (editor.isActive('link')) {
editor.chain().focus().extendMarkRange('link').unsetLink().run()
}
setIsEditingLink(false)
}, [])
const handleLinkRemove = useCallback(() => {
const editor = editorRef.current
if (!editor) {
return
}
editor.chain().focus().extendMarkRange('link').unsetLink().run()
setLinkBubble(null)
setIsEditingLink(false)
}, [])
const handleLinkOpen = useCallback(() => {
if (linkBubble?.href) {
window.api.shell.openUrl(linkBubble.href)
}
}, [linkBubble?.href])
const insertImageUrl = useCallback(() => {
const editor = editorRef.current
const trimmed = imageUrl.trim()
if (!editor || !trimmed) {
return
}
if (!isHttpImageUrl(trimmed)) {
toast.error('Use an http:// or https:// image URL.')
return
}
editor
.chain()
.focus()
.insertContent({ type: 'image', attrs: { src: trimmed } })
.run()
setImageUrl('')
setImageInputOpen(false)
}, [imageUrl])
return (
<div
ref={rootRef}
className={cn(
'github-markdown-composer relative overflow-hidden rounded-md border border-input bg-background shadow-xs',
disabled && 'opacity-60',
className
)}
>
<RichMarkdownToolbar
editor={editor}
onToggleLink={openLinkEditor}
onImagePick={() => {
if (!disabledRef.current) {
setImageInputOpen(true)
}
}}
/>
{imageInputOpen ? (
<form
className="github-markdown-composer-image-row"
onSubmit={(event) => {
event.preventDefault()
insertImageUrl()
}}
>
<ImageIcon className="size-3.5 shrink-0 text-muted-foreground" />
<Input
ref={imageInputRef}
value={imageUrl}
onChange={(event) => setImageUrl(event.target.value)}
onKeyDown={(event) => {
if (isScreenSubmitShortcut(event)) {
event.preventDefault()
event.stopPropagation()
insertImageUrl()
return
}
if (event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
setImageInputOpen(false)
}
}}
placeholder="https://..."
disabled={disabled}
className="h-8 min-w-0 text-xs"
/>
<Button type="submit" size="xs" disabled={disabled || !imageUrl.trim()}>
Insert
</Button>
<Button type="button" variant="ghost" size="xs" onClick={() => setImageInputOpen(false)}>
Cancel
</Button>
</form>
) : null}
<div className="max-h-[360px] overflow-y-auto scrollbar-sleek">
<EditorContent editor={editor} />
</div>
{linkBubble ? (
<RichMarkdownLinkBubble
linkBubble={linkBubble}
isEditing={isEditingLink}
onSave={handleLinkSave}
onRemove={handleLinkRemove}
onEditStart={() => setIsEditingLink(true)}
onEditCancel={() => {
setIsEditingLink(false)
if (!linkBubble.href) {
setLinkBubble(null)
}
editorRef.current?.commands.focus()
}}
onOpen={handleLinkOpen}
/>
) : null}
</div>
)
}
@@ -361,31 +361,29 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
</div>
)}
{!isMainWorktree &&
allowSkipConfirm &&
!canForceDelete && (
// Why: only show "Don't ask again" for the primary confirmation. The
// force-delete variant is a recovery path that shouldn't double as a
// preference checkpoint; see handleDelete for the matching guard.
<button
type="button"
role="checkbox"
aria-checked={dontAskAgain}
onClick={() => setDontAskAgain((prev) => !prev)}
className="flex items-center gap-2 rounded-sm px-1 py-1 text-xs text-foreground/80 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
{!isMainWorktree && allowSkipConfirm && !canForceDelete && (
// Why: only show "Don't ask again" for the primary confirmation. The
// force-delete variant is a recovery path that shouldn't double as a
// preference checkpoint; see handleDelete for the matching guard.
<button
type="button"
role="checkbox"
aria-checked={dontAskAgain}
onClick={() => setDontAskAgain((prev) => !prev)}
className="flex items-center gap-2 rounded-sm px-1 py-1 text-xs text-foreground/80 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span
className={`flex size-4 items-center justify-center rounded-sm border transition-colors ${
dontAskAgain
? 'border-foreground bg-foreground text-background'
: 'border-muted-foreground bg-transparent'
}`}
>
<span
className={`flex size-4 items-center justify-center rounded-sm border transition-colors ${
dontAskAgain
? 'border-foreground bg-foreground text-background'
: 'border-muted-foreground bg-transparent'
}`}
>
{dontAskAgain ? <Check className="size-3" strokeWidth={3} /> : null}
</span>
Don&apos;t ask again
</button>
)}
{dontAskAgain ? <Check className="size-3" strokeWidth={3} /> : null}
</span>
Don&apos;t ask again
</button>
)}
<DialogFooter>
<Button variant="outline" onClick={() => handleOpenChange(false)} disabled={isDeleting}>
+45 -13
View File
@@ -1,7 +1,7 @@
/* eslint-disable max-lines -- Why: repo metadata hooks share TTL caches and
Linear/GitHub cache invalidation entrypoints used by the issue dialog. */
import { useEffect, useRef, useState } from 'react'
import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
import {
linearTeamLabels,
linearTeamMembers,
@@ -27,6 +27,10 @@ type MetadataState<T> = {
error: string | null
}
type GitHubMetadataOptions = {
runtimeEnvironmentId?: string | null
}
// ─── GitHub ────────────────────────────────────────────────
const ghLabelStore = createMetadataRequestStore<string[]>()
@@ -34,7 +38,8 @@ const ghAssigneeStore = createMetadataRequestStore<GitHubAssignableUser[]>()
export function useRepoLabels(
repoPath: string | null,
repoId?: string | null
repoId?: string | null,
options?: GitHubMetadataOptions
): MetadataState<string[]> {
const [state, setState] = useState<MetadataState<string[]>>({
data: [],
@@ -47,7 +52,13 @@ export function useRepoLabels(
if (!repoPath && !repoId) {
return
}
const cacheKey = repoId ?? repoPath ?? ''
const runtimeEnvironmentId = options?.runtimeEnvironmentId?.trim() || null
const repoSelector = repoId ?? repoPath ?? ''
// Why: SSH/runtime metadata must not reuse host-path cache entries; the same
// repo id may resolve through a different credential/runtime boundary.
const cacheKey = runtimeEnvironmentId
? `runtime:${runtimeEnvironmentId}:${repoSelector}`
: repoSelector
const cached = getFreshMetadata(ghLabelStore, cacheKey)
if (cached) {
if (activeKeyRef.current !== cacheKey) {
@@ -66,9 +77,16 @@ export function useRepoLabels(
error: null
}))
loadMetadata(ghLabelStore, cacheKey, () =>
window.api.gh
.listLabels({ repoPath: repoPath ?? '', repoId: repoId ?? undefined })
.then((labels) => labels as string[])
runtimeEnvironmentId
? callRuntimeRpc<string[]>(
{ kind: 'environment', environmentId: runtimeEnvironmentId },
'github.listLabels',
{ repo: repoSelector },
{ timeoutMs: 15_000 }
)
: window.api.gh
.listLabels({ repoPath: repoPath ?? '', repoId: repoId ?? undefined })
.then((labels) => labels as string[])
)
.then((data) => {
if (activeKeyRef.current !== requestKey) {
@@ -87,14 +105,15 @@ export function useRepoLabels(
error: err instanceof Error ? err.message : 'Failed to load labels'
}))
})
}, [repoPath, repoId])
}, [repoPath, repoId, options?.runtimeEnvironmentId])
return state
}
export function useRepoAssignees(
repoPath: string | null,
repoId?: string | null
repoId?: string | null,
options?: GitHubMetadataOptions
): MetadataState<GitHubAssignableUser[]> {
const [state, setState] = useState<MetadataState<GitHubAssignableUser[]>>({
data: [],
@@ -107,7 +126,13 @@ export function useRepoAssignees(
if (!repoPath && !repoId) {
return
}
const cacheKey = repoId ?? repoPath ?? ''
const runtimeEnvironmentId = options?.runtimeEnvironmentId?.trim() || null
const repoSelector = repoId ?? repoPath ?? ''
// Why: SSH/runtime metadata must not reuse host-path cache entries; the same
// repo id may resolve through a different credential/runtime boundary.
const cacheKey = runtimeEnvironmentId
? `runtime:${runtimeEnvironmentId}:${repoSelector}`
: repoSelector
const cached = getFreshMetadata(ghAssigneeStore, cacheKey)
if (cached) {
if (activeKeyRef.current !== cacheKey) {
@@ -126,9 +151,16 @@ export function useRepoAssignees(
error: null
}))
loadMetadata(ghAssigneeStore, cacheKey, () =>
window.api.gh
.listAssignableUsers({ repoPath: repoPath ?? '', repoId: repoId ?? undefined })
.then((users) => users as GitHubAssignableUser[])
runtimeEnvironmentId
? callRuntimeRpc<GitHubAssignableUser[]>(
{ kind: 'environment', environmentId: runtimeEnvironmentId },
'github.listAssignableUsers',
{ repo: repoSelector },
{ timeoutMs: 15_000 }
)
: window.api.gh
.listAssignableUsers({ repoPath: repoPath ?? '', repoId: repoId ?? undefined })
.then((users) => users as GitHubAssignableUser[])
)
.then((data) => {
if (activeKeyRef.current !== requestKey) {
@@ -147,7 +179,7 @@ export function useRepoAssignees(
error: err instanceof Error ? err.message : 'Failed to load assignees'
}))
})
}, [repoPath, repoId])
}, [repoPath, repoId, options?.runtimeEnvironmentId])
return state
}
+5
View File
@@ -1248,6 +1248,11 @@ export type LinearComment = {
// ─── Issue Mutations ────────────────────────────────────────────────
export type GitHubCreateIssueFields = {
labels?: string[]
assignees?: string[]
}
export type GitHubIssueUpdate = {
state?: 'open' | 'closed'
title?: string