Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

7.5 KB
Raw Blame
import type { ProjectWorkspaceCommentActionsModel } from './use-mobile-tasks-project-workspace-comment-actions'
import { useCallback } from './mobile-tasks-dependencies'
import {
  type DetailComment,
  type GitHubProjectRow,
  commentAuthor,
  projectRowGitHubRepository,
  projectRowType,
  splitRepositorySlug
} from './mobile-tasks-legacy-foundation'
import { githubProjectCommentDelete } from './mobile-task-project-board-operations'
import {
  githubIssueCommentWrite,
  githubReviewCommentReplyWrite,
  githubReviewThreadResolve
} from './mobile-task-item-comment-operations'

export function useMobileTasksProjectThreadReplyActions(
  model: ProjectWorkspaceCommentActionsModel
) {
  const {
    activeGitHubProjectHost,
    client,
    findProjectRowRepo,
    itemReplyDrafts,
    projectEditingCommentId,
    projectMutating,
    setItemReplyDrafts,
    setProjectEditingCommentDraft,
    setProjectEditingCommentId,
    setProjectMutating,
    setProjectRowDetail,
    setProjectRowDetailError
  } = model
  const deleteProjectRowComment = useCallback(
    async (row: GitHubProjectRow, comment: DetailComment): Promise<void> => {
      if (!client || projectMutating) {
        return
      }
      const slug = splitRepositorySlug(row.content.repository)
      const commentId = Number(comment.id)
      if (!slug || !Number.isInteger(commentId) || commentId <= 0) {
        setProjectRowDetailError('This project comment cannot be deleted from mobile.')
        return
      }
      setProjectMutating(true)
      setProjectRowDetailError('')
      try {
        const reply = await githubProjectCommentDelete.request(
          client,
          {
            owner: slug.owner,
            repo: slug.repo,
            host: activeGitHubProjectHost,
            commentId
          },
          { timeoutMs: 30_000 }
        )
        const result = githubProjectCommentDelete.interpret(reply)
        if (result.ok === false) {
          throw new Error(
            typeof result.error === 'string'
              ? result.error
              : (result.error?.message ?? 'Failed to delete comment')
          )
        }
        setProjectRowDetail((current) =>
          current?.provider === 'github'
            ? {
                ...current,
                comments: current.comments.filter((candidate) => Number(candidate.id) !== commentId)
              }
            : current
        )
        if (projectEditingCommentId === String(comment.id)) {
          setProjectEditingCommentId(null)
          setProjectEditingCommentDraft('')
        }
      } catch (err) {
        setProjectRowDetailError(err instanceof Error ? err.message : 'Failed to delete comment')
      } finally {
        setProjectMutating(false)
      }
    },
    [activeGitHubProjectHost, client, projectEditingCommentId, projectMutating]
  )

  const toggleProjectGitHubReviewThread = useCallback(
    async (row: GitHubProjectRow, comment: DetailComment): Promise<void> => {
      const repo = findProjectRowRepo(row)
      if (
        !client ||
        projectMutating ||
        row.itemType !== 'PULL_REQUEST' ||
        !repo ||
        !comment.threadId
      ) {
        return
      }
      const resolve = !comment.isResolved
      setProjectMutating(true)
      setProjectRowDetailError('')
      try {
        const reply = await githubReviewThreadResolve.request(
          client,
          {
            repo: `id:${repo.id}`,
            prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost),
            threadId: comment.threadId,
            resolve
          },
          { timeoutMs: 30_000 }
        )
        if (githubReviewThreadResolve.interpret(reply) !== true) {
          throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread')
        }
        setProjectRowDetail((current) =>
          current?.provider === 'github'
            ? {
                ...current,
                comments: current.comments.map((candidate) =>
                  candidate.threadId === comment.threadId
                    ? { ...candidate, isResolved: resolve }
                    : candidate
                )
              }
            : current
        )
      } catch (err) {
        setProjectRowDetailError(
          err instanceof Error ? err.message : 'Failed to update review thread'
        )
      } finally {
        setProjectMutating(false)
      }
    },
    [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating]
  )

  const replyToProjectGitHubComment = useCallback(
    async (row: GitHubProjectRow, comment: DetailComment): Promise<void> => {
      const repo = findProjectRowRepo(row)
      if (!client || projectMutating || !repo || !row.content.number) {
        return
      }
      const key = String(comment.id)
      const body = (itemReplyDrafts[key] ?? '').trim()
      if (!body) {
        return
      }
      setProjectMutating(true)
      setProjectRowDetailError('')
      try {
        const reviewAnchor =
          row.itemType === 'PULL_REQUEST' &&
          comment.path &&
          typeof comment.line === 'number' &&
          typeof comment.id === 'number'
            ? { path: comment.path, line: comment.line, commentId: comment.id }
            : null
        const written = reviewAnchor
          ? githubReviewCommentReplyWrite.interpret(
              await githubReviewCommentReplyWrite.request(
                client,
                {
                  repo: `id:${repo.id}`,
                  prNumber: row.content.number,
                  prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost),
                  commentId: reviewAnchor.commentId,
                  body,
                  threadId: comment.threadId,
                  path: reviewAnchor.path,
                  line: reviewAnchor.line
                },
                { timeoutMs: 30_000 }
              )
            )
          : githubIssueCommentWrite.interpret(
              await githubIssueCommentWrite.request(
                client,
                {
                  repo: `id:${repo.id}`,
                  number: row.content.number,
                  prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost),
                  body: `@${commentAuthor(comment)} ${body}`,
                  type: projectRowType(row) ?? 'issue'
                },
                { timeoutMs: 30_000 }
              )
            )
        if (written.ok === false) {
          throw new Error(written.error ?? 'Failed to reply')
        }
        const reply: DetailComment = written.comment ?? {
          id: `local-${Date.now()}`,
          body,
          createdAt: new Date().toISOString(),
          author: 'You',
          path: comment.path,
          line: comment.line,
          threadId: comment.threadId
        }
        setItemReplyDrafts((current) => {
          const next = { ...current }
          delete next[key]
          return next
        })
        setProjectRowDetail((current) =>
          current?.provider === 'github'
            ? { ...current, comments: [...current.comments, reply] }
            : current
        )
      } catch (err) {
        setProjectRowDetailError(err instanceof Error ? err.message : 'Failed to reply')
      } finally {
        setProjectMutating(false)
      }
    },
    [activeGitHubProjectHost, client, findProjectRowRepo, itemReplyDrafts, projectMutating]
  )
  return Object.assign(model, {
    deleteProjectRowComment,
    toggleProjectGitHubReviewThread,
    replyToProjectGitHubComment
  })
}

export type ProjectThreadReplyActionsModel = ReturnType<
  typeof useMobileTasksProjectThreadReplyActions
>