diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1fa6fb94ad..f2bc8db65e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,6 +75,8 @@ jobs: - '.github/workflows/ci.yml' - name: Release workflow source contract run: scripts/test-release-ref-contract.sh + - name: Relay image eligibility contract + run: scripts/test-relay-image-eligibility-workflow.sh - name: Desktop release candidate contract run: scripts/test-desktop-release-candidate.sh - name: OSS desktop promotion contract diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 564cd74e9d..ddb55f8542 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -49,6 +49,10 @@ on: - "Dockerfile.push-gateway" - ".dockerignore" - ".github/workflows/docker.yml" + - "deploy/charts/buzz/Chart.yaml" + - "scripts/create-deployment-eligibility-predicate.jq" + - "scripts/select-qualified-ci-run.jq" + - "scripts/test-relay-image-eligibility-workflow.sh" - "Cargo.toml" - "Cargo.lock" - "rust-toolchain.toml" @@ -172,6 +176,10 @@ jobs: target: runtime platforms: ${{ matrix.platform }} labels: ${{ steps.meta.outputs.labels }} + build-args: | + BUZZ_SOURCE_SHA=${{ github.sha }} + BUZZ_BUILD_ID=github-actions:${{ github.run_id }}:${{ github.run_attempt }} + BUZZ_BUILD_URL=https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }} # Push by digest, not by tag — the merge job assembles the tags # into one multi-arch manifest. This is what makes the native-arm # matrix possible. @@ -190,6 +198,10 @@ jobs: target: runtime-debug platforms: ${{ matrix.platform }} labels: ${{ steps.meta.outputs.labels }} + build-args: | + BUZZ_SOURCE_SHA=${{ github.sha }} + BUZZ_BUILD_ID=github-actions:${{ github.run_id }}:${{ github.run_attempt }} + BUZZ_BUILD_URL=https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }} outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' }} cache-from: | type=registry,ref=${{ env.IMAGE_NAME }}-buildcache:${{ matrix.arch }} @@ -222,11 +234,86 @@ jobs: if-no-files-found: error retention-days: 1 + qualify: + name: Qualify relay image source + if: github.event_name != 'pull_request' + runs-on: ubuntu-24.04 + timeout-minutes: 70 + permissions: + actions: read + contents: read + outputs: + source_sha: ${{ steps.qualify.outputs.source_sha }} + ci_run_id: ${{ steps.qualify.outputs.ci_run_id }} + ci_run_attempt: ${{ steps.qualify.outputs.ci_run_attempt }} + ci_run_url: ${{ steps.qualify.outputs.ci_run_url }} + chart_version: ${{ steps.qualify.outputs.chart_version }} + steps: + - name: Checkout source + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Require successful same-SHA CI run + id: qualify + env: + GH_TOKEN: ${{ github.token }} + SOURCE_SHA: ${{ github.sha }} + run: | + set -euo pipefail + + if [[ ! "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Invalid source SHA: $SOURCE_SHA" + exit 1 + fi + + deadline=$((SECONDS + 3900)) + while (( SECONDS < deadline )); do + payload=$(gh api \ + "/repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SOURCE_SHA}&event=push&per_page=100") + successful_run=$(jq -c --arg source_sha "$SOURCE_SHA" \ + -f "$GITHUB_WORKSPACE/scripts/select-qualified-ci-run.jq" <<<"$payload") + + if [[ -n "$successful_run" ]]; then + ci_run_id=$(jq -r '.id' <<<"$successful_run") + ci_run_attempt=$(jq -r '.run_attempt' <<<"$successful_run") + ci_run_url=$(jq -r '.html_url' <<<"$successful_run") + chart_version=$(awk '/^version:/ { print $2; exit }' deploy/charts/buzz/Chart.yaml) + if [[ ! "$chart_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?$ ]]; then + echo "::error::Invalid Buzz chart version: $chart_version" + exit 1 + fi + { + echo "source_sha=$SOURCE_SHA" + echo "ci_run_id=$ci_run_id" + echo "ci_run_attempt=$ci_run_attempt" + echo "ci_run_url=$ci_run_url" + echo "chart_version=$chart_version" + } >>"$GITHUB_OUTPUT" + echo "Qualified source $SOURCE_SHA with CI run $ci_run_id (attempt $ci_run_attempt)." + exit 0 + fi + + matching=$(jq --arg source_sha "$SOURCE_SHA" '[.workflow_runs[] | select(.head_sha == $source_sha) | select(.event == "push") | select(.head_branch == "main" or .head_branch == "release")] | length' <<<"$payload") + pending=$(jq --arg source_sha "$SOURCE_SHA" '[.workflow_runs[] | select(.head_sha == $source_sha) | select(.event == "push") | select(.head_branch == "main" or .head_branch == "release") | select(.status != "completed")] | length' <<<"$payload") + if (( matching > 0 && pending == 0 )); then + echo "::error::No successful CI run exists for source $SOURCE_SHA" + jq -r --arg source_sha "$SOURCE_SHA" '.workflow_runs[] | select(.head_sha == $source_sha) | "run=\(.id) attempt=\(.run_attempt) status=\(.status) conclusion=\(.conclusion)"' <<<"$payload" + exit 1 + fi + + echo "Waiting for same-SHA CI qualification ($matching matching, $pending pending)..." + sleep 30 + done + + echo "::error::Timed out waiting for successful CI qualification of $SOURCE_SHA" + exit 1 + merge: name: Merge ${{ matrix.variant }} multi-arch manifest if: github.event_name != 'pull_request' runs-on: ubuntu-24.04 - needs: build + needs: [build, qualify] timeout-minutes: 15 permissions: contents: read @@ -286,6 +373,10 @@ jobs: env: IMAGE_NAME: ${{ env.IMAGE_NAME }} META_TAGS: ${{ steps.meta.outputs.tags }} + SOURCE_SHA: ${{ needs.qualify.outputs.source_sha }} + CI_RUN_ID: ${{ needs.qualify.outputs.ci_run_id }} + CI_RUN_ATTEMPT: ${{ needs.qualify.outputs.ci_run_attempt }} + CHART_VERSION: ${{ needs.qualify.outputs.chart_version }} run: | set -euo pipefail # Build -t flags from the metadata-action output. @@ -300,7 +391,15 @@ jobs: digests+=("${IMAGE_NAME}@sha256:${digest}") done - docker buildx imagetools create "${tags[@]}" "${digests[@]}" + annotations=( + --annotation "index:org.opencontainers.image.revision=${SOURCE_SHA}" + --annotation "index:xyz.block.buzz.build.id=github-actions:${GITHUB_RUN_ID}:${GITHUB_RUN_ATTEMPT}" + --annotation "index:xyz.block.buzz.qualification.ci-run-id=${CI_RUN_ID}" + --annotation "index:xyz.block.buzz.qualification.ci-run-attempt=${CI_RUN_ATTEMPT}" + --annotation "index:xyz.block.buzz.qualification.ci-conclusion=success" + --annotation "index:xyz.block.buzz.helm-chart.version=${CHART_VERSION}" + ) + docker buildx imagetools create "${tags[@]}" "${annotations[@]}" "${digests[@]}" # Capture the merged manifest digest for the attestation step. first_tag=$(echo "$META_TAGS" | head -n1) @@ -317,17 +416,58 @@ jobs: subject-digest: ${{ steps.manifest.outputs.digest }} push-to-registry: true + - name: Create deployment eligibility predicate + if: matrix.variant == 'release' + env: + SOURCE_SHA: ${{ needs.qualify.outputs.source_sha }} + CI_RUN_ID: ${{ needs.qualify.outputs.ci_run_id }} + CI_RUN_ATTEMPT: ${{ needs.qualify.outputs.ci_run_attempt }} + CI_RUN_URL: ${{ needs.qualify.outputs.ci_run_url }} + CHART_VERSION: ${{ needs.qualify.outputs.chart_version }} + run: | + jq -n \ + --arg source_repository "$GITHUB_REPOSITORY" \ + --arg source_ref "$GITHUB_REF" \ + --arg source_sha "$SOURCE_SHA" \ + --arg build_workflow ".github/workflows/docker.yml" \ + --argjson build_run_id "$GITHUB_RUN_ID" \ + --argjson build_run_attempt "$GITHUB_RUN_ATTEMPT" \ + --arg build_run_url "https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/attempts/${GITHUB_RUN_ATTEMPT}" \ + --arg qualification_workflow ".github/workflows/ci.yml" \ + --argjson qualification_run_id "$CI_RUN_ID" \ + --argjson qualification_run_attempt "$CI_RUN_ATTEMPT" \ + --arg qualification_run_url "$CI_RUN_URL" \ + --arg chart_version "$CHART_VERSION" \ + -f "$GITHUB_WORKSPACE/scripts/create-deployment-eligibility-predicate.jq" \ + >/tmp/deployment-eligibility.json + + - name: Attest deployment eligibility + if: matrix.variant == 'release' + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.manifest.outputs.digest }} + predicate-type: https://buzz.block.xyz/attestations/deployment-eligibility/v1 + predicate-path: /tmp/deployment-eligibility.json + push-to-registry: true + - name: Summary env: IMAGE_NAME: ${{ env.IMAGE_NAME }} VARIANT: ${{ matrix.variant }} MERGED_DIGEST: ${{ steps.manifest.outputs.digest }} META_TAGS: ${{ steps.meta.outputs.tags }} + SOURCE_SHA: ${{ needs.qualify.outputs.source_sha }} + CI_RUN_URL: ${{ needs.qualify.outputs.ci_run_url }} + CHART_VERSION: ${{ needs.qualify.outputs.chart_version }} run: | { echo "### Published \`${IMAGE_NAME}\` (${VARIANT})" echo echo "**Digest:** \`${MERGED_DIGEST}\`" + echo "**Source:** \`${SOURCE_SHA}\`" + echo "**Compatible Buzz chart:** \`${CHART_VERSION}\`" + echo "**Qualifying CI:** ${CI_RUN_URL} (success)" echo echo "**Tags:**" echo '```' @@ -338,6 +478,13 @@ jobs: echo '```' echo "gh attestation verify oci://${IMAGE_NAME}@${MERGED_DIGEST} --owner block" echo '```' + if [[ "$VARIANT" == "release" ]]; then + echo + echo "Verify deployment eligibility:" + echo '```' + echo "gh attestation verify oci://${IMAGE_NAME}@${MERGED_DIGEST} --repo block/buzz --signer-workflow block/buzz/.github/workflows/docker.yml --predicate-type https://buzz.block.xyz/attestations/deployment-eligibility/v1 --source-digest ${SOURCE_SHA}" + echo '```' + fi } >> "$GITHUB_STEP_SUMMARY" push-gateway-build: diff --git a/Dockerfile b/Dockerfile index d883ac6b01..2c1e8adbb5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -67,6 +67,14 @@ COPY --from=planner /build/recipe.json recipe.json # scoping to -p buzz-relay misses transitive deps and re-builds them later. RUN cargo chef cook --release --recipe-path recipe.json COPY . . +# Compile immutable artifact identity into the relay. Defaults preserve local +# and third-party builds that do not run in provenance-aware CI. +ARG BUZZ_SOURCE_SHA=unknown +ARG BUZZ_BUILD_ID=local +ARG BUZZ_BUILD_URL=unknown +ENV BUZZ_SOURCE_SHA=${BUZZ_SOURCE_SHA} \ + BUZZ_BUILD_ID=${BUZZ_BUILD_ID} \ + BUZZ_BUILD_URL=${BUZZ_BUILD_URL} RUN cargo build --release --locked -p buzz-relay --bin buzz-relay \ -p buzz-admin --bin buzz-admin \ -p buzz-pair-relay --bin buzz-pair-relay diff --git a/crates/buzz-relay/src/build_info.rs b/crates/buzz-relay/src/build_info.rs new file mode 100644 index 0000000000..c7073505b3 --- /dev/null +++ b/crates/buzz-relay/src/build_info.rs @@ -0,0 +1,16 @@ +//! Build-time identity compiled into the relay binary. + +/// Full source commit SHA, or `unknown` outside a provenance-aware build. +pub(crate) fn source_sha() -> &'static str { + option_env!("BUZZ_SOURCE_SHA").unwrap_or("unknown") +} + +/// Stable build identifier, or `local` outside CI. +pub(crate) fn build_id() -> &'static str { + option_env!("BUZZ_BUILD_ID").unwrap_or("local") +} + +/// Build details URL, or `unknown` outside CI. +pub(crate) fn build_url() -> &'static str { + option_env!("BUZZ_BUILD_URL").unwrap_or("unknown") +} diff --git a/crates/buzz-relay/src/lib.rs b/crates/buzz-relay/src/lib.rs index 314adad92e..800433a849 100644 --- a/crates/buzz-relay/src/lib.rs +++ b/crates/buzz-relay/src/lib.rs @@ -3,6 +3,7 @@ //! NIP-01 WebSocket relay for Buzz private team communication. mod admission; +mod build_info; /// REST API route handlers. pub mod api; diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index 1dce66e91e..653e21f093 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -413,14 +413,22 @@ async fn readiness_handler(State(state): State>) -> impl IntoRespo } } -/// Status endpoint — service name, version, uptime. -async fn status_handler(State(state): State>) -> impl IntoResponse { - let uptime_secs = state.started_at.elapsed().as_secs(); - Json(json!({ +fn status_payload(uptime_secs: u64) -> serde_json::Value { + json!({ "service": "buzz-relay", "version": env!("CARGO_PKG_VERSION"), "uptime_seconds": uptime_secs, - })) + "build": { + "source_sha": crate::build_info::source_sha(), + "id": crate::build_info::build_id(), + "url": crate::build_info::build_url(), + }, + }) +} + +/// Status endpoint — service name, version, uptime, and intrinsic build identity. +async fn status_handler(State(state): State>) -> impl IntoResponse { + Json(status_payload(state.started_at.elapsed().as_secs())) } /// `/_mesh` — live mesh status: peer table, connection/phi state, per-peer @@ -506,6 +514,23 @@ mod tests { assert!(!should_serve_spa("/arbitrary", true)); } + #[test] + fn status_payload_exposes_source_and_build_identity() { + let payload = status_payload(42); + + assert_eq!(payload["service"], "buzz-relay"); + assert_eq!(payload["version"], env!("CARGO_PKG_VERSION")); + assert_eq!(payload["uptime_seconds"], 42); + for field in ["source_sha", "id", "url"] { + assert!( + payload["build"][field] + .as_str() + .is_some_and(|value| !value.is_empty()), + "build.{field} must be a non-empty string" + ); + } + } + #[tokio::test(flavor = "current_thread")] async fn http_and_datastore_spans_are_exported_in_the_same_trace() { let exporter = InMemorySpanExporter::default(); diff --git a/deploy/charts/buzz/Chart.yaml b/deploy/charts/buzz/Chart.yaml index 9309074895..49a6fafd19 100644 --- a/deploy/charts/buzz/Chart.yaml +++ b/deploy/charts/buzz/Chart.yaml @@ -7,7 +7,7 @@ description: | PostgreSQL and Redis. Configurable for single-node evaluation (subcharts on) and HA production (external services, existingSecret). type: application -version: 0.1.7 +version: 0.1.8 appVersion: "0.1.0" home: https://github.com/block/buzz sources: @@ -24,7 +24,7 @@ maintainers: annotations: artifacthub.io/changes: | - kind: added - description: Generic init-container, volume, volume-mount, command, and args extension points for the relay Pod. + description: Optional immutable relay image digest pinning with backwards-compatible tag fallback. artifacthub.io/license: Apache-2.0 # Optional eval-only subcharts. Production deploys disable both and point diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 30cee4f406..e0645ef6fb 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -12,7 +12,7 @@ This chart has two operating profiles selected by values: ## Quickstart (eval only) ```sh -helm install buzz oci://ghcr.io/block/buzz/charts/buzz --version 0.1.7 \ +helm install buzz oci://ghcr.io/block/buzz/charts/buzz --version 0.1.8 \ --create-namespace --namespace buzz \ --set quickstart=true \ --set postgresql.enabled=true \ @@ -29,6 +29,15 @@ intent marker surfaced in NOTES.txt; the bundled services are opted in via the four `*.enabled` flags above (see `ci/quickstart-values.yaml` for the exact set CI installs). Eval-only: every bundled service is a single replica with no HA. +For immutable delivery, pin the OCI digest instead of a tag. `image.digest` +overrides `image.tag` when both are present: + +```yaml +image: + repository: ghcr.io/block/buzz + digest: sha256:<64-lowercase-hex-characters> +``` + ## Production (GitOps) The chart is designed for ArgoCD and Flux. Both render charts with `helm template`, in which mode Helm's `lookup` function returns empty — any chart-side `randAlphaNum` call would regenerate secrets on every sync. The chart-managed Secret path is **only** safe for `helm install` / `helm upgrade`. diff --git a/deploy/charts/buzz/templates/_helpers.tpl b/deploy/charts/buzz/templates/_helpers.tpl index ff070379eb..13efe0d1fd 100644 --- a/deploy/charts/buzz/templates/_helpers.tpl +++ b/deploy/charts/buzz/templates/_helpers.tpl @@ -53,9 +53,13 @@ app.kubernetes.io/component: relay {{- end -}} {{- define "buzz.image" -}} +{{- if .Values.image.digest -}} +{{- printf "%s@%s" .Values.image.repository .Values.image.digest -}} +{{- else -}} {{- $tag := default .Chart.AppVersion .Values.image.tag -}} {{- printf "%s:%s" .Values.image.repository $tag -}} {{- end -}} +{{- end -}} {{/* Name of the chart-managed Secret holding relay-identity material and any diff --git a/deploy/charts/buzz/tests/render_test.yaml b/deploy/charts/buzz/tests/render_test.yaml index 10a1a34d1f..f288f8df2d 100644 --- a/deploy/charts/buzz/tests/render_test.yaml +++ b/deploy/charts/buzz/tests/render_test.yaml @@ -195,6 +195,24 @@ tests: path: spec.template.spec.containers[0].args template: templates/deployment.yaml + - it: renders an immutable digest instead of a configured tag + set: + relayUrl: wss://buzz.example.com + ownerPubkey: "0000000000000000000000000000000000000000000000000000000000000000" + externalPostgresql.url: postgres://u:p@h:5432/d + externalRedis.url: redis://h:6379 + s3.endpoint: http://minio:9000 + s3.accessKey: a + s3.secretKey: s + image.repository: ghcr.io/block/buzz + image.tag: sha-deadbee + image.digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/block/buzz@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + template: templates/deployment.yaml + - it: appends generic Pod extensions and overrides the relay command set: relayUrl: wss://buzz.example.com diff --git a/deploy/charts/buzz/tests/validation_test.yaml b/deploy/charts/buzz/tests/validation_test.yaml index a5a0050a86..3498189c8a 100644 --- a/deploy/charts/buzz/tests/validation_test.yaml +++ b/deploy/charts/buzz/tests/validation_test.yaml @@ -2,6 +2,16 @@ suite: validation templates: - templates/deployment.yaml tests: + - it: rejects a malformed image digest + set: + relayUrl: wss://buzz.example.com + ownerPubkey: "0000000000000000000000000000000000000000000000000000000000000000" + externalPostgresql.url: postgres://u:p@h:5432/d + image.digest: sha256:not-a-digest + asserts: + - failedTemplate: + errorPattern: "image.digest: Does not match pattern" + - it: fails when relayUrl is missing set: relayUrl: "" diff --git a/deploy/charts/buzz/values.schema.json b/deploy/charts/buzz/values.schema.json index 94d369c890..aaab848fd3 100644 --- a/deploy/charts/buzz/values.schema.json +++ b/deploy/charts/buzz/values.schema.json @@ -15,6 +15,11 @@ "properties": { "repository": { "type": "string", "minLength": 1 }, "tag": { "type": "string" }, + "digest": { + "type": "string", + "pattern": "^$|^sha256:[0-9a-f]{64}$", + "description": "Optional immutable OCI image digest. When set, the chart renders repository@digest and ignores tag." + }, "pullPolicy": { "type": "string", "enum": ["Always", "IfNotPresent", "Never"] }, "pullSecrets": { "type": "array", diff --git a/deploy/charts/buzz/values.yaml b/deploy/charts/buzz/values.yaml index 448e15ca97..738c50eec3 100644 --- a/deploy/charts/buzz/values.yaml +++ b/deploy/charts/buzz/values.yaml @@ -25,6 +25,7 @@ quickstart: false image: repository: ghcr.io/block/buzz tag: "" # empty → .Chart.AppVersion + digest: "" # optional sha256:...; when set, overrides tag pullPolicy: IfNotPresent pullSecrets: [] diff --git a/desktop/src-tauri/src/managed_agents/nest.rs b/desktop/src-tauri/src/managed_agents/nest.rs index 72cf466427..3d191926a3 100644 --- a/desktop/src-tauri/src/managed_agents/nest.rs +++ b/desktop/src-tauri/src/managed_agents/nest.rs @@ -48,7 +48,7 @@ const BUZZ_CLI_SKILL_MD: &str = include_str!("nest_skill.md"); /// Template content version for AGENTS.md static content (above managed markers). /// Bump this when changing `nest_agents.md` to trigger refresh on existing installs. /// Version 1 is implicitly "before this mechanism existed" (no version file). -const NEST_AGENTS_VERSION: u32 = 4; +const NEST_AGENTS_VERSION: u32 = 5; /// Template content version for SKILL.md. /// Bump this when changing `nest_skill.md` to trigger refresh on existing installs. diff --git a/desktop/src-tauri/src/managed_agents/nest/tests.rs b/desktop/src-tauri/src/managed_agents/nest/tests.rs index bc67a5b69e..9aa1eeb098 100644 --- a/desktop/src-tauri/src/managed_agents/nest/tests.rs +++ b/desktop/src-tauri/src/managed_agents/nest/tests.rs @@ -41,6 +41,21 @@ fn nest_skill_contains_safe_mention_workflow() { assert!(BUZZ_CLI_SKILL_MD.contains("never changes membership automatically")); } +#[test] +fn nest_agents_template_separates_commit_attribution_claims() { + assert_eq!(AGENTS_MD.matches("## Git Commit Attribution").count(), 1); + assert!(AGENTS_MD.contains( + "Git authorship, co-authorship, DCO sign-off, and cryptographic signing are separate claims" + )); + assert!(AGENTS_MD + .contains("Request, approval, review, or accountability alone is not co-authorship")); + assert!(AGENTS_MD.contains("A sign-off is not an approval marker")); + assert!(AGENTS_MD.contains("Never use another person's signing key")); + assert!(AGENTS_MD.contains("inspect every outgoing commit against the actual upstream or base")); + assert!(AGENTS_MD.contains("An agent-owned repository may use the agent as author")); + assert!(!AGENTS_MD.contains("every commit MUST include a `Signed-off-by`")); +} + #[test] fn ensure_nest_creates_all_dirs_and_agents_md() { let tmp = tempfile::tempdir().unwrap(); @@ -431,6 +446,34 @@ fn refresh_agents_md_writes_version_file() { assert_eq!(version.trim(), NEST_AGENTS_VERSION.to_string()); } +#[test] +fn refresh_agents_md_upgrades_attribution_and_preserves_owned_content() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + ensure_nest_at(&root).unwrap(); + + let agents_md = root.join("AGENTS.md"); + fs::write( + &agents_md, + "# Buzz Nest\n\n## Git Commit Identity\n\n\ + - **Human sign-off (required):** every commit MUST include a `Signed-off-by`.\n\n\ + \n\ + ## Active Agents\n\n| Name | Persona | How to address |\n\ + |------|---------|----------------|\n| Kit | Builder | @Kit |\n\ + \n\n## Local Notes\n\nKeep me.\n", + ) + .unwrap(); + fs::write(root.join(".nest-agents-version"), "4\n").unwrap(); + + ensure_nest_at(&root).unwrap(); + + let content = fs::read_to_string(&agents_md).unwrap(); + assert_eq!(content.matches("## Git Commit Attribution").count(), 1); + assert!(!content.contains("**Human sign-off (required):**")); + assert!(content.contains("| Kit | Builder | @Kit |")); + assert!(content.contains("## Local Notes\n\nKeep me.")); +} + #[test] fn refresh_skill_md_writes_version_file() { let tmp = tempfile::tempdir().unwrap(); diff --git a/desktop/src-tauri/src/managed_agents/nest_agents.md b/desktop/src-tauri/src/managed_agents/nest_agents.md index 7cb7489b85..dbba2624db 100644 --- a/desktop/src-tauri/src/managed_agents/nest_agents.md +++ b/desktop/src-tauri/src/managed_agents/nest_agents.md @@ -44,15 +44,18 @@ created: 2026-01-15 - **`.scratch/` is disposable** — don't rely on it across sessions - **Stay on task** — only stage files relevant to your current work -## Git Commit Identity +## Git Commit Attribution -The human operator signs off for accountability. +Git authorship, co-authorship, DCO sign-off, and cryptographic signing are separate claims. Follow repository-local rules and the authorizing human's explicit directions; do not infer attribution from repository ownership or from who requested, approved, or reviewed the work. -- **Human sign-off (required):** every commit MUST include a `Signed-off-by` trailer for the human operator who is responsible for the agent's work. Add via `git commit --trailer "Signed-off-by: Human Name "`. One blank line must separate trailers from the commit body. -- **Human credit (`Co-authored-by`):** every commit MUST also include a `Co-authored-by` trailer for the same human operator, with identical name and email to the `Signed-off-by` line. GitHub parses `Co-authored-by` for contribution-graph credit; `Signed-off-by` alone does not grant it. Add via `git commit --trailer "Co-authored-by: Human Name "`. Place `Co-authored-by` before `Signed-off-by` in the trailer block. -- **Discovering the human's identity:** read `git config user.name` and `git config user.email` from the working repository. These reflect the human operator's configured identity for that repo (which may differ from their global config). Use these exact values for both trailers. Do NOT hardcode, guess, or prompt for the email — the repo config is the source of truth. If `git config user.email` returns empty, STOP and ask the human operator for their name and email before committing. -- **Signing:** if the agent has a registered signing key, sign commits. If not, commits will land unverified — this is acceptable until agent SSH keys are provisioned. Do NOT use the human's signing key. -- **Verify before pushing:** `git log -1` should show the human's `Signed-off-by` trailer. +- **Author:** use the person or agent required by the applicable policy. If no policy specifies an author, use the identity that actually authored the change. +- **Co-authors:** add `Co-authored-by` only for other people or agents who materially authored the change. Request, approval, review, or accountability alone is not co-authorship. +- **DCO:** add `Signed-off-by` only when repository policy requires that identity's DCO certification. A sign-off is not an approval marker. +- **Identity:** resolve required identities from trusted local configuration or explicit verified direction; never hard-code or guess them. A managed runtime may make effective `git config user.*` values identify the agent. Stop and ask if a required identity cannot be established. +- **Signing:** use only the signing key configured for the committing identity. Never use another person's signing key. +- **Verify before pushing:** inspect every outgoing commit against the actual upstream or base and confirm its attribution matches the applicable policy. + +A repository may require an accountable human as author and the implementing agent as co-author. An agent-owned repository may use the agent as author and require no human trailer. In both cases, repository-local policy controls. ## Active Agents diff --git a/desktop/src/features/channels/ui/ChannelPane.tsx b/desktop/src/features/channels/ui/ChannelPane.tsx index 19bb21b62f..89c61bdf60 100644 --- a/desktop/src/features/channels/ui/ChannelPane.tsx +++ b/desktop/src/features/channels/ui/ChannelPane.tsx @@ -371,7 +371,6 @@ export const ChannelPane = React.memo(function ChannelPane({ }), [activeChannel, currentPubkey, profiles], ); - const handleWelcomeAddAgent = React.useCallback(() => { onAddAgent?.({ beforeSend: () => @@ -387,13 +386,14 @@ export const ChannelPane = React.memo(function ChannelPane({ onWelcomeAddAgent: onAddAgent ? handleWelcomeAddAgent : undefined, }); const channelIntro = isHuddleTranscript ? null : standardChannelIntro; - const { mainTimelineEntries, visibleMessages } = useChannelPaneMessages({ - activeChannel, - isHuddleTranscript, - messages, - profiles, - threadSummaries, - }); + const { mainTimelineEntries, recentMentions, visibleMessages } = + useChannelPaneMessages({ + activeChannel, + isHuddleTranscript, + messages, + profiles, + threadSummaries, + }); useRenderScopedReactionHydration({ activeChannel, mainTimelineEntries, @@ -780,7 +780,7 @@ export const ChannelPane = React.memo(function ChannelPane({ : undefined } onSend={handleSendMessage} - profiles={profiles} + {...{ profiles, recentMentionPubkeys: recentMentions }} showBackgroundUploadProgress={false} placeholder={ timeoutState.active @@ -889,7 +889,7 @@ export const ChannelPane = React.memo(function ChannelPane({ onScrollTargetSettled={resolveScrollTarget} onToggleReaction={onToggleReaction} onUnfollowThread={onUnfollowThread} - profiles={profiles} + {...{ profiles, recentMentionPubkeys: recentMentions }} replyTargetMessage={threadReplyTargetMessage} scrollTargetHighlights={!layoutScrollTargetId} scrollTargetId={layoutScrollTargetId ?? threadScrollTargetId} diff --git a/desktop/src/features/channels/ui/useChannelPaneMessages.ts b/desktop/src/features/channels/ui/useChannelPaneMessages.ts index a2de4bbfe9..168ea66573 100644 --- a/desktop/src/features/channels/ui/useChannelPaneMessages.ts +++ b/desktop/src/features/channels/ui/useChannelPaneMessages.ts @@ -5,6 +5,7 @@ import { } from "@/features/channels/ui/ChannelPane.helpers"; import type { ChannelPaneProps } from "@/features/channels/ui/ChannelPane.types"; import { buildMainTimelineEntries } from "@/features/messages/lib/threadPanel"; +import { getRecentMentionPubkeys } from "@/features/messages/lib/recentMentionPubkeys"; import { isWelcomeExperienceChannel } from "@/features/onboarding/welcome"; type ChannelPaneMessagesOptions = Pick< @@ -46,5 +47,14 @@ export function useChannelPaneMessages({ [isHuddleTranscript, profiles, threadSummaries, visibleMessages], ); - return { mainTimelineEntries, visibleMessages }; + const recentMentionPubkeys = React.useMemo( + () => getRecentMentionPubkeys(messages, activeChannel?.channelType), + [activeChannel?.channelType, messages], + ); + + return { + mainTimelineEntries, + recentMentions: recentMentionPubkeys, + visibleMessages, + }; } diff --git a/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.test.mjs b/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.test.mjs index d7516fe691..b30008109c 100644 --- a/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.test.mjs +++ b/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.test.mjs @@ -9,25 +9,25 @@ globalThis.localStorage = { const preference = await import("./autoPinMentionedAgentsPreference.ts"); -test("defaults missing and invalid values to keeping mentioned agents pinned", () => { - assert.equal(preference.parseKeepMentionedAgentsPinned(null), true); - assert.equal(preference.parseKeepMentionedAgentsPinned("invalid"), true); +test("defaults missing and invalid values to one-time agent mentions", () => { + assert.equal(preference.parseKeepMentionedAgentsPinned(null), false); + assert.equal(preference.parseKeepMentionedAgentsPinned("invalid"), false); assert.equal(preference.parseKeepMentionedAgentsPinned("true"), true); assert.equal(preference.parseKeepMentionedAgentsPinned("false"), false); }); test("persists changes to the post-mention pinning preference", () => { - preference.setKeepMentionedAgentsPinned(false); - assert.equal(preference.getKeepMentionedAgentsPinned(), false); - assert.equal( - values.get(preference.KEEP_MENTIONED_AGENTS_PINNED_STORAGE_KEY), - "false", - ); - preference.setKeepMentionedAgentsPinned(true); assert.equal(preference.getKeepMentionedAgentsPinned(), true); assert.equal( values.get(preference.KEEP_MENTIONED_AGENTS_PINNED_STORAGE_KEY), "true", ); + + preference.setKeepMentionedAgentsPinned(false); + assert.equal(preference.getKeepMentionedAgentsPinned(), false); + assert.equal( + values.get(preference.KEEP_MENTIONED_AGENTS_PINNED_STORAGE_KEY), + "false", + ); }); diff --git a/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.ts b/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.ts index 0a3821b4e3..8f8e0b12d6 100644 --- a/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.ts +++ b/desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.ts @@ -2,7 +2,7 @@ import * as React from "react"; export const KEEP_MENTIONED_AGENTS_PINNED_STORAGE_KEY = "buzz.messages.keepMentionedAgentsPinned"; -export const DEFAULT_KEEP_MENTIONED_AGENTS_PINNED = true; +export const DEFAULT_KEEP_MENTIONED_AGENTS_PINNED = false; const listeners = new Set<() => void>(); let keepMentionedAgentsPinned = readStoredPreference(); diff --git a/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.test.mjs b/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.test.mjs new file mode 100644 index 0000000000..ad00eb296c --- /dev/null +++ b/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { getVisibleAgentAddressPubkeys } from "./getVisibleAgentAddressPubkeys.ts"; + +const DARIA = "a".repeat(64); +const RIZZ = "b".repeat(64); + +test("hides an address prefix already represented by an inline mention", () => { + assert.deepEqual( + getVisibleAgentAddressPubkeys("@Daria please review this", [DARIA], { + daria: DARIA, + }), + [], + ); +}); + +test("keeps a tag-backed prefix when its inline mention was deleted", () => { + assert.deepEqual( + getVisibleAgentAddressPubkeys("please review this", [DARIA], { + daria: DARIA, + }), + [DARIA], + ); +}); + +test("filters only addressed agents that are present inline", () => { + assert.deepEqual( + getVisibleAgentAddressPubkeys( + "@Daria please pair with someone", + [DARIA, RIZZ], + { + daria: DARIA, + rizz: RIZZ, + }, + ), + [RIZZ], + ); +}); diff --git a/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.ts b/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.ts new file mode 100644 index 0000000000..f96279628f --- /dev/null +++ b/desktop/src/features/messages/lib/getVisibleAgentAddressPubkeys.ts @@ -0,0 +1,20 @@ +import { orderMentionPubkeysByText } from "@/features/messages/lib/orderMentionPubkeys"; +import { normalizePubkey } from "@/shared/lib/pubkey"; + +/** + * Keep tag-backed address recipients visible without repeating ordinary inline + * mentions already present in the message body. + */ +export function getVisibleAgentAddressPubkeys( + body: string, + addressedPubkeys: readonly string[], + mentionPubkeysByName: Readonly> | undefined, +): string[] { + const inlineMentionPubkeys = new Set( + orderMentionPubkeysByText(body, mentionPubkeysByName, () => true), + ); + + return addressedPubkeys.filter( + (pubkey) => !inlineMentionPubkeys.has(normalizePubkey(pubkey)), + ); +} diff --git a/desktop/src/features/messages/lib/mentionCandidates.ts b/desktop/src/features/messages/lib/mentionCandidates.ts index 3ad358a0d6..659832dead 100644 --- a/desktop/src/features/messages/lib/mentionCandidates.ts +++ b/desktop/src/features/messages/lib/mentionCandidates.ts @@ -46,6 +46,7 @@ export type MentionCandidate = { secondaryLabel?: string | null; ownerPubkey?: string | null; isAgent: boolean; + isActiveAgent?: boolean; isManagedAgent?: boolean; isGlobalSearchResult?: boolean; }; diff --git a/desktop/src/features/messages/lib/mentionHighlightExtension.ts b/desktop/src/features/messages/lib/mentionHighlightExtension.ts index 82809eaabc..3d1d5d6ef7 100644 --- a/desktop/src/features/messages/lib/mentionHighlightExtension.ts +++ b/desktop/src/features/messages/lib/mentionHighlightExtension.ts @@ -202,6 +202,7 @@ export function settleAutocompleteMentionInsert( editor: { storage: object }, tr: Transaction, text: string, + settleCaret = true, ): void { const storage = mentionHighlightStorage(editor); const mentionInsert = /(?:^|[\s(])([@#])([^\s]+) $/.exec(text); @@ -222,7 +223,7 @@ export function settleAutocompleteMentionInsert( } } } - tr.setMeta(mentionHighlightKey, true); + if (settleCaret) tr.setMeta(mentionHighlightKey, true); } export function syncMentionHighlightFromProps( diff --git a/desktop/src/features/messages/lib/mentionRanking.test.mjs b/desktop/src/features/messages/lib/mentionRanking.test.mjs index 2e74bba52d..bdbf1cf11d 100644 --- a/desktop/src/features/messages/lib/mentionRanking.test.mjs +++ b/desktop/src/features/messages/lib/mentionRanking.test.mjs @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { rankMentionCandidates } from "./mentionRanking.ts"; +import { + pickDefaultAgentCandidate, + rankMentionCandidates, +} from "./mentionRanking.ts"; const CHANNEL_BRAIN_PUBKEY = "1".repeat(64); const OTHER_BRAIN_PUBKEY = "2".repeat(64); @@ -139,3 +142,108 @@ test("rankMentionCandidates: owned teams rank with runnable personas", () => { ["team", "identity"], ); }); + +test("pickDefaultAgentCandidate: active agents outrank stopped channel members", () => { + const stoppedMember = candidate({ + displayName: "Ada", + isActiveAgent: false, + isAgent: true, + isMember: true, + pubkey: CHANNEL_BRAIN_PUBKEY, + }); + const runningNonMember = candidate({ + displayName: "Bea", + isActiveAgent: true, + isAgent: true, + pubkey: OTHER_BRAIN_PUBKEY, + }); + + assert.equal( + pickDefaultAgentCandidate([stoppedMember, runningNonMember]), + runningNonMember, + ); +}); + +test("pickDefaultAgentCandidate: stable labels break ties instead of roster order", () => { + const vogue = candidate({ + displayName: "Vogue", + isActiveAgent: true, + isAgent: true, + isMember: true, + pubkey: OTHER_BRAIN_PUBKEY, + }); + const morgarita = candidate({ + displayName: "Morgarita", + isActiveAgent: true, + isAgent: true, + isMember: true, + pubkey: CHANNEL_BRAIN_PUBKEY, + }); + + assert.equal(pickDefaultAgentCandidate([vogue, morgarita]), morgarita); + assert.equal(pickDefaultAgentCandidate([morgarita, vogue]), morgarita); +}); + +test("pickDefaultAgentCandidate: runnable personas break otherwise equal ties", () => { + const plain = candidate({ + displayName: "Zulu", + isActiveAgent: true, + isAgent: true, + pubkey: OTHER_BRAIN_PUBKEY, + }); + const runnable = candidate({ + displayName: "Zulu 2", + isActiveAgent: true, + isAgent: true, + personaId: "active-persona", + pubkey: CHANNEL_BRAIN_PUBKEY, + }); + + assert.equal( + pickDefaultAgentCandidate([plain, runnable], new Set(["active-persona"])), + runnable, + ); +}); + +test("pickDefaultAgentCandidate: recent eligible mentions outrank the fallback ranking", () => { + const stoppedRecentMember = candidate({ + displayName: "Ada", + isActiveAgent: false, + isAgent: true, + isMember: true, + pubkey: CHANNEL_BRAIN_PUBKEY, + }); + const runningNonMember = candidate({ + displayName: "Bea", + isActiveAgent: true, + isAgent: true, + pubkey: OTHER_BRAIN_PUBKEY, + }); + + assert.equal( + pickDefaultAgentCandidate( + [runningNonMember, stoppedRecentMember], + new Set(), + [CHANNEL_BRAIN_PUBKEY], + ), + stoppedRecentMember, + ); +}); + +test("pickDefaultAgentCandidate: skips recent pubkeys that are not eligible candidates", () => { + const runningAgent = candidate({ + isActiveAgent: true, + isAgent: true, + pubkey: OTHER_BRAIN_PUBKEY, + }); + + assert.equal( + pickDefaultAgentCandidate([runningAgent], new Set(), ["f".repeat(64)]), + runningAgent, + ); +}); + +test("pickDefaultAgentCandidate: returns null without an addressable agent", () => { + assert.equal(pickDefaultAgentCandidate([]), null); + assert.equal(pickDefaultAgentCandidate([candidate()]), null); +}); diff --git a/desktop/src/features/messages/lib/mentionRanking.ts b/desktop/src/features/messages/lib/mentionRanking.ts index 09b9e03de7..3df5bba0b0 100644 --- a/desktop/src/features/messages/lib/mentionRanking.ts +++ b/desktop/src/features/messages/lib/mentionRanking.ts @@ -3,6 +3,7 @@ import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; export type MentionCandidateForRanking = { displayName: string | null; isAgent: boolean; + isActiveAgent?: boolean; isMember: boolean; kind: "identity" | "persona" | "team"; personaId?: string | null; @@ -51,6 +52,58 @@ function scoreMentionCandidateLabel( return null; } +export function pickDefaultAgentCandidate( + candidates: readonly T[], + activePersonaIds: ReadonlySet = new Set(), + recentMentionPubkeys: readonly string[] = [], +): T | null { + const recentMentionRankByPubkey = new Map( + recentMentionPubkeys.map((pubkey, index) => [ + normalizePubkey(pubkey), + index, + ]), + ); + return ( + candidates + .filter((candidate) => candidate.isAgent && Boolean(candidate.pubkey)) + .sort((left, right) => { + const leftRecentRank = left.pubkey + ? recentMentionRankByPubkey.get(normalizePubkey(left.pubkey)) + : undefined; + const rightRecentRank = right.pubkey + ? recentMentionRankByPubkey.get(normalizePubkey(right.pubkey)) + : undefined; + const recentDiff = + (leftRecentRank ?? recentMentionPubkeys.length) - + (rightRecentRank ?? recentMentionPubkeys.length); + if (recentDiff !== 0) return recentDiff; + const activeDiff = + Number(right.isActiveAgent === true) - + Number(left.isActiveAgent === true); + if (activeDiff !== 0) return activeDiff; + const memberDiff = Number(right.isMember) - Number(left.isMember); + if (memberDiff !== 0) return memberDiff; + const runnableDiff = + Number( + Boolean(right.personaId) && + activePersonaIds.has(right.personaId ?? ""), + ) - + Number( + Boolean(left.personaId) && + activePersonaIds.has(left.personaId ?? ""), + ); + if (runnableDiff !== 0) return runnableDiff; + const labelDiff = (left.displayName ?? "").localeCompare( + right.displayName ?? "", + undefined, + { sensitivity: "base" }, + ); + if (labelDiff !== 0) return labelDiff; + return (left.pubkey ?? "").localeCompare(right.pubkey ?? ""); + })[0] ?? null + ); +} + export function rankMentionCandidates( candidates: readonly T[], query: string, diff --git a/desktop/src/features/messages/lib/mentionSuggestionMapping.ts b/desktop/src/features/messages/lib/mentionSuggestionMapping.ts index 9be4f2c4a5..cd84aa6e8c 100644 --- a/desktop/src/features/messages/lib/mentionSuggestionMapping.ts +++ b/desktop/src/features/messages/lib/mentionSuggestionMapping.ts @@ -3,7 +3,9 @@ import type { UserProfileLookup } from "@/features/profile/lib/identity"; import { formatOwnerLabel } from "@/features/profile/lib/identity"; import type { ChannelRole, ChannelType } from "@/shared/api/types"; import { normalizePubkey } from "@/shared/lib/pubkey"; -import type { TeamMentionMember } from "./mentionCandidates"; +import type { MentionCandidate, TeamMentionMember } from "./mentionCandidates"; +import { mentionCandidateLabel } from "./mentionCandidates"; +import { pickDefaultAgentCandidate } from "./mentionRanking"; export type MentionSuggestionCandidate = { kind: "identity" | "persona" | "team"; @@ -74,3 +76,26 @@ export function mapMentionCandidateToSuggestion(opts: { role: !candidate.isAgent && candidate.role === "admin" ? "admin" : null, }; } + +export function pickDefaultAgentSuggestion(opts: { + activePersonaIds: ReadonlySet; + agentProvenanceReady: boolean; + candidates: readonly MentionCandidate[]; + channelType?: ChannelType | null; + currentPubkey?: string | null; + ownerProfiles?: UserProfileLookup; + profiles?: UserProfileLookup; + recentMentionPubkeys?: readonly string[]; +}): MentionSuggestion | null { + const candidate = pickDefaultAgentCandidate( + opts.candidates, + opts.activePersonaIds, + opts.recentMentionPubkeys, + ); + if (!candidate) return null; + return mapMentionCandidateToSuggestion({ + ...opts, + candidate, + label: mentionCandidateLabel(candidate), + }); +} diff --git a/desktop/src/features/messages/lib/recentMentionPubkeys.test.mjs b/desktop/src/features/messages/lib/recentMentionPubkeys.test.mjs new file mode 100644 index 0000000000..f8add9c84a --- /dev/null +++ b/desktop/src/features/messages/lib/recentMentionPubkeys.test.mjs @@ -0,0 +1,114 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { getRecentMentionPubkeys } from "./recentMentionPubkeys.ts"; + +const AUTHOR = "a".repeat(64); +const OLDER = "1".repeat(64); +const LATEST_FIRST = "2".repeat(64); +const LATEST_LAST = "3".repeat(64); +const REPLY_AUTHOR = "4".repeat(64); + +function message(createdAt, tags) { + return { + id: String(createdAt), + createdAt, + pubkey: AUTHOR, + author: "Author", + time: "", + body: "", + depth: 0, + tags, + }; +} + +test("returns loaded channel mentions newest-first and excludes structural author tags", () => { + assert.deepEqual( + getRecentMentionPubkeys([ + message(1, [ + ["p", AUTHOR], + ["p", OLDER], + ]), + message(2, [ + ["p", AUTHOR], + ["p", LATEST_FIRST], + ["p", LATEST_LAST], + ]), + ]), + [LATEST_LAST, LATEST_FIRST, OLDER], + ); +}); + +test("keeps a top-level mention when the event omits its structural author tag", () => { + assert.deepEqual( + getRecentMentionPubkeys([message(1, [["p", LATEST_FIRST]])]), + [LATEST_FIRST], + ); +}); + +test("filters desktop structural self-tags by identity", () => { + const parent = message(1, []); + assert.deepEqual( + getRecentMentionPubkeys([ + parent, + { + ...message(2, [ + ["p", REPLY_AUTHOR], + ["p", LATEST_FIRST], + ]), + id: "desktop-reply", + parentId: parent.id, + pubkey: REPLY_AUTHOR, + }, + ]), + [LATEST_FIRST], + ); +}); + +test("keeps an sdk-shaped reply mention that matches the parent author", () => { + const parent = message(1, []); + assert.deepEqual( + getRecentMentionPubkeys([ + parent, + { + ...message(2, [["p", AUTHOR]]), + id: "sdk-reply", + parentId: parent.id, + pubkey: REPLY_AUTHOR, + }, + ]), + [AUTHOR], + ); +}); + +test("ignores DM participant fan-out tags", () => { + assert.deepEqual( + getRecentMentionPubkeys( + [ + message(1, [ + ["p", AUTHOR], + ["p", LATEST_FIRST], + ["p", LATEST_LAST], + ]), + ], + "dm", + ), + [], + ); +}); + +test("deduplicates repeated mentions at their newest position", () => { + assert.deepEqual( + getRecentMentionPubkeys([ + message(1, [ + ["p", AUTHOR], + ["p", LATEST_FIRST], + ]), + message(2, [ + ["p", AUTHOR], + ["p", LATEST_FIRST], + ]), + ]), + [LATEST_FIRST], + ); +}); diff --git a/desktop/src/features/messages/lib/recentMentionPubkeys.ts b/desktop/src/features/messages/lib/recentMentionPubkeys.ts new file mode 100644 index 0000000000..5150904ddb --- /dev/null +++ b/desktop/src/features/messages/lib/recentMentionPubkeys.ts @@ -0,0 +1,41 @@ +import type { TimelineMessage } from "@/features/messages/types"; +import type { ChannelType } from "@/shared/api/types"; +import { normalizePubkey } from "@/shared/lib/pubkey"; + +/** + * Return explicitly addressed pubkeys from the loaded channel window, newest + * first. DM `p` tags fan out to every participant and cannot distinguish inline + * mentions, so DMs deliberately fall back to the non-recency ranking ladder. + * Desktop-authored stream events may include the message author as a structural + * `p` tag, while SDK-authored events omit it. Filter by author identity rather + * than tag position so an SDK mention of a reply target remains eligible. + */ +export function getRecentMentionPubkeys( + messages: readonly TimelineMessage[], + channelType?: ChannelType | null, +): string[] { + if (channelType === "dm") return []; + + const seen = new Set(); + const recent: string[] = []; + + for ( + let messageIndex = messages.length - 1; + messageIndex >= 0; + messageIndex -= 1 + ) { + const message = messages[messageIndex]; + const authorPubkey = normalizePubkey(message.pubkey ?? ""); + const tags = message.tags ?? []; + for (let tagIndex = tags.length - 1; tagIndex >= 0; tagIndex -= 1) { + const tag = tags[tagIndex]; + if (tag[0] !== "p" || !tag[1]) continue; + const pubkey = normalizePubkey(tag[1]); + if (!pubkey || pubkey === authorPubkey || seen.has(pubkey)) continue; + seen.add(pubkey); + recent.push(pubkey); + } + } + + return recent; +} diff --git a/desktop/src/features/messages/lib/useActiveAgentPubkeys.ts b/desktop/src/features/messages/lib/useActiveAgentPubkeys.ts new file mode 100644 index 0000000000..0ac56e72eb --- /dev/null +++ b/desktop/src/features/messages/lib/useActiveAgentPubkeys.ts @@ -0,0 +1,24 @@ +import * as React from "react"; +import type { ManagedAgent, RelayAgent } from "@/shared/api/types"; +import { normalizePubkey } from "@/shared/lib/pubkey"; + +export function useActiveAgentPubkeys( + managedAgents?: readonly ManagedAgent[], + relayAgents?: readonly RelayAgent[], +): ReadonlySet { + return React.useMemo( + () => + new Set([ + ...(managedAgents ?? []) + .filter( + (agent) => + agent.status === "running" || agent.status === "deployed", + ) + .map((agent) => normalizePubkey(agent.pubkey)), + ...(relayAgents ?? []) + .filter((agent) => agent.status !== "offline") + .map((agent) => normalizePubkey(agent.pubkey)), + ]), + [managedAgents, relayAgents], + ); +} diff --git a/desktop/src/features/messages/lib/useDefaultAgentSuggestion.ts b/desktop/src/features/messages/lib/useDefaultAgentSuggestion.ts new file mode 100644 index 0000000000..5748ca2098 --- /dev/null +++ b/desktop/src/features/messages/lib/useDefaultAgentSuggestion.ts @@ -0,0 +1,50 @@ +import * as React from "react"; +import type { MentionSuggestion } from "@/features/messages/ui/MentionAutocomplete"; +import type { UserProfileLookup } from "@/features/profile/lib/identity"; +import type { ChannelType } from "@/shared/api/types"; +import type { MentionCandidate } from "./mentionCandidates"; +import { pickDefaultAgentSuggestion } from "./mentionSuggestionMapping"; + +export function useDefaultAgentSuggestion({ + activePersonaIds, + agentProvenanceReady, + candidates, + channelType, + currentPubkey, + ownerProfiles, + profiles, + recentMentionPubkeys, +}: { + activePersonaIds: ReadonlySet; + agentProvenanceReady: boolean; + candidates: readonly MentionCandidate[]; + channelType?: ChannelType | null; + currentPubkey?: string | null; + ownerProfiles?: UserProfileLookup; + profiles?: UserProfileLookup; + recentMentionPubkeys?: readonly string[]; +}): () => MentionSuggestion | null { + return React.useCallback( + () => + pickDefaultAgentSuggestion({ + activePersonaIds, + agentProvenanceReady, + candidates, + channelType, + currentPubkey, + ownerProfiles, + profiles, + recentMentionPubkeys, + }), + [ + activePersonaIds, + agentProvenanceReady, + candidates, + channelType, + currentPubkey, + ownerProfiles, + profiles, + recentMentionPubkeys, + ], + ); +} diff --git a/desktop/src/features/messages/lib/useDrafts.ts b/desktop/src/features/messages/lib/useDrafts.ts index 2a78e88132..a3e0fcf919 100644 --- a/desktop/src/features/messages/lib/useDrafts.ts +++ b/desktop/src/features/messages/lib/useDrafts.ts @@ -114,6 +114,10 @@ function storageKey(): string { : legacyStorageKey(); } +export function getDraftStoreScope(): string { + return storageKey(); +} + function legacyStorageKey(): string { return `${LEGACY_DRAFT_STORE_KEY_PREFIX}:${currentPubkey}`; } diff --git a/desktop/src/features/messages/lib/useMentions.ts b/desktop/src/features/messages/lib/useMentions.ts index 30b7a1f48a..1a6ca1be4a 100644 --- a/desktop/src/features/messages/lib/useMentions.ts +++ b/desktop/src/features/messages/lib/useMentions.ts @@ -37,6 +37,8 @@ import { detectPrefixQuery } from "@/shared/lib/detectPrefixQuery"; import { normalizePubkey } from "@/shared/lib/pubkey"; import { channelMemberPubkeySet } from "@/shared/lib/rosterDerivations"; import { trimMapToSize } from "@/shared/lib/trimMapToSize"; +import { useActiveAgentPubkeys } from "./useActiveAgentPubkeys"; +import { useDefaultAgentSuggestion } from "./useDefaultAgentSuggestion"; import { flushMentionDebounce } from "./flushMentionDebounce"; import { useAgentMentionRevalidation } from "./agentMentionRevalidation"; import { extractMentionPubkeys } from "./extractMentionPubkeys"; @@ -61,9 +63,12 @@ import { type MentionCandidate, mentionCandidateLabel, } from "./mentionCandidates"; -const MENTION_DEBOUNCE_MS = 120; -const MENTION_SUGGESTION_LIMIT = 50; -type UseMentionsOptions = { channelType?: ChannelType | null }; +const MENTION_DEBOUNCE_MS = 120, + MENTION_SUGGESTION_LIMIT = 50; +type UseMentionsOptions = { + channelType?: ChannelType | null; + recentMentionPubkeys?: readonly string[]; +}; export function useMentions( channelId: string | null, externalMembers?: ChannelMember[], @@ -170,6 +175,10 @@ export function useMentions( ), [relayAgentsQuery.data], ); + const activeAgentPubkeys = useActiveAgentPubkeys( + managedAgentsQuery.data, + relayAgentsQuery.data, + ); const sharedChannelIds = React.useMemo( () => getSharedChannelIds(channelsQuery.data), [channelsQuery.data], @@ -276,6 +285,7 @@ export function useMentions( ? (candidate.displayName ?? current.displayName) : (current.displayName ?? candidate.displayName), isAgent: current.isAgent || candidate.isAgent, + isActiveAgent: current.isActiveAgent || candidate.isActiveAgent, isMember: current.isMember || candidate.isMember, personaId: current.personaId ?? candidate.personaId, personaName: current.personaName ?? candidate.personaName ?? null, @@ -321,6 +331,7 @@ export function useMentions( member.role === "bot" || managedAgentNamesByPubkey.has(pubkey) || relayAgentNamesByPubkey.has(pubkey), + isActiveAgent: activeAgentPubkeys.has(pubkey), ownerPubkey: profile?.ownerPubkey ?? null, personaName: personaNameByPubkey.get(pubkey) ?? null, role: member.role, @@ -342,6 +353,7 @@ export function useMentions( (activePersonaById.has(pubkey) ? pubkey : undefined), ownerPubkey: agent.ownerPubkey, isAgent: true, + isActiveAgent: agent.status !== "offline", }); } for (const agent of managedAgentsQuery.data ?? []) { @@ -351,6 +363,8 @@ export function useMentions( displayName: agent.name, isMember: false, isAgent: true, + isActiveAgent: + agent.status === "running" || agent.status === "deployed", isManagedAgent: true, personaId: agent.personaId ?? undefined, personaName: @@ -406,6 +420,7 @@ export function useMentions( ); }, [ activePersonaById, + activeAgentPubkeys, activePersonas, userSearchResults, canSearchGlobalUsers, @@ -534,6 +549,16 @@ export function useMentions( ownerProfilesQuery.data?.profiles, profiles, ]); + const getDefaultAgentSuggestion = useDefaultAgentSuggestion({ + activePersonaIds, + agentProvenanceReady: agentDirectoriesReady, + candidates: mentionCandidates, + channelType: options?.channelType, + currentPubkey, + ownerProfiles: ownerProfilesQuery.data?.profiles, + profiles, + recentMentionPubkeys: options?.recentMentionPubkeys, + }); const fetchMoreSuggestions = React.useCallback(() => { if (userSearchQuery.hasNextPage && !userSearchQuery.isFetchingNextPage) { void userSearchQuery.fetchNextPage(); @@ -938,6 +963,7 @@ export function useMentions( return { cancelMentionAutocomplete, clearMentions, + getDefaultAgentSuggestion, extractMentionPersonas, extractMentionPubkeys: extractMentionPubkeysForCurrentMentions, revalidateMentionPubkeys, diff --git a/desktop/src/features/messages/lib/useRichTextEditor.ts b/desktop/src/features/messages/lib/useRichTextEditor.ts index 36a75f32e5..87574e7972 100644 --- a/desktop/src/features/messages/lib/useRichTextEditor.ts +++ b/desktop/src/features/messages/lib/useRichTextEditor.ts @@ -71,6 +71,8 @@ export type AutocompleteEdit = { replaceFromOffset: number; replaceToOffset: number; insertText: string; + /** Keep the current selection mapped through this edit instead of moving it to the insertion. */ + preserveSelection?: boolean; /** * When set, the replaced range becomes a CustomEmojiNode for this * shortcode (followed by `insertText`, which carries the trailing space) @@ -824,6 +826,7 @@ export function useRichTextEditor({ toOffset: number, text: string, customEmojiShortcode?: string, + preserveSelection = false, ) => { if (!editor) return; const projection = buildPlainTextProjection(editor.state.doc); @@ -856,19 +859,23 @@ export function useRichTextEditor({ } const tr = editor.state.tr.insertText(text, fromPM, toPM); - // Place cursor at the end of the inserted text. We map `toPM` (the - // right end of the replaced range) through the transaction's - // mapping — that's the post-transaction position right after the - // inserted text, valid even if mark normalisation shifted things. - // (Mapping `fromPM + text.length` directly would be a pre-image - // position that may not exist in the original doc, which throws - // "Position N out of range".) - const cursorPM = tr.mapping.map(toPM); - tr.setSelection(TextSelection.create(tr.doc, cursorPM)); - settleAutocompleteMentionInsert(editor, tr, text); + if (preserveSelection) { + tr.setSelection(editor.state.selection.map(tr.doc, tr.mapping)); + } else { + // Place cursor at the end of the inserted text. We map `toPM` (the + // right end of the replaced range) through the transaction's + // mapping — that's the post-transaction position right after the + // inserted text, valid even if mark normalisation shifted things. + // (Mapping `fromPM + text.length` directly would be a pre-image + // position that may not exist in the original doc, which throws + // "Position N out of range".) + const cursorPM = tr.mapping.map(toPM); + tr.setSelection(TextSelection.create(tr.doc, cursorPM)); + } + settleAutocompleteMentionInsert(editor, tr, text, !preserveSelection); editor.view.dispatch(tr); editor.view.focus(); - reassertMentionCaretAfterFocus(editor.view); + if (!preserveSelection) reassertMentionCaretAfterFocus(editor.view); }, [editor, customEmojiWiring.resolveUrl], ); diff --git a/desktop/src/features/messages/ui/ComposerAddressControls.test.mjs b/desktop/src/features/messages/ui/ComposerAddressControls.test.mjs index 78c14aeef9..4fe40da4b3 100644 --- a/desktop/src/features/messages/ui/ComposerAddressControls.test.mjs +++ b/desktop/src/features/messages/ui/ComposerAddressControls.test.mjs @@ -78,9 +78,8 @@ test("mention control expands with automatically mentioned agents", async () => assert.match(manage.className, /(?:^|\s)pl-2(?:\s|$)/); assert.match(manage.parentElement?.className ?? "", /(?:^|\s)pl-2(?:\s|$)/); assert.match( - view.getByRole("button", { name: "Manage automatic agent mentions" }) - .parentElement?.className ?? "", - /(?:^|\s)pr-1(?:\s|$)/, + manage.parentElement?.className ?? "", + /(?:^|\s)pr-1\.5(?:\s|$)/, ); assert.match( view.getByRole("button", { name: "Manage automatic agent mentions" }) @@ -111,17 +110,21 @@ test("mention control expands with automatically mentioned agents", async () => /scale\(0.8\)/, ); } - const remove = view.getByRole("button", { - name: "Stop automatically mentioning Agent Ada", - }); + const remove = view.getByTestId("composer-address-lock-remove-agent-pubkey"); assert.match( remove.querySelector("span.absolute")?.className ?? "", /group-hover\/address:opacity-100/, ); fireEvent.click(remove); assert.deepEqual(removed, ["agent-pubkey"]); - fireEvent.click( - view.getByRole("button", { name: "Manage automatic agent mentions" }), + view.rerender(renderButton([])); + const exitingLocks = view.getByTestId("composer-address-locks"); + assert.match(exitingLocks.className, /(?:^|\s)overflow-hidden(?:\s|$)/); + assert.match( + view.getByRole("button", { name: "Mention someone" }).parentElement + ?.className ?? "", + /(?:^|\s)pr-1\.5(?:\s|$)/, ); + fireEvent.click(view.getByRole("button", { name: "Mention someone" })); assert.equal(opened, 1); }); diff --git a/desktop/src/features/messages/ui/ComposerAddressControls.tsx b/desktop/src/features/messages/ui/ComposerAddressControls.tsx index 2c8c28f5de..f141a4d2fd 100644 --- a/desktop/src/features/messages/ui/ComposerAddressControls.tsx +++ b/desktop/src/features/messages/ui/ComposerAddressControls.tsx @@ -9,6 +9,7 @@ import * as React from "react"; import { cn } from "@/shared/lib/cn"; import { UserAvatar } from "@/shared/ui/UserAvatar"; +import { Popover, PopoverAnchor, PopoverContent } from "@/shared/ui/popover"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip"; export type ComposerAddressAgent = { @@ -58,7 +59,7 @@ function AddressedAgentAvatar({ return ( void; + onConfirmationTurnOff?: () => void; onCaptureSelection: () => void; onOpen: () => void; onRemove: (pubkey: string) => void; @@ -142,89 +149,161 @@ export function ComposerMentionButton({ const visibleAgents = showAgents ? agents.slice(0, VISIBLE_AGENT_LIMIT) : []; const hiddenCount = showAgents ? agents.length - visibleAgents.length : 0; const hasAgents = visibleAgents.length > 0; + const shouldReduceMotion = useReducedMotion(); + const [showActiveChrome, setShowActiveChrome] = React.useState(hasAgents); const newlyAddedAgentPubkeys = useNewlyAddedAgentPubkeys(visibleAgents); + React.useEffect(() => { + if (hasAgents) setShowActiveChrome(true); + }, [hasAgents]); + return ( -
{ + if (!open) onConfirmationDismiss?.(); + }} + open={Boolean(confirmationTitle)} > - - + +
+ + + + + + {hasAgents + ? "Manage automatic agent mentions" + : "Mention someone"} + + + { + if (!hasAgents) setShowActiveChrome(false); + }} + > + {hasAgents ? ( + + + {visibleAgents.map((agent) => ( + + + onRemove(agent.pubkey)} + transition={ + shouldReduceMotion + ? { duration: 0 } + : addressEntryTransition + } + type="button" + > + + + + + + + Stop automatically mentioning {agent.displayName} + + + ))} + + + + ) : null} + +
+
+ {confirmationTitle ? ( + event.preventDefault()} + onOpenAutoFocus={(event) => event.preventDefault()} + side="right" + sideOffset={8} + style={{ width: "max-content" }} + > + {confirmationTitle} -
- - {hasAgents ? "Manage automatic agent mentions" : "Mention someone"} - -
- {hasAgents ? ( - - - {visibleAgents.map((agent) => ( - - - onRemove(agent.pubkey)} - transition={addressEntryTransition} - type="button" - > - - - - - - - Stop automatically mentioning {agent.displayName} - - - ))} - - - + ) : null} -
+ ); } diff --git a/desktop/src/features/messages/ui/MessageComposer.tsx b/desktop/src/features/messages/ui/MessageComposer.tsx index 1adaefd832..d4db6f5d17 100644 --- a/desktop/src/features/messages/ui/MessageComposer.tsx +++ b/desktop/src/features/messages/ui/MessageComposer.tsx @@ -4,7 +4,6 @@ import { useChannelLinks, type ChannelSuggestion, } from "@/features/messages/lib/useChannelLinks"; -import { handleAgentSnapshotPaste } from "@/features/messages/lib/agentSnapshotClipboard"; import { useComposerAutofocus } from "@/features/messages/lib/useComposerAutofocus"; import { useDrafts } from "@/features/messages/lib/useDrafts"; import { resolveSentDraftKey } from "@/features/messages/ui/draftSubmitKey"; @@ -29,7 +28,6 @@ import { } from "@/features/messages/lib/backgroundMediaUploadStore"; import { useMentions } from "@/features/messages/lib/useMentions"; import { - getPersistentAgentAudienceRevision, getPersistentAgentAudienceScope, usePersistentAgentAudience, } from "@/features/messages/lib/persistentAgentAudience"; @@ -38,10 +36,6 @@ import { useKeepMentionedAgentsPinned, } from "@/features/messages/lib/autoPinMentionedAgentsPreference"; import { useIdentityQuery } from "@/shared/api/hooks"; -import { - hasMentionClipboardHtml, - normalizeMentionClipboardHtml, -} from "@/features/messages/lib/normalizeMentionClipboard"; import { CUSTOM_EMOJI_NODE_NAME } from "@/features/messages/lib/customEmojiNode"; import { type AutocompleteEdit, @@ -51,7 +45,6 @@ import { import { useLinkEditor } from "@/features/messages/lib/useLinkEditor"; import { useComposerSpoilerParticles } from "@/features/messages/lib/useComposerSpoilerParticles"; import { useTypingBroadcast } from "@/features/messages/useTypingBroadcast"; -import { getBuzzCodeBlockClipboardText } from "@/shared/lib/codeBlockClipboard"; import { cn } from "@/shared/lib/cn"; import { ChannelAutocomplete } from "./ChannelAutocomplete"; import { ComposerReplyEditBanner } from "./ComposerReplyEditBanner"; @@ -68,6 +61,7 @@ import { useAlwaysAddressShortcut } from "./useAlwaysAddressShortcut"; import { useComposerMentionPicker } from "./useComposerMentionPicker"; import { useAutoPinMentionedAgents } from "./useAutoPinMentionedAgents"; import { useComposerContentState } from "./useComposerContentState"; +import { useComposerPasteHandler } from "./useComposerPasteHandler"; import { useDraftPersistLifecycle } from "./useDraftPersistSnapshot"; import { submitMessageEdit } from "./submitMessageEdit"; import { prepareBackgroundLinkPreviews } from "@/features/messages/lib/linkPreviewPreparationStore"; @@ -98,6 +92,7 @@ function MessageComposerImpl({ onSend, placeholder, profiles, + recentMentionPubkeys, replyTarget = null, mediaController, showBackgroundUploadProgress = true, @@ -122,8 +117,6 @@ function MessageComposerImpl({ } = useComposerLinkPreviews(previewContent, editTarget == null); const [isEmojiPickerOpen, setIsEmojiPickerOpen] = React.useState(false); const [isFormattingOpen, setIsFormattingOpen] = React.useState(false); - const [mentionOptionsOpenRequest, setMentionOptionsOpenRequest] = - React.useState(0); const [spoileredAttachmentUrls, setSpoileredAttachmentUrls] = React.useState< Set >(() => new Set()); @@ -154,6 +147,7 @@ function MessageComposerImpl({ } | null>(null); const mentions = useMentions(channelId, undefined, profiles, { channelType, + recentMentionPubkeys, }); const channelLinks = useChannelLinks(); const customEmoji = useCustomEmoji(); @@ -176,32 +170,33 @@ function MessageComposerImpl({ media.queuedAttachmentsRef.current.length === 0; const ownsDropZone = mediaController === undefined; const backgroundUpload = useBackgroundMediaUpload(); - useDraftPersistLifecycle({ - effectiveDraftKey, - channelId, - loadDraft: drafts.loadDraft, - persistDraft: drafts.persistDraft, - getMentionRefs: mentions.getDraftMentionRefs, - restoreMentionRefs: mentions.restoreDraftMentionRefs, - livePendingImeta: media.pendingImeta, - setPendingImeta: media.setPendingImeta, - getQueuedAttachments: () => media.queuedAttachmentsRef.current, - saveQueuedAttachmentsForDraft, - clearQueuedAttachments: media.clearQueuedAttachments, - restoreQueuedAttachments: media.restoreQueuedAttachments, - takeQueuedAttachmentsForDraft, - setContent: (content) => { - setComposerContent(content); - richText.setContent(content); - }, - clearContent: () => { - setComposerContent(""); - richText.clearContent(); - }, - setSpoileredAttachmentUrls, - spoileredAttachmentUrlsRef, - syncComposerContentFromEditor, - }); + const { trackAuthoredContent: trackDraftAuthoredContent } = + useDraftPersistLifecycle({ + effectiveDraftKey, + channelId, + loadDraft: drafts.loadDraft, + persistDraft: drafts.persistDraft, + getMentionRefs: mentions.getDraftMentionRefs, + restoreMentionRefs: mentions.restoreDraftMentionRefs, + livePendingImeta: media.pendingImeta, + setPendingImeta: media.setPendingImeta, + getQueuedAttachments: () => media.queuedAttachmentsRef.current, + saveQueuedAttachmentsForDraft, + clearQueuedAttachments: media.clearQueuedAttachments, + restoreQueuedAttachments: media.restoreQueuedAttachments, + takeQueuedAttachmentsForDraft, + setContent: (content) => { + setComposerContent(content); + richText.setContent(content); + }, + clearContent: () => { + setComposerContent(""); + richText.clearContent(); + }, + setSpoileredAttachmentUrls, + spoileredAttachmentUrlsRef, + syncComposerContentFromEditor, + }); // biome-ignore lint/correctness/useExhaustiveDependencies: effectiveDraftKey is the sole trigger React.useEffect(() => { media.setUploadState({ status: "idle" }); @@ -213,12 +208,16 @@ function MessageComposerImpl({ const isSendingRef = React.useRef(isSending); const isUploadingRef = React.useRef(media.isUploading); const isSubmitLockedRef = React.useRef(false); + const [isSubmitLocked, setIsSubmitLocked] = React.useState(false); const onSendRef = React.useRef(onSend); const onEditSaveRef = React.useRef(onEditSave); const onEditLastOwnMessageRef = React.useRef(onEditLastOwnMessage); const editTargetRef = React.useRef(editTarget); const extractMentionPubkeysRef = React.useRef(mentions.extractMentionPubkeys); const ownerPubkeyRef = React.useRef(ownerPubkey); + const syncAddressedAgentsFromTextRef = React.useRef<(text: string) => void>( + () => {}, + ); disabledRef.current = disabled; isSendingRef.current = isSending; isUploadingRef.current = media.isUploading; @@ -274,8 +273,13 @@ function MessageComposerImpl({ onLinkSelectionChange: (info) => onLinkSelectionChangeRef.current?.(info), onLinkShortcut: () => onLinkShortcutRef.current?.() ?? false, onUpdate: ({ cursor, linkPreviewContent, text }) => { + trackDraftAuthoredContent(text); + contentRef.current = text; setComposerContentFromText(text); setPreviewContent(linkPreviewContent); + if (!isSubmitLockedRef.current && !editTargetRef.current) { + syncAddressedAgentsFromTextRef.current(text); + } mentions.updateMentionQuery(text, cursor); channelLinks.updateChannelQuery(text, cursor); emojiAutocomplete.updateEmojiQuery(text, cursor); @@ -297,14 +301,38 @@ function MessageComposerImpl({ const persistentAudience = usePersistentAgentAudience(audienceScope); const keepMentionedAgentsPinned = useKeepMentionedAgentsPinned(); const addressPulse = useAddressMentionPulse(); - const openMentionOptionsRef = React.useRef<() => void>(() => {}); - const addInlineAgentMentionsToAudience = useAutoPinMentionedAgents({ + const { + confirmationTitle: autoPinConfirmationTitle, + dismissConfirmation: dismissAutoPinConfirmation, + promoteExplicitlyAddressedAgents, + promoteMentionedAgents, + turnOffConfirmation: turnOffAutoPinConfirmation, + } = useAutoPinMentionedAgents({ audienceScope, enabled: keepMentionedAgentsPinned, getDisplayName: mentions.getMentionDisplayName, - onOpenOptions: () => openMentionOptionsRef.current(), onPulse: addressPulse.pulseOne, + onTurnOff: () => setKeepMentionedAgentsPinned(false), }); + const restoreAddressedAgentMentionsRef = React.useRef< + ( + pubkeys?: readonly string[], + allowedUnpinnedPubkeys?: readonly string[], + ) => string + >(() => ""); + const restoreAddressedAgentMentionsFrameRef = React.useRef( + null, + ); + const channelIdRef = React.useRef(channelId); + channelIdRef.current = channelId; + React.useEffect( + () => () => { + if (restoreAddressedAgentMentionsFrameRef.current !== null) { + cancelAnimationFrame(restoreAddressedAgentMentionsFrameRef.current); + } + }, + [], + ); const mentionSendFlow = useMentionSendFlow({ channelId, channelLinks, @@ -315,8 +343,23 @@ function MessageComposerImpl({ emojiAutocomplete, mentions, onAddressedAgentsSendStarted: addressPulse.pulseMany, + onAddressedAgentsComposerCleared: (pubkeys) => + restoreAddressedAgentMentionsRef.current(pubkeys), onAddressedAgentsSendFailed: addressPulse.shakeMany, - onInlineAgentMentionsSent: addInlineAgentMentionsToAudience, + onAddressedAgentsSendSucceeded: (pubkeys, newlyPinnedPubkeys) => { + if (newlyPinnedPubkeys.length === 0) return; + const sentChannelId = channelId; + if (restoreAddressedAgentMentionsFrameRef.current !== null) { + cancelAnimationFrame(restoreAddressedAgentMentionsFrameRef.current); + } + restoreAddressedAgentMentionsFrameRef.current = requestAnimationFrame( + () => { + restoreAddressedAgentMentionsFrameRef.current = null; + if (channelIdRef.current !== sentChannelId) return; + restoreAddressedAgentMentionsRef.current(pubkeys, newlyPinnedPubkeys); + }, + ); + }, onPrepareSendChannel, onSendRef, richText, @@ -394,6 +437,7 @@ function MessageComposerImpl({ edit.replaceToOffset, edit.insertText, edit.customEmojiShortcode, + edit.preserveSelection, ); }, [richText.replacePlainTextRange], @@ -403,17 +447,30 @@ function MessageComposerImpl({ lockedAgents, lockedAgentPubkeys, removeAddressedAgent, + restoreAddressedAgentMentions, selectMentionSuggestion, + syncAddressedAgentsFromText, toggleAlwaysAddressAgent, } = useAgentAddressLockPicker({ applyAutocompleteEdit, audience: persistentAudience, audienceScope, mentions, + onAddressAgentMention: (suggestion) => + promoteExplicitlyAddressedAgents({ + pubkeys: suggestion.pubkey ? [suggestion.pubkey] : [], + }), + onAutoPinAgentMention: (suggestion) => { + promoteMentionedAgents({ + pubkeys: suggestion.pubkey ? [suggestion.pubkey] : [], + }); + }, onPulseAddressLock: addressPulse.pulseOne, profiles, richText, }); + restoreAddressedAgentMentionsRef.current = restoreAddressedAgentMentions; + syncAddressedAgentsFromTextRef.current = syncAddressedAgentsFromText; const applyChannelInsert = React.useCallback( (suggestion: ChannelSuggestion) => { const { cursor } = richText.getPlainTextAndCursor(); @@ -481,15 +538,12 @@ function MessageComposerImpl({ () => openMentionPicker(false), [openMentionPicker], ); - const openMentionOptions = React.useCallback(() => { - openMentionSettings(); - setMentionOptionsOpenRequest((request) => request + 1); - }, [openMentionSettings]); - openMentionOptionsRef.current = openMentionOptions; const handleAlwaysAddressShortcut = useAlwaysAddressShortcut({ enabled: Boolean(audienceScope && editTarget == null), + lockedAgent: lockedAgents[0], mentions, onOpenPicker: openMentionPicker, + onSelect: selectMentionSuggestion, onToggle: toggleAlwaysAddressAgent, }); const submitMessage = React.useCallback(async () => { @@ -561,6 +615,7 @@ function MessageComposerImpl({ return; } isSubmitLockedRef.current = true; + setIsSubmitLocked(true); onPreparingMentionSendChange?.(true); try { const preparedLinkPreviews = getReadyLinkPreviewTags().some( @@ -570,9 +625,6 @@ function MessageComposerImpl({ : prepareBackgroundLinkPreviews(getLiveLinkPreviewCandidates()); await mentionSendFlow.sendMessageWithMentionFlow({ addressedAgentPubkeys: persistentAudience.pubkeys, - audienceRevision: audienceScope - ? getPersistentAgentAudienceRevision(audienceScope) - : 0, capturedChannelId: channelId, capturedThreadContext, pendingImeta: currentPendingImeta, @@ -589,6 +641,7 @@ function MessageComposerImpl({ }); } finally { isSubmitLockedRef.current = false; + setIsSubmitLocked(false); onPreparingMentionSendChange?.(false); } }, [ @@ -615,7 +668,6 @@ function MessageComposerImpl({ syncComposerContentFromEditor, onCaptureSendContext, onPreparingMentionSendChange, - audienceScope, persistentAudience.pubkeys, isEditSubmissionLocked, effectiveDraftKey, @@ -713,74 +765,12 @@ function MessageComposerImpl({ onCancelEdit, ], ); - // ── Media paste + ⌘K link shortcut via Tiptap editorProps ────────── - const uploadFileRef = React.useRef(media.uploadFile); - uploadFileRef.current = media.uploadFile; - React.useEffect(() => { - if (!richText.editor) return; - richText.editor.setOptions({ - editorProps: { - ...richText.editor.options.editorProps, - handlePaste: (_view, event) => { - // --- File paste --- - // Any actual file (image, video, document, …) pastes as an - // attachment. String/text items have kind "string", so plain-text - // and code-block paste fall through to the handlers below. - const items = Array.from(event.clipboardData?.items ?? []); - const mediaItem = items.find((item) => item.kind === "file"); - if (mediaItem) { - const file = mediaItem.getAsFile(); - if (file) { - void uploadFileRef.current(file); - } - return true; - } - // --- Buzz code-block paste --- - // The code block copy button writes a small Buzz marker alongside - // plain text. Use it to paste back as a literal code block so Markdown - // parsing cannot reshape indentation, fence markers, or headings. - const codeBlockText = getBuzzCodeBlockClipboardText( - event.clipboardData, - ); - if (codeBlockText !== null) { - event.preventDefault(); - richText.editor - ?.chain() - .focus() - .insertContent([ - { - type: "codeBlock", - content: - codeBlockText.length > 0 - ? [{ type: "text", text: codeBlockText }] - : [], - }, - { type: "paragraph" }, - ]) - .run(); - scrollComposerToBottom(); - return true; - } - // Restore Buzz snapshots before normal styled-HTML normalization. - if (handleAgentSnapshotPaste(event, media.setPendingImeta)) - return true; - // Strip mention/channel wrappers that Tiptap would misread as bold. - const html = event.clipboardData?.getData("text/html"); - if (html && hasMentionClipboardHtml(html)) { - const cleanHtml = normalizeMentionClipboardHtml(html); - event.preventDefault(); - _view.pasteHTML(cleanHtml); - return true; - } - const plainText = event.clipboardData?.getData("text/plain") ?? ""; - if (plainText.includes("\n")) { - scrollComposerToBottom(); - } - return false; - }, - }, - }); - }, [media.setPendingImeta, richText.editor, scrollComposerToBottom]); + useComposerPasteHandler({ + editor: richText.editor, + scrollToBottom: scrollComposerToBottom, + setPendingImeta: media.setPendingImeta, + uploadFile: media.uploadFile, + }); // ── Send button state ─────────────────────────────────────────────── const sendDisabled = composerDisabled || @@ -858,6 +848,7 @@ function MessageComposerImpl({ layoutMode === "standalone" && "backdrop-blur-md dark:backdrop-blur-xl", )} + data-submit-locked={isSubmitLocked ? "true" : "false"} data-testid="message-composer" onDragEnter={ownsDropZone ? media.handleDragEnter : undefined} onDragLeave={ownsDropZone ? media.handleDragLeave : undefined} @@ -904,7 +895,6 @@ function MessageComposerImpl({ ? setKeepMentionedAgentsPinned : undefined } - openOptionsRequest={mentionOptionsOpenRequest} onToggleAlwaysAddressAgent={ audienceScope && editTarget == null ? toggleAlwaysAddressAgent @@ -973,6 +963,7 @@ function MessageComposerImpl({ Promise; placeholder?: string; profiles?: UserProfileLookup; + /** Explicit mention pubkeys from the loaded channel window, newest first. */ + recentMentionPubkeys?: readonly string[]; replyTarget?: { author: string; body: string; diff --git a/desktop/src/features/messages/ui/MessageComposerDraftImagePersist.test.mjs b/desktop/src/features/messages/ui/MessageComposerDraftImagePersist.test.mjs index 46b5d91d5b..e5f08b6ebd 100644 --- a/desktop/src/features/messages/ui/MessageComposerDraftImagePersist.test.mjs +++ b/desktop/src/features/messages/ui/MessageComposerDraftImagePersist.test.mjs @@ -585,6 +585,225 @@ test("draft_lifecycle_empty_target_clears_stale_mention_refs", async () => { await handle.unmount(); }); +test("draft_lifecycle_persists_an_explicit_clear_before_async_rerender", async () => { + const DRAFT_KEY = "chan-clear-race"; + setupStore("pubkey-clear-race"); + persistDraftEntry(DRAFT_KEY, "draft text", DRAFT_KEY, [], []); + + let editorContent = ""; + let trackAuthoredContent; + const spoileredRef = { current: new Set() }; + + function HarnessComposer() { + ({ trackAuthoredContent } = useDraftPersistLifecycle({ + effectiveDraftKey: DRAFT_KEY, + channelId: DRAFT_KEY, + loadDraft: loadDraftEntry, + persistDraft: persistDraftEntry, + getMentionRefs: () => [], + restoreMentionRefs: () => {}, + livePendingImeta: [], + setPendingImeta: () => {}, + setContent: (content) => { + editorContent = content; + }, + clearContent: () => { + editorContent = ""; + }, + setSpoileredAttachmentUrls: () => {}, + spoileredAttachmentUrlsRef: spoileredRef, + syncComposerContentFromEditor: () => editorContent, + })); + return null; + } + + const handle = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, "draft text"); + + trackAuthoredContent(""); + assert.equal( + loadDraftEntry(DRAFT_KEY), + undefined, + "the authoritative update removes the stale body even while editor reads lag", + ); + + await handle.unmount(); + assert.equal( + loadDraftEntry(DRAFT_KEY), + undefined, + "async settlement must not repersist the deleted body", + ); + + const remounted = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, "", "the deleted body must not be restored"); + await remounted.unmount(); +}); + +test("draft_lifecycle_clear_caption_preserves_image_and_spoiler_on_remount", async () => { + const DRAFT_KEY = "chan-clear-caption-image"; + setupStore("pubkey-clear-caption-image"); + persistDraftEntry(DRAFT_KEY, "caption", DRAFT_KEY, [IMG_A], [IMG_A.url]); + + let editorContent = ""; + let pendingImeta = []; + let spoileredUrls = new Set(); + let trackAuthoredContent; + + function HarnessComposer() { + ({ trackAuthoredContent } = useDraftPersistLifecycle({ + effectiveDraftKey: DRAFT_KEY, + channelId: DRAFT_KEY, + loadDraft: loadDraftEntry, + persistDraft: persistDraftEntry, + getMentionRefs: () => [], + restoreMentionRefs: () => {}, + livePendingImeta: pendingImeta, + setPendingImeta: (imeta) => { + pendingImeta = imeta; + }, + setContent: (content) => { + editorContent = content; + }, + clearContent: () => { + editorContent = ""; + }, + setSpoileredAttachmentUrls: (urls) => { + spoileredUrls = urls; + }, + spoileredAttachmentUrlsRef: { + get current() { + return spoileredUrls; + }, + }, + syncComposerContentFromEditor: () => editorContent, + })); + return null; + } + + const handle = await mountStrictMode(HarnessComposer); + trackAuthoredContent(""); + editorContent = ""; + await handle.unmount(); + + const remounted = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, ""); + assert.equal(pendingImeta[0]?.url, IMG_A.url); + assert.deepEqual([...spoileredUrls], [IMG_A.url]); + assert.equal(loadDraftEntry(DRAFT_KEY)?.content, ""); + await remounted.unmount(); +}); + +test("draft_lifecycle_clear_caption_preserves_queued_file_on_remount", async () => { + const DRAFT_KEY = "chan-clear-caption-file"; + setupStore("pubkey-clear-caption-file"); + persistDraftEntry(DRAFT_KEY, "caption", DRAFT_KEY, [], []); + const FILE_A = { + file: new File(["report"], "report.pdf", { type: "application/pdf" }), + id: 9, + spoilered: true, + }; + + let editorContent = ""; + let queuedAttachments = [FILE_A]; + let trackAuthoredContent; + const spoileredRef = { current: new Set() }; + + function HarnessComposer() { + ({ trackAuthoredContent } = useDraftPersistLifecycle({ + effectiveDraftKey: DRAFT_KEY, + channelId: DRAFT_KEY, + loadDraft: loadDraftEntry, + persistDraft: persistDraftEntry, + getMentionRefs: () => [], + restoreMentionRefs: () => {}, + livePendingImeta: [], + setPendingImeta: () => {}, + getQueuedAttachments: () => queuedAttachments, + saveQueuedAttachmentsForDraft, + clearQueuedAttachments: () => { + queuedAttachments = []; + }, + restoreQueuedAttachments: (attachments) => { + queuedAttachments = attachments; + }, + takeQueuedAttachmentsForDraft, + setContent: (content) => { + editorContent = content; + }, + clearContent: () => { + editorContent = ""; + }, + setSpoileredAttachmentUrls: () => {}, + spoileredAttachmentUrlsRef: spoileredRef, + syncComposerContentFromEditor: () => editorContent, + })); + return null; + } + + saveQueuedAttachmentsForDraft(DRAFT_KEY, [FILE_A]); + const handle = await mountStrictMode(HarnessComposer); + trackAuthoredContent(""); + editorContent = ""; + await handle.unmount(); + + const remounted = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, ""); + assert.equal(queuedAttachments[0]?.file.name, "report.pdf"); + assert.equal(queuedAttachments[0]?.spoilered, true); + await remounted.unmount(); +}); + +test("draft_lifecycle_clear_authority_is_scoped_to_relay_and_identity", async () => { + const DRAFT_KEY = "shared-key"; + installFreshLocalStorage(); + clearAllDrafts(); + initDraftStore("pubkey-a", "wss://relay-a.example"); + persistDraftEntry(DRAFT_KEY, "workspace A", DRAFT_KEY, [], []); + + let editorContent = ""; + let trackAuthoredContent; + const spoileredRef = { current: new Set() }; + function HarnessComposer() { + ({ trackAuthoredContent } = useDraftPersistLifecycle({ + effectiveDraftKey: DRAFT_KEY, + channelId: DRAFT_KEY, + loadDraft: loadDraftEntry, + persistDraft: persistDraftEntry, + getMentionRefs: () => [], + restoreMentionRefs: () => {}, + livePendingImeta: [], + setPendingImeta: () => {}, + setContent: (content) => { + editorContent = content; + }, + clearContent: () => { + editorContent = ""; + }, + setSpoileredAttachmentUrls: () => {}, + spoileredAttachmentUrlsRef: spoileredRef, + syncComposerContentFromEditor: () => editorContent, + })); + return null; + } + + const workspaceA = await mountStrictMode(HarnessComposer); + trackAuthoredContent(""); + editorContent = ""; + await workspaceA.unmount(); + + initDraftStore("pubkey-b", "wss://relay-b.example"); + persistDraftEntry(DRAFT_KEY, "workspace B", DRAFT_KEY, [], []); + const workspaceB = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, "workspace B"); + await workspaceB.unmount(); + assert.equal(loadDraftEntry(DRAFT_KEY)?.content, "workspace B"); + + initDraftStore("pubkey-a", "wss://relay-a.example"); + const workspaceARemount = await mountStrictMode(HarnessComposer); + assert.equal(editorContent, "", "workspace A stale text must stay cleared"); + await workspaceARemount.unmount(); +}); + test("draft_lifecycle_preserves_local_files_across_a_b_a_switch", async () => { setupStore("pubkey-switch-files"); const FILE_A = { diff --git a/desktop/src/features/messages/ui/MessageComposerToolbar.tsx b/desktop/src/features/messages/ui/MessageComposerToolbar.tsx index d4e2284b85..5d5a1f5876 100644 --- a/desktop/src/features/messages/ui/MessageComposerToolbar.tsx +++ b/desktop/src/features/messages/ui/MessageComposerToolbar.tsx @@ -26,6 +26,7 @@ const ignoreAddressRemoval = () => {}; export const MessageComposerToolbar = React.memo( function MessageComposerToolbar({ addressedAgents = NO_ADDRESSED_AGENTS, + autoPinConfirmationTitle, composerDisabled, editor, extraActions, @@ -35,6 +36,8 @@ export const MessageComposerToolbar = React.memo( isSending, isUploading, onCaptureSelection, + onAutoPinConfirmationDismiss, + onAutoPinConfirmationTurnOff, onEmojiPickerOpenChange, onEmojiSelect, onFormattingToggle, @@ -47,6 +50,7 @@ export const MessageComposerToolbar = React.memo( shakeVersionByPubkey, }: { addressedAgents?: readonly ComposerAddressAgent[]; + autoPinConfirmationTitle?: string | null; composerDisabled: boolean; editor: Editor | null; extraActions?: React.ReactNode; @@ -56,6 +60,8 @@ export const MessageComposerToolbar = React.memo( isSending: boolean; isUploading: boolean; onCaptureSelection: () => void; + onAutoPinConfirmationDismiss?: () => void; + onAutoPinConfirmationTurnOff?: () => void; onEmojiPickerOpenChange: (open: boolean) => void; onEmojiSelect: (emoji: string) => void; onFormattingToggle: (pressed: boolean) => void; @@ -175,7 +181,10 @@ export const MessageComposerToolbar = React.memo( > import("./DiffMessage")); @@ -280,10 +280,12 @@ export const MessageRow = React.memo( return Object.keys(values).length > 0 ? values : undefined; }, [isKnownAgentPubkey, mentionPubkeysByName]); const addressedAgentPubkeys = React.useMemo(() => { - return getAgentAddressMentionPubkeys(message.tags).filter( - isKnownAgentPubkey, + return getVisibleAgentAddressPubkeys( + message.body, + getAgentAddressMentionPubkeys(message.tags).filter(isKnownAgentPubkey), + mentionPubkeysByName, ); - }, [isKnownAgentPubkey, message.tags]); + }, [isKnownAgentPubkey, mentionPubkeysByName, message.body, message.tags]); const agentAddressPrefix = addressedAgentPubkeys.length > 0 ? ( Promise; profiles?: UserProfileLookup; + recentMentionPubkeys?: readonly string[]; replyTargetMessage: TimelineMessage | null; scrollTargetId: string | null; threadHead: TimelineMessage | null; @@ -184,6 +185,7 @@ export function MessageThreadPanel({ onToggleReaction, onUnfollowThread, profiles, + recentMentionPubkeys, replyTargetMessage, scrollTargetId, scrollTargetHighlights = true, @@ -510,8 +512,12 @@ export function MessageThreadPanel({ tabIndex={-1} ref={threadBodyRef} > + {/* The gallery is intentionally DOM-scoped: only media currently rendered + in this open thread participates. Collapsed or unloaded descendants + join only after the thread UI renders them. */}
{ assert.equal(view.result.current.mentionSelectedIndex, 1); }); -test("primary+Shift+Enter opens the picker or toggles in place", async () => { +test("primary+Shift+M addresses the default agent or toggles the tray selection", async () => { const { act, renderHook } = await import("@testing-library/react"); const { useAlwaysAddressShortcut } = await import( "./useAlwaysAddressShortcut.ts" ); const { isMacPlatform } = await import("@/shared/lib/platform"); - const opened = []; + const selected = []; const toggled = []; const suggestion = { displayName: "Agent Ada", @@ -59,8 +59,9 @@ test("primary+Shift+Enter opens the picker or toggles in place", async () => { }; const createEvent = () => ({ altKey: false, + code: "KeyM", ctrlKey: !isMacPlatform(), - key: "Enter", + key: "M", metaKey: isMacPlatform(), preventDefault() {}, repeat: false, @@ -71,24 +72,123 @@ test("primary+Shift+Enter opens the picker or toggles in place", async () => { useAlwaysAddressShortcut({ enabled: true, mentions: { + getDefaultAgentSuggestion: () => suggestion, isMentionOpen, mentionSelectedIndex: 0, suggestions: [suggestion], }, - onOpenPicker: (insertTrigger) => opened.push(insertTrigger), + onOpenPicker: () => {}, + onSelect: (value) => selected.push(value), onToggle: (value) => toggled.push(value), }), { initialProps: { isMentionOpen: false } }, ); act(() => assert.equal(view.result.current(createEvent()), true)); - assert.deepEqual(opened, [false]); - assert.deepEqual(toggled, []); + assert.deepEqual(toggled, [suggestion]); + assert.deepEqual(selected, []); view.rerender({ isMentionOpen: true }); act(() => assert.equal(view.result.current(createEvent()), true)); assert.deepEqual(toggled, [suggestion]); + assert.deepEqual(selected, [suggestion]); act(() => assert.equal(view.result.current(createEvent()), true)); - assert.deepEqual(toggled, [suggestion, suggestion]); + assert.deepEqual(toggled, [suggestion]); + assert.deepEqual(selected, [suggestion, suggestion]); +}); + +test("primary+Shift+M removes the current locked agent before choosing a new default", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAlwaysAddressShortcut } = await import( + "./useAlwaysAddressShortcut.ts" + ); + const { isMacPlatform } = await import("@/shared/lib/platform"); + const lockedAgent = { + avatarUrl: null, + displayName: "Agent Ada", + pubkey: "agent-a", + }; + const defaultAgent = { + displayName: "Agent Bea", + isAgent: true, + pubkey: "agent-b", + }; + const toggled = []; + const { result } = renderHook(() => + useAlwaysAddressShortcut({ + enabled: true, + lockedAgent, + mentions: { + getDefaultAgentSuggestion: () => defaultAgent, + isMentionOpen: false, + mentionSelectedIndex: 0, + suggestions: [], + }, + onOpenPicker: () => {}, + onSelect: () => {}, + onToggle: (value) => toggled.push(value), + }), + ); + + act(() => + assert.equal( + result.current({ + altKey: false, + code: "KeyM", + ctrlKey: !isMacPlatform(), + key: "m", + metaKey: isMacPlatform(), + preventDefault() {}, + repeat: false, + shiftKey: true, + }), + true, + ), + ); + + assert.deepEqual(toggled, [{ ...lockedAgent, isAgent: true }]); +}); + +test("primary+Shift+M opens the picker when no default agent is ready", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAlwaysAddressShortcut } = await import( + "./useAlwaysAddressShortcut.ts" + ); + const { isMacPlatform } = await import("@/shared/lib/platform"); + let opened = 0; + const { result } = renderHook(() => + useAlwaysAddressShortcut({ + enabled: true, + mentions: { + getDefaultAgentSuggestion: () => null, + isMentionOpen: false, + mentionSelectedIndex: 0, + suggestions: [], + }, + onOpenPicker: () => { + opened += 1; + }, + onSelect: () => {}, + onToggle: () => {}, + }), + ); + + act(() => + assert.equal( + result.current({ + altKey: false, + code: "KeyM", + ctrlKey: !isMacPlatform(), + key: "m", + metaKey: isMacPlatform(), + preventDefault() {}, + repeat: false, + shiftKey: true, + }), + true, + ), + ); + + assert.equal(opened, 1); }); diff --git a/desktop/src/features/messages/ui/useAgentAddressLockPicker.test.mjs b/desktop/src/features/messages/ui/useAgentAddressLockPicker.test.mjs index 4acd89cf0a..95e0af9e06 100644 --- a/desktop/src/features/messages/ui/useAgentAddressLockPicker.test.mjs +++ b/desktop/src/features/messages/ui/useAgentAddressLockPicker.test.mjs @@ -23,7 +23,7 @@ afterEach(async () => { after(() => dom.window.close()); -test("always addressing an agent keeps autocomplete open, adds the lock, and pulses", async () => { +test("always addressing an agent keeps autocomplete open, inserts the chip, adds the lock, and pulses", async () => { const { act, renderHook } = await import("@testing-library/react"); const { useAgentAddressLockPicker } = await import( "./useAgentAddressLockPicker.ts" @@ -32,7 +32,7 @@ test("always addressing an agent keeps autocomplete open, adds the lock, and pul const addedPubkeys = []; const pulsedPubkeys = []; let cancelCount = 0; - const text = "Ask @Agent Ada later @"; + const text = "@"; const mentions = { cancelMentionAutocomplete: () => { cancelCount += 1; @@ -45,6 +45,9 @@ test("always addressing an agent keeps autocomplete open, adds the lock, and pul }, ], getMentionDisplayName: () => "Agent Ada", + isInlineMentionSelection: () => false, + isMentionOpen: true, + registerMentionPubkey: () => {}, mentionStartIndex: text.lastIndexOf("@"), }; const audience = { @@ -73,7 +76,14 @@ test("always addressing an agent keeps autocomplete open, adds the lock, and pul }); }); - assert.deepEqual(appliedEdits, []); + assert.deepEqual(appliedEdits, [ + { + replaceFromOffset: 0, + replaceToOffset: 0, + insertText: "@Agent Ada ", + preserveSelection: true, + }, + ]); assert.equal(cancelCount, 0); assert.deepEqual(addedPubkeys, ["agent-pubkey"]); assert.deepEqual(pulsedPubkeys, ["agent-pubkey"]); @@ -83,6 +93,49 @@ test("always addressing an agent keeps autocomplete open, adds the lock, and pul ); }); +test("always addressing a new agent delegates the first add for immediate confirmation", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAgentAddressLockPicker } = await import( + "./useAgentAddressLockPicker.ts" + ); + const addressedSuggestions = []; + const addedPubkeys = []; + const pulsedPubkeys = []; + const suggestion = { + pubkey: "agent-pubkey", + displayName: "Agent Ada", + isAgent: true, + }; + const { result } = renderHook(() => + useAgentAddressLockPicker({ + applyAutocompleteEdit: () => {}, + audience: { + pubkeys: [], + addPubkey: (pubkey) => addedPubkeys.push(pubkey), + }, + audienceScope: "channel-scope", + mentions: { + getDraftMentionRefs: () => [], + getMentionDisplayName: () => "Agent Ada", + isInlineMentionSelection: () => false, + isMentionOpen: false, + registerMentionPubkey: () => {}, + }, + onAddressAgentMention: (value) => addressedSuggestions.push(value), + onPulseAddressLock: (pubkey) => pulsedPubkeys.push(pubkey), + richText: { + getPlainTextAndCursor: () => ({ text: "@Agent Ada ", cursor: 11 }), + }, + }), + ); + + act(() => result.current.toggleAlwaysAddressAgent(suggestion)); + + assert.deepEqual(addressedSuggestions, [suggestion]); + assert.deepEqual(addedPubkeys, []); + assert.deepEqual(pulsedPubkeys, []); +}); + test("toggling an addressed agent keeps autocomplete open and removes the lock", async () => { const { act, renderHook } = await import("@testing-library/react"); const { useAgentAddressLockPicker } = await import( @@ -105,6 +158,7 @@ test("toggling an addressed agent keeps autocomplete open and removes the lock", }, ], getMentionDisplayName: () => "Agent Ada", + registerMentionPubkey: () => {}, mentionStartIndex: text.lastIndexOf("@"), }; const audience = { @@ -136,7 +190,13 @@ test("toggling an addressed agent keeps autocomplete open and removes the lock", }); }); - assert.deepEqual(appliedEdits, []); + assert.deepEqual(appliedEdits, [ + { + replaceFromOffset: 4, + replaceToOffset: 15, + insertText: "", + }, + ]); assert.equal(cancelCount, 0); assert.deepEqual(removedPubkeys, ["agent-pubkey"]); assert.deepEqual(pulsedPubkeys, []); @@ -158,10 +218,13 @@ test("selecting an already addressed agent from the explicit picker pulses its b cancelMentionAutocomplete: () => {}, getDraftMentionRefs: () => [], getMentionDisplayName: () => "Agent Ada", + registerMentionPubkey: () => {}, isInlineMentionSelection: () => false, - insertMention: () => { - throw new Error("an already addressed agent must not be inserted"); - }, + insertMention: () => ({ + replaceFromOffset: 5, + replaceToOffset: 5, + insertText: "@Agent Ada ", + }), mentionStartIndex: 5, }; const audience = { @@ -190,16 +253,23 @@ test("selecting an already addressed agent from the explicit picker pulses its b }); }); - assert.deepEqual(appliedEdits, []); + assert.deepEqual(appliedEdits, [ + { + replaceFromOffset: 5, + replaceToOffset: 5, + insertText: "@Agent Ada ", + }, + ]); assert.deepEqual(addedPubkeys, []); assert.deepEqual(pulsedPubkeys, ["agent-pubkey"]); }); -test("selecting an agent from a typed query leaves the inline mention for send", async () => { +test("selecting an agent from a typed query immediately auto-addresses it", async () => { const { act, renderHook } = await import("@testing-library/react"); const { useAgentAddressLockPicker } = await import( "./useAgentAddressLockPicker.ts" ); + const autoPinnedSuggestions = []; const appliedEdits = []; const addedPubkeys = []; const pulsedPubkeys = []; @@ -207,6 +277,7 @@ test("selecting an agent from a typed query leaves the inline mention for send", cancelMentionAutocomplete: () => {}, getDraftMentionRefs: () => [], getMentionDisplayName: () => "Agent Ada", + registerMentionPubkey: () => {}, isInlineMentionSelection: () => true, insertMention: () => ({ replaceFromOffset: 5, @@ -224,6 +295,206 @@ test("selecting an agent from a typed query leaves the inline mention for send", // makes the editor text/cursor insufficient to re-detect the typed query. getPlainTextAndCursor: () => ({ text: "ping ", cursor: 5 }), }; + const { result } = renderHook(() => + useAgentAddressLockPicker({ + applyAutocompleteEdit: (edit) => appliedEdits.push(edit), + audience, + audienceScope: "channel-scope", + mentions, + onAutoPinAgentMention: (suggestion) => + autoPinnedSuggestions.push(suggestion), + onPulseAddressLock: (pubkey) => pulsedPubkeys.push(pubkey), + richText, + }), + ); + + const suggestion = { + pubkey: "agent-pubkey", + displayName: "Agent Ada", + isAgent: true, + }; + act(() => result.current.selectMentionSuggestion(suggestion)); + + assert.deepEqual(appliedEdits, [ + { + replaceFromOffset: 5, + replaceToOffset: 6, + insertText: "@Agent Ada ", + }, + ]); + assert.deepEqual(autoPinnedSuggestions, [suggestion]); + assert.deepEqual(addedPubkeys, []); + assert.deepEqual(pulsedPubkeys, []); + assert.equal(result.current.announcement, ""); +}); + +test("selecting a human mention never changes automatic addressing", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAgentAddressLockPicker } = await import( + "./useAgentAddressLockPicker.ts" + ); + const autoPinnedSuggestions = []; + const appliedEdits = []; + const { result } = renderHook(() => + useAgentAddressLockPicker({ + applyAutocompleteEdit: (edit) => appliedEdits.push(edit), + audience: { pubkeys: [], addPubkey: () => {} }, + audienceScope: "channel-scope", + mentions: { + getMentionDisplayName: () => "Alice", + insertMention: () => ({ + replaceFromOffset: 0, + replaceToOffset: 3, + insertText: "@Alice ", + }), + }, + onAutoPinAgentMention: (suggestion) => + autoPinnedSuggestions.push(suggestion), + onPulseAddressLock: () => {}, + richText: { + getPlainTextAndCursor: () => ({ text: "@Al", cursor: 3 }), + }, + }), + ); + + act(() => + result.current.selectMentionSuggestion({ + pubkey: "human-pubkey", + displayName: "Alice", + isAgent: false, + }), + ); + + assert.deepEqual(appliedEdits, [ + { + replaceFromOffset: 0, + replaceToOffset: 3, + insertText: "@Alice ", + }, + ]); + assert.deepEqual(autoPinnedSuggestions, []); +}); + +test("removing the last agent chip clears its automatic address", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAgentAddressLockPicker } = await import( + "./useAgentAddressLockPicker.ts" + ); + const removedPubkeys = []; + const mentionRefsByText = { + "@Agent Ada first @Agent Ada second": [ + { displayName: "Agent Ada", pubkey: "agent-pubkey", isAgent: true }, + { displayName: "Agent Ada", pubkey: "agent-pubkey", isAgent: true }, + ], + "@Agent Ada second": [ + { displayName: "Agent Ada", pubkey: "agent-pubkey", isAgent: true }, + ], + "": [], + }; + const { result } = renderHook(() => + useAgentAddressLockPicker({ + applyAutocompleteEdit: () => {}, + audience: { + pubkeys: ["agent-pubkey", "existing-lock"], + removePubkey: (pubkey) => removedPubkeys.push(pubkey), + }, + audienceScope: "channel-scope", + mentions: { + getDraftMentionRefs: (text) => mentionRefsByText[text] ?? [], + getMentionDisplayName: () => "Agent Ada", + }, + onPulseAddressLock: () => {}, + richText: { getPlainTextAndCursor: () => ({ text: "", cursor: 0 }) }, + }), + ); + + act(() => result.current.trackMentionAddressedAgent("agent-pubkey")); + act(() => + result.current.syncAddressedAgentsFromText( + "@Agent Ada first @Agent Ada second", + ), + ); + act(() => result.current.syncAddressedAgentsFromText("@Agent Ada second")); + assert.deepEqual(removedPubkeys, []); + + act(() => result.current.syncAddressedAgentsFromText("")); + assert.deepEqual(removedPubkeys, ["agent-pubkey"]); +}); + +test("removing human mentions is ignored while removing a restored agent chip clears its lock", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAgentAddressLockPicker } = await import( + "./useAgentAddressLockPicker.ts" + ); + const removedPubkeys = []; + const { result } = renderHook(() => + useAgentAddressLockPicker({ + applyAutocompleteEdit: () => {}, + audience: { + pubkeys: ["existing-lock"], + removePubkey: (pubkey) => removedPubkeys.push(pubkey), + }, + audienceScope: "channel-scope", + mentions: { + getDraftMentionRefs: (text) => { + if (text === "@Alice @Existing Agent") { + return [ + { displayName: "Alice", pubkey: "human-pubkey", isAgent: false }, + { + displayName: "Existing Agent", + pubkey: "existing-lock", + isAgent: true, + }, + ]; + } + return text + ? [{ displayName: "Alice", pubkey: "human-pubkey", isAgent: false }] + : []; + }, + getMentionDisplayName: () => "Existing Agent", + }, + onPulseAddressLock: () => {}, + richText: { getPlainTextAndCursor: () => ({ text: "", cursor: 0 }) }, + }), + ); + + act(() => + result.current.syncAddressedAgentsFromText("@Alice @Existing Agent"), + ); + act(() => result.current.syncAddressedAgentsFromText("@Alice")); + assert.deepEqual(removedPubkeys, ["existing-lock"]); + act(() => result.current.syncAddressedAgentsFromText("")); + assert.deepEqual(removedPubkeys, ["existing-lock"]); +}); + +test("selecting an agent from the explicit picker auto-addresses it", async () => { + const { act, renderHook } = await import("@testing-library/react"); + const { useAgentAddressLockPicker } = await import( + "./useAgentAddressLockPicker.ts" + ); + const appliedEdits = []; + const addedPubkeys = []; + const pulsedPubkeys = []; + const mentions = { + cancelMentionAutocomplete: () => {}, + getDraftMentionRefs: () => [], + getMentionDisplayName: () => "Agent Ada", + registerMentionPubkey: () => {}, + isInlineMentionSelection: () => false, + insertMention: () => ({ + replaceFromOffset: 5, + replaceToOffset: 5, + insertText: "@Agent Ada ", + }), + mentionStartIndex: 5, + }; + const audience = { + pubkeys: [], + addPubkey: (pubkey) => addedPubkeys.push(pubkey), + }; + const richText = { + getPlainTextAndCursor: () => ({ text: "ping ", cursor: 5 }), + }; const { result } = renderHook(() => useAgentAddressLockPicker({ applyAutocompleteEdit: (edit) => appliedEdits.push(edit), @@ -246,60 +517,10 @@ test("selecting an agent from a typed query leaves the inline mention for send", assert.deepEqual(appliedEdits, [ { replaceFromOffset: 5, - replaceToOffset: 6, + replaceToOffset: 5, insertText: "@Agent Ada ", }, ]); - assert.deepEqual(addedPubkeys, []); - assert.deepEqual(pulsedPubkeys, []); - assert.equal(result.current.announcement, ""); -}); - -test("selecting an agent from the explicit picker auto-addresses it", async () => { - const { act, renderHook } = await import("@testing-library/react"); - const { useAgentAddressLockPicker } = await import( - "./useAgentAddressLockPicker.ts" - ); - const appliedEdits = []; - const addedPubkeys = []; - const pulsedPubkeys = []; - const mentions = { - cancelMentionAutocomplete: () => {}, - getDraftMentionRefs: () => [], - getMentionDisplayName: () => "Agent Ada", - isInlineMentionSelection: () => false, - insertMention: () => { - throw new Error("explicit picker selections must become addressing"); - }, - mentionStartIndex: 5, - }; - const audience = { - pubkeys: [], - addPubkey: (pubkey) => addedPubkeys.push(pubkey), - }; - const richText = { - getPlainTextAndCursor: () => ({ text: "ping ", cursor: 5 }), - }; - const { result } = renderHook(() => - useAgentAddressLockPicker({ - applyAutocompleteEdit: (edit) => appliedEdits.push(edit), - audience, - audienceScope: "channel-scope", - mentions, - onPulseAddressLock: (pubkey) => pulsedPubkeys.push(pubkey), - richText, - }), - ); - - act(() => { - result.current.selectMentionSuggestion({ - pubkey: "agent-pubkey", - displayName: "Agent Ada", - isAgent: true, - }); - }); - - assert.deepEqual(appliedEdits, []); assert.deepEqual(addedPubkeys, ["agent-pubkey"]); assert.deepEqual(pulsedPubkeys, ["agent-pubkey"]); assert.equal( @@ -319,8 +540,11 @@ test("selecting an explicitly unpinned agent inserts a mention until send", asyn const pulsedPubkeys = []; const mentions = { cancelMentionAutocomplete: () => {}, - getDraftMentionRefs: () => [], + getDraftMentionRefs: () => [ + { displayName: "Agent Ada", pubkey: "agent-pubkey", isAgent: true }, + ], getMentionDisplayName: () => "Agent Ada", + registerMentionPubkey: () => {}, isInlineMentionSelection: () => false, insertMention: () => ({ replaceFromOffset: 0, @@ -330,7 +554,10 @@ test("selecting an explicitly unpinned agent inserts a mention until send", asyn mentionStartIndex: 0, }; const richText = { - getPlainTextAndCursor: () => ({ text: "", cursor: 0 }), + getPlainTextAndCursor: () => ({ + text: "@Agent Ada keep this authored text", + cursor: 35, + }), }; const { result, rerender } = renderHook( ({ pubkeys }) => @@ -350,6 +577,7 @@ test("selecting an explicitly unpinned agent inserts a mention until send", asyn ); act(() => result.current.removeAddressedAgent("AGENT-PUBKEY")); + assert.deepEqual(appliedEdits, []); rerender({ pubkeys: [] }); act(() => { result.current.selectMentionSuggestion({ diff --git a/desktop/src/features/messages/ui/useAgentAddressLockPicker.ts b/desktop/src/features/messages/ui/useAgentAddressLockPicker.ts index 8d5a87b9b8..17883900ec 100644 --- a/desktop/src/features/messages/ui/useAgentAddressLockPicker.ts +++ b/desktop/src/features/messages/ui/useAgentAddressLockPicker.ts @@ -16,8 +16,7 @@ import type { MentionSuggestion } from "./MentionAutocomplete"; function buildMentionRemovalEdits( text: string, displayNames: readonly string[], - queryStart: number, - cursor: number, + queryRange?: { start: number; end: number }, ): AutocompleteEdit[] { const ranges = displayNames.flatMap((displayName) => getMentionOffsets(text, displayName).map((start) => { @@ -26,10 +25,12 @@ function buildMentionRemovalEdits( return { start, end }; }), ); - ranges.push({ - start: Math.max(0, Math.min(queryStart, text.length)), - end: Math.max(0, Math.min(cursor, text.length)), - }); + if (queryRange) { + ranges.push({ + start: Math.max(0, Math.min(queryRange.start, text.length)), + end: Math.max(0, Math.min(queryRange.end, text.length)), + }); + } const merged = ranges .filter(({ start, end }) => start < end) @@ -56,6 +57,8 @@ export function useAgentAddressLockPicker({ audience, audienceScope, mentions, + onAddressAgentMention, + onAutoPinAgentMention, onPulseAddressLock, profiles, richText, @@ -64,6 +67,8 @@ export function useAgentAddressLockPicker({ audience: ReturnType; audienceScope: string | null; mentions: UseMentionsResult; + onAddressAgentMention?: (suggestion: MentionSuggestion) => void; + onAutoPinAgentMention?: (suggestion: MentionSuggestion) => void; onPulseAddressLock: (pubkey: string) => void; profiles?: UserProfileLookup; richText: UseRichTextEditorResult; @@ -79,6 +84,12 @@ export function useAgentAddressLockPicker({ unpinnedAgentPubkeysRef.current.clear(); } const lockedAgentNamesRef = React.useRef(new Map()); + const visibleAgentMentionPubkeysRef = React.useRef(new Set()); + const mentionSyncScopeRef = React.useRef(audienceScope); + if (mentionSyncScopeRef.current !== audienceScope) { + mentionSyncScopeRef.current = audienceScope; + visibleAgentMentionPubkeysRef.current.clear(); + } const [announcement, setAnnouncement] = React.useState(""); const lockedAgents = React.useMemo( () => @@ -104,41 +115,42 @@ export function useAgentAddressLockPicker({ }), [audience.pubkeys, mentions.getMentionDisplayName, profiles], ); - const consumeAddressSuggestion = React.useCallback( - ( - suggestion: MentionSuggestion, - { removeInlineMentions }: { removeInlineMentions: boolean }, - ): string | null => { - const pubkey = normalizePubkey(suggestion.pubkey ?? ""); - if (!audienceScope || !pubkey || !suggestion.isAgent) return null; - - const { text, cursor } = richText.getPlainTextAndCursor(); - const matchingDisplayNames = removeInlineMentions - ? mentions - .getDraftMentionRefs(text) - .filter((ref) => normalizePubkey(ref.pubkey) === pubkey) - .map((ref) => ref.displayName) - : []; - mentions.cancelMentionAutocomplete(); - for (const edit of buildMentionRemovalEdits( - text, - matchingDisplayNames, - mentions.mentionStartIndex, - cursor, - )) { - applyAutocompleteEdit(edit); + const trackMentionAddressedAgent = React.useCallback( + (pubkey: string) => { + const normalized = normalizePubkey(pubkey); + if (audienceScope && normalized) { + visibleAgentMentionPubkeysRef.current.add(normalized); } - return pubkey; + }, + [audienceScope], + ); + const syncAddressedAgentsFromText = React.useCallback( + (text: string) => { + if (!audienceScope) return; + const presentAgentPubkeys = new Set( + mentions + .getDraftMentionRefs(text) + .filter((ref) => ref.isAgent) + .map((ref) => normalizePubkey(ref.pubkey)), + ); + for (const pubkey of visibleAgentMentionPubkeysRef.current) { + if ( + !presentAgentPubkeys.has(pubkey) && + lockedAgentPubkeys.has(pubkey) + ) { + audience.removePubkey(pubkey); + } + } + visibleAgentMentionPubkeysRef.current = presentAgentPubkeys; }, [ - applyAutocompleteEdit, + audience.removePubkey, audienceScope, - mentions.cancelMentionAutocomplete, + lockedAgentPubkeys, mentions.getDraftMentionRefs, - mentions.mentionStartIndex, - richText.getPlainTextAndCursor, ], ); + const removeAddressedAgent = React.useCallback( (pubkey: string) => { const normalized = normalizePubkey(pubkey); @@ -148,24 +160,63 @@ export function useAgentAddressLockPicker({ }, [audience.removePubkey, audienceScope], ); + const removeAddressedAgentMentions = React.useCallback( + (pubkey: string) => { + const normalized = normalizePubkey(pubkey); + if (!audienceScope || !normalized) return; + const { text } = richText.getPlainTextAndCursor(); + const matchingDisplayNames = mentions + .getDraftMentionRefs(text) + .filter((ref) => normalizePubkey(ref.pubkey) === normalized) + .map((ref) => ref.displayName); + for (const edit of buildMentionRemovalEdits(text, matchingDisplayNames)) { + applyAutocompleteEdit(edit); + } + removeAddressedAgent(normalized); + }, + [ + applyAutocompleteEdit, + audienceScope, + mentions.getDraftMentionRefs, + removeAddressedAgent, + richText.getPlainTextAndCursor, + ], + ); const toggleAlwaysAddressAgent = React.useCallback( (suggestion: MentionSuggestion) => { const pubkey = normalizePubkey(suggestion.pubkey ?? ""); if (!audienceScope || !pubkey || !suggestion.isAgent) return; if (lockedAgentPubkeys.has(pubkey)) { - removeAddressedAgent(pubkey); + removeAddressedAgentMentions(pubkey); setAnnouncement( `Stopped automatically mentioning ${suggestion.displayName}`, ); } else { unpinnedAgentPubkeysRef.current.delete(pubkey); - audience.addPubkey(pubkey); - onPulseAddressLock(pubkey); + mentions.registerMentionPubkey(suggestion.displayName, pubkey, { + isAgent: true, + }); + const { text } = richText.getPlainTextAndCursor(); + if (getMentionOffsets(text, suggestion.displayName).length === 0) { + applyAutocompleteEdit({ + replaceFromOffset: 0, + replaceToOffset: 0, + insertText: `@${suggestion.displayName} `, + preserveSelection: true, + }); + } + trackMentionAddressedAgent(pubkey); + if (onAddressAgentMention) { + onAddressAgentMention(suggestion); + } else { + audience.addPubkey(pubkey); + onPulseAddressLock(pubkey); + } setAnnouncement(`Automatically mentioning ${suggestion.displayName}`); } - if (mentions.isMentionOpen) { + if (mentions.isMentionOpen && mentions.isInlineMentionSelection()) { const { text, cursor } = richText.getPlainTextAndCursor(); const activeMention = detectPrefixQuery("@", text, cursor, [ suggestion.displayName.toLowerCase(), @@ -190,12 +241,16 @@ export function useAgentAddressLockPicker({ audience.addPubkey, audienceScope, lockedAgentPubkeys, + mentions.isInlineMentionSelection, mentions.isMentionOpen, mentions.mentionStartIndex, mentions.openMentionPicker, + mentions.registerMentionPubkey, + onAddressAgentMention, onPulseAddressLock, - removeAddressedAgent, + removeAddressedAgentMentions, richText.getPlainTextAndCursor, + trackMentionAddressedAgent, ], ); @@ -209,15 +264,25 @@ export function useAgentAddressLockPicker({ unpinnedAgentPubkeysRef.current.has(pubkey); if (mentions.isInlineMentionSelection() || wasUnpinned) { applyAutocompleteEdit(mentions.insertMention(suggestion, cursor)); + if (wasUnpinned) unpinnedAgentPubkeysRef.current.delete(pubkey); + trackMentionAddressedAgent(pubkey); + onAutoPinAgentMention?.(suggestion); return; } - consumeAddressSuggestion(suggestion, { removeInlineMentions: false }); + applyAutocompleteEdit(mentions.insertMention(suggestion, cursor)); if (!lockedAgentPubkeys.has(pubkey)) { - audience.addPubkey(pubkey); + trackMentionAddressedAgent(pubkey); + if (onAddressAgentMention) { + onAddressAgentMention(suggestion); + } else { + audience.addPubkey(pubkey); + onPulseAddressLock(pubkey); + } setAnnouncement(`Automatically mentioning ${suggestion.displayName}`); + } else { + onPulseAddressLock(pubkey); } - onPulseAddressLock(pubkey); return; } @@ -228,12 +293,84 @@ export function useAgentAddressLockPicker({ applyAutocompleteEdit, audience.addPubkey, audienceScope, - consumeAddressSuggestion, lockedAgentPubkeys, mentions.isInlineMentionSelection, mentions.insertMention, + onAddressAgentMention, + onAutoPinAgentMention, onPulseAddressLock, richText.getPlainTextAndCursor, + trackMentionAddressedAgent, + ], + ); + + const restoreAddressedAgentMentions = React.useCallback( + ( + pubkeys?: readonly string[], + allowedUnpinnedPubkeys: readonly string[] = [], + ) => { + const restorePubkeys = pubkeys + ? new Set(pubkeys.map(normalizePubkey)) + : null; + const allowedUnpinned = new Set( + allowedUnpinnedPubkeys.map(normalizePubkey), + ); + const currentAudiencePubkeys = new Set( + audience.pubkeys.map(normalizePubkey), + ); + const targetAgents = [...(restorePubkeys ?? currentAudiencePubkeys)] + .filter( + (pubkey) => + currentAudiencePubkeys.has(pubkey) || allowedUnpinned.has(pubkey), + ) + .map((pubkey) => { + const profile = profiles?.[pubkey]; + const displayName = + profile?.displayName?.trim() || + profile?.name?.trim() || + profile?.nip05Handle?.trim() || + mentions.getMentionDisplayName(pubkey)?.trim() || + lockedAgentNamesRef.current.get(pubkey) || + truncatePubkey(pubkey); + return { pubkey, displayName }; + }); + const { text } = richText.getPlainTextAndCursor(); + for (const agent of targetAgents) { + if (getMentionOffsets(text, agent.displayName).length > 0) { + visibleAgentMentionPubkeysRef.current.add(agent.pubkey); + } + } + const missingAgents = targetAgents.filter( + (agent) => + (!unpinnedAgentPubkeysRef.current.has(agent.pubkey) || + allowedUnpinned.has(agent.pubkey)) && + getMentionOffsets(text, agent.displayName).length === 0, + ); + if (missingAgents.length === 0) return text; + for (const agent of missingAgents) { + mentions.registerMentionPubkey(agent.displayName, agent.pubkey, { + isAgent: true, + }); + visibleAgentMentionPubkeysRef.current.add(agent.pubkey); + } + const insertedText = `${missingAgents + .map((agent) => `@${agent.displayName}`) + .join(" ")} `; + applyAutocompleteEdit({ + replaceFromOffset: 0, + replaceToOffset: 0, + insertText: insertedText, + preserveSelection: true, + }); + return `${insertedText}${text}`; + }, + [ + applyAutocompleteEdit, + audience.pubkeys, + mentions.getMentionDisplayName, + mentions.registerMentionPubkey, + profiles, + richText.getPlainTextAndCursor, ], ); @@ -242,7 +379,10 @@ export function useAgentAddressLockPicker({ lockedAgents, lockedAgentPubkeys, removeAddressedAgent, + restoreAddressedAgentMentions, selectMentionSuggestion, + syncAddressedAgentsFromText, toggleAlwaysAddressAgent, + trackMentionAddressedAgent, }; } diff --git a/desktop/src/features/messages/ui/useAlwaysAddressShortcut.ts b/desktop/src/features/messages/ui/useAlwaysAddressShortcut.ts index 8fd253df22..ed92e7b3f0 100644 --- a/desktop/src/features/messages/ui/useAlwaysAddressShortcut.ts +++ b/desktop/src/features/messages/ui/useAlwaysAddressShortcut.ts @@ -6,21 +6,30 @@ import type { MentionSuggestion } from "./MentionAutocomplete"; export function useAlwaysAddressShortcut({ enabled, + lockedAgent, mentions, onOpenPicker, + onSelect, onToggle, }: { enabled: boolean; + lockedAgent?: Pick; mentions: UseMentionsResult; onOpenPicker: (insertTrigger?: boolean) => void; + onSelect: (suggestion: MentionSuggestion) => void; onToggle: (suggestion: MentionSuggestion) => void; }) { - const { isMentionOpen, mentionSelectedIndex, suggestions } = mentions; + const { + getDefaultAgentSuggestion, + isMentionOpen, + mentionSelectedIndex, + suggestions, + } = mentions; return React.useCallback( (event: React.KeyboardEvent): boolean => { if ( !enabled || - event.key !== "Enter" || + event.code !== "KeyM" || !hasPrimaryShortcutModifier(event) || event.altKey || !event.shiftKey @@ -30,21 +39,30 @@ export function useAlwaysAddressShortcut({ event.preventDefault(); if (event.repeat) return true; - if (!isMentionOpen) { - onOpenPicker(false); + const suggestion = isMentionOpen + ? suggestions[mentionSelectedIndex] + : lockedAgent + ? { ...lockedAgent, isAgent: true } + : getDefaultAgentSuggestion(); + if (!suggestion?.isAgent || !suggestion.pubkey) { + if (!isMentionOpen) onOpenPicker(false); return true; } - - const suggestion = suggestions[mentionSelectedIndex]; - if (!suggestion?.isAgent || !suggestion.pubkey) return true; - onToggle(suggestion); + if (isMentionOpen) { + onSelect(suggestion); + } else { + onToggle(suggestion); + } return true; }, [ enabled, + getDefaultAgentSuggestion, isMentionOpen, + lockedAgent, mentionSelectedIndex, onOpenPicker, + onSelect, onToggle, suggestions, ], diff --git a/desktop/src/features/messages/ui/useAutoPinMentionedAgents.ts b/desktop/src/features/messages/ui/useAutoPinMentionedAgents.ts index 44b87c9f1d..d0557567fd 100644 --- a/desktop/src/features/messages/ui/useAutoPinMentionedAgents.ts +++ b/desktop/src/features/messages/ui/useAutoPinMentionedAgents.ts @@ -1,36 +1,62 @@ import * as React from "react"; -import { toast } from "sonner"; import { + getPersistentAgentAudienceRevision, promotePersistentAgentAudienceIfUnchanged, removePersistentAgentAudienceMembersIfUnchanged, } from "@/features/messages/lib/persistentAgentAudience"; import { normalizePubkey } from "@/shared/lib/pubkey"; +const CONFIRMATION_DURATION_MS = 4_000; + +type Confirmation = { + expectedRevision: number; + pubkeys: readonly string[]; + scope: string; + title: string; +}; + type Options = { audienceScope: string | null; enabled: boolean; getDisplayName: (pubkey: string) => string | null | undefined; - onOpenOptions: () => void; onPulse: (pubkey: string) => void; + onTurnOff: () => void; }; export function useAutoPinMentionedAgents({ audienceScope, enabled, getDisplayName, - onOpenOptions, onPulse, + onTurnOff, }: Options) { - return React.useCallback( + const [confirmation, setConfirmation] = React.useState( + null, + ); + + React.useEffect(() => { + if (!confirmation) return; + const timeout = window.setTimeout( + () => setConfirmation(null), + CONFIRMATION_DURATION_MS, + ); + return () => window.clearTimeout(timeout); + }, [confirmation]); + + const promoteAgents = React.useCallback( ({ - expectedRevision, + expectedRevision = audienceScope + ? getPersistentAgentAudienceRevision(audienceScope) + : 0, pubkeys, + requirePreference, }: { - expectedRevision: number; + expectedRevision?: number; pubkeys: readonly string[]; + requirePreference: boolean; }) => { - if (!audienceScope || !enabled) return; + if (!audienceScope || (requirePreference && !enabled)) return; const normalizedPubkeys = [ ...new Set(pubkeys.map(normalizePubkey)), ].filter(Boolean); @@ -52,23 +78,47 @@ export function useAutoPinMentionedAgents({ : promotedPubkeys.length === 1 ? "Agent will be mentioned automatically" : `${promotedPubkeys.length} agents will be mentioned automatically`; - toast.success(title, { - action: { - label: "Undo", - onClick: () => { - if ( - removePersistentAgentAudienceMembersIfUnchanged({ - expectedRevision: revision, - pubkeys: promotedPubkeys, - scope: audienceScope, - }) - ) { - onOpenOptions(); - } - }, - }, + setConfirmation({ + expectedRevision: revision, + pubkeys: promotedPubkeys, + scope: audienceScope, + title, }); }, - [audienceScope, enabled, getDisplayName, onOpenOptions, onPulse], + [audienceScope, enabled, getDisplayName, onPulse], ); + const promoteMentionedAgents = React.useCallback( + (promotion: { expectedRevision?: number; pubkeys: readonly string[] }) => + promoteAgents({ ...promotion, requirePreference: true }), + [promoteAgents], + ); + const promoteExplicitlyAddressedAgents = React.useCallback( + (promotion: { expectedRevision?: number; pubkeys: readonly string[] }) => + promoteAgents({ ...promotion, requirePreference: false }), + [promoteAgents], + ); + + const dismissConfirmation = React.useCallback( + () => setConfirmation(null), + [], + ); + const turnOffConfirmation = React.useCallback(() => { + if (!confirmation) return; + setConfirmation(null); + removePersistentAgentAudienceMembersIfUnchanged({ + expectedRevision: confirmation.expectedRevision, + pubkeys: confirmation.pubkeys, + scope: confirmation.scope, + }); + onTurnOff(); + }, [confirmation, onTurnOff]); + + return { + confirmationTitle: + confirmation?.scope === audienceScope ? confirmation.title : null, + dismissConfirmation, + promoteExplicitlyAddressedAgents, + promoteMentionedAgents, + turnOffConfirmation, + }; } diff --git a/desktop/src/features/messages/ui/useComposerPasteHandler.ts b/desktop/src/features/messages/ui/useComposerPasteHandler.ts new file mode 100644 index 0000000000..8e56da071a --- /dev/null +++ b/desktop/src/features/messages/ui/useComposerPasteHandler.ts @@ -0,0 +1,73 @@ +import * as React from "react"; +import type { Editor } from "@tiptap/react"; +import { handleAgentSnapshotPaste } from "@/features/messages/lib/agentSnapshotClipboard"; +import type { BlobDescriptor } from "@/shared/api/tauri"; +import { + hasMentionClipboardHtml, + normalizeMentionClipboardHtml, +} from "@/features/messages/lib/normalizeMentionClipboard"; +import { getBuzzCodeBlockClipboardText } from "@/shared/lib/codeBlockClipboard"; + +export function useComposerPasteHandler(options: { + editor: Editor | null; + scrollToBottom: () => void; + setPendingImeta: ( + update: (current: BlobDescriptor[]) => BlobDescriptor[], + ) => void; + uploadFile: (file: File) => Promise; +}) { + const uploadFileRef = React.useRef(options.uploadFile); + uploadFileRef.current = options.uploadFile; + React.useEffect(() => { + const editor = options.editor; + if (!editor) return; + editor.setOptions({ + editorProps: { + ...editor.options.editorProps, + handlePaste: (view, event) => { + const mediaItem = Array.from(event.clipboardData?.items ?? []).find( + (item) => item.kind === "file", + ); + if (mediaItem) { + const file = mediaItem.getAsFile(); + if (file) void uploadFileRef.current(file); + return true; + } + const codeBlockText = getBuzzCodeBlockClipboardText( + event.clipboardData, + ); + if (codeBlockText !== null) { + event.preventDefault(); + editor + .chain() + .focus() + .insertContent([ + { + type: "codeBlock", + content: + codeBlockText.length > 0 + ? [{ type: "text", text: codeBlockText }] + : [], + }, + { type: "paragraph" }, + ]) + .run(); + options.scrollToBottom(); + return true; + } + if (handleAgentSnapshotPaste(event, options.setPendingImeta)) + return true; + const html = event.clipboardData?.getData("text/html"); + if (html && hasMentionClipboardHtml(html)) { + event.preventDefault(); + view.pasteHTML(normalizeMentionClipboardHtml(html)); + return true; + } + if ((event.clipboardData?.getData("text/plain") ?? "").includes("\n")) + options.scrollToBottom(); + return false; + }, + }, + }); + }, [options.editor, options.scrollToBottom, options.setPendingImeta]); +} diff --git a/desktop/src/features/messages/ui/useDraftPersistSnapshot.ts b/desktop/src/features/messages/ui/useDraftPersistSnapshot.ts index 14dae33adb..694bf6a2a5 100644 --- a/desktop/src/features/messages/ui/useDraftPersistSnapshot.ts +++ b/desktop/src/features/messages/ui/useDraftPersistSnapshot.ts @@ -2,9 +2,10 @@ import * as React from "react"; import type { ImetaMedia } from "@/features/messages/lib/imetaMediaMarkdown"; import type { QueuedMediaAttachment } from "@/features/messages/lib/backgroundMediaUploadStore"; -import type { - DraftMentionRef, - DraftState, +import { + getDraftStoreScope, + type DraftMentionRef, + type DraftState, } from "@/features/messages/lib/useDrafts"; type UseDraftPersistLifecycleParams = { @@ -60,6 +61,21 @@ type UseDraftPersistLifecycleParams = { syncComposerContentFromEditor: () => string; }; +type UseDraftPersistLifecycleResult = { + /** + * Record the latest authored editor content. Empty content is persisted + * immediately and remains authoritative across composer remounts until a + * later non-empty editor update supersedes it. + */ + trackAuthoredContent: (content: string) => void; +}; + +const authoritativelyClearedDraftKeys = new Set(); + +function scopedDraftKey(draftKey: string): string { + return `${getDraftStoreScope()}:${draftKey}`; +} + /** * Owns the draft-persist lifecycle for `MessageComposer`. * @@ -104,8 +120,10 @@ export function useDraftPersistLifecycle({ setSpoileredAttachmentUrls, spoileredAttachmentUrlsRef, syncComposerContentFromEditor, -}: UseDraftPersistLifecycleParams): void { +}: UseDraftPersistLifecycleParams): UseDraftPersistLifecycleResult { const pendingImetaForPersistRef = React.useRef([]); + const emptyContentIsAuthoritativeRef = React.useRef(false); + const isRestoringContentRef = React.useRef(false); const restoredQueuedAttachmentsRef = React.useRef( [], ); @@ -117,7 +135,7 @@ export function useDraftPersistLifecycle({ pendingImetaForPersistRef.current = livePendingImeta; // biome-ignore lint/correctness/useExhaustiveDependencies: effectiveDraftKey is the sole trigger - React.useEffect(() => { + React.useLayoutEffect(() => { // The outgoing draft is persisted by the cleanup below, which runs before // this body on key changes and has the correct outgoing channelId in its // closure. Do NOT re-persist prevKey here: channelId in this render @@ -134,10 +152,21 @@ export function useDraftPersistLifecycle({ : []; } restoreQueuedAttachments?.(restoredQueuedAttachmentsRef.current); + const authoritativeDraftKey = effectiveDraftKey + ? scopedDraftKey(effectiveDraftKey) + : null; + const wasAuthoritativelyCleared = authoritativeDraftKey + ? authoritativelyClearedDraftKeys.has(authoritativeDraftKey) + : false; const saved = effectiveDraftKey ? loadDraft(effectiveDraftKey) : undefined; + emptyContentIsAuthoritativeRef.current = wasAuthoritativelyCleared; + isRestoringContentRef.current = true; if (saved) { - setContent(saved.content); - restoreMentionRefs(saved.mentionRefs ?? []); + const restoredContent = wasAuthoritativelyCleared ? "" : saved.content; + setContent(restoredContent); + restoreMentionRefs( + wasAuthoritativelyCleared ? [] : (saved.mentionRefs ?? []), + ); // Set the persist-snapshot ref SYNCHRONOUSLY before calling the async // state setter, so the cleanup closure (which may fire before the state // update commits in React StrictMode's simulate-unmount pass) reads the @@ -153,6 +182,7 @@ export function useDraftPersistLifecycle({ setPendingImeta([]); setSpoileredAttachmentUrls(new Set()); } + isRestoringContentRef.current = false; return () => { if (effectiveDraftKey) { @@ -160,7 +190,9 @@ export function useDraftPersistLifecycle({ if (queuedAttachments.length > 0) { saveQueuedAttachmentsForDraft?.(effectiveDraftKey, queuedAttachments); } - const content = syncComposerContentFromEditor(); + const content = emptyContentIsAuthoritativeRef.current + ? "" + : syncComposerContentFromEditor(); persistDraft( effectiveDraftKey, content, @@ -172,4 +204,29 @@ export function useDraftPersistLifecycle({ } }; }, [effectiveDraftKey]); + + const trackAuthoredContent = React.useCallback( + (content: string) => { + if (!effectiveDraftKey || isRestoringContentRef.current) return; + const authoritativeDraftKey = scopedDraftKey(effectiveDraftKey); + if (content.length > 0) { + authoritativelyClearedDraftKeys.delete(authoritativeDraftKey); + emptyContentIsAuthoritativeRef.current = false; + return; + } + authoritativelyClearedDraftKeys.add(authoritativeDraftKey); + emptyContentIsAuthoritativeRef.current = true; + persistDraft( + effectiveDraftKey, + content, + channelId ?? effectiveDraftKey, + [...pendingImetaForPersistRef.current], + [...spoileredAttachmentUrlsRef.current], + [], + ); + }, + [channelId, effectiveDraftKey, persistDraft, spoileredAttachmentUrlsRef], + ); + + return { trackAuthoredContent }; } diff --git a/desktop/src/features/messages/ui/useMentionSendFlow.helpers.ts b/desktop/src/features/messages/ui/useMentionSendFlow.helpers.ts index 8176bb13bb..ab7d8c2f4d 100644 --- a/desktop/src/features/messages/ui/useMentionSendFlow.helpers.ts +++ b/desktop/src/features/messages/ui/useMentionSendFlow.helpers.ts @@ -13,7 +13,6 @@ export { MENTION_REFERENCE_TAG }; export type PendingNonMemberMentionSend = { addressedAgentPubkeys: string[]; - audienceRevision: number; inlineAgentMentionPubkeys: string[]; capturedChannelId: string | null; capturedThreadContext: { @@ -38,7 +37,6 @@ export type PendingNonMemberMentionSend = { export type SendMessageWithMentionFlowInput = { addressedAgentPubkeys?: readonly string[]; - audienceRevision?: number; capturedChannelId: string | null; capturedThreadContext?: PendingNonMemberMentionSend["capturedThreadContext"]; pendingImeta: ImetaMedia[]; diff --git a/desktop/src/features/messages/ui/useMentionSendFlow.ts b/desktop/src/features/messages/ui/useMentionSendFlow.ts index 601c3b4113..10ca033272 100644 --- a/desktop/src/features/messages/ui/useMentionSendFlow.ts +++ b/desktop/src/features/messages/ui/useMentionSendFlow.ts @@ -17,21 +17,14 @@ import { dmThreadAgentMentionError } from "@/features/messages/lib/dmThreadAgent import { prepareBackgroundMediaUpload, saveQueuedAttachmentsForDraft, - type QueuedMediaAttachment, } from "@/features/messages/lib/backgroundMediaUploadStore"; -import type { UseChannelLinksResult } from "@/features/messages/lib/useChannelLinks"; -import type { UseEmojiAutocompleteResult } from "@/features/messages/lib/useEmojiAutocomplete"; import { buildOutgoingMessage, type ImetaMedia, } from "@/features/messages/lib/imetaMediaMarkdown"; -import type { UseMentionsResult } from "@/features/messages/lib/useMentions"; -import type { UseRichTextEditorResult } from "@/features/messages/lib/useRichTextEditor"; -import type { UseDraftsResult } from "@/features/messages/lib/useDrafts"; import { useActivePreparedLinkPreviews } from "./useActivePreparedLinkPreviews"; import { invokeTauri } from "@/shared/api/tauri"; -import type { CustomEmoji } from "@/shared/lib/remarkCustomEmoji"; -import type { AcpRuntime, ChannelType, ManagedAgent } from "@/shared/api/types"; +import type { AcpRuntime, ManagedAgent } from "@/shared/api/types"; import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; import { buildCustomEmojiTags } from "@/shared/lib/customEmojiTags"; import { @@ -47,46 +40,8 @@ import { uniqueNormalizedPubkeys, } from "./useMentionSendFlow.helpers"; import { buildAgentAddressMentionTags } from "@/features/messages/lib/agentAddressMention.mjs"; -type UseMentionSendFlowOptions = { - channelId: string | null; - channelLinks: Pick; - channelType: ChannelType | null; - contentRef: React.MutableRefObject; - customEmoji: CustomEmoji[]; - drafts: Pick; - emojiAutocomplete: Pick; - mentions: UseMentionsResult; - onPrepareSendChannel?: (pubkeys?: string[]) => Promise; - onAddressedAgentsSendStarted?: (pubkeys: readonly string[]) => void; - onAddressedAgentsSendFailed?: (pubkeys: readonly string[]) => void; - onInlineAgentMentionsSent?: (promotion: { - expectedRevision: number; - pubkeys: readonly string[]; - }) => void; - onSendRef: React.MutableRefObject< - ( - content: string, - mentionPubkeys: string[], - mediaTags?: string[][], - channelId?: string | null, - threadContext?: { - parentEventId: string | null; - threadHeadId: string | null; - } | null, - forceRest?: boolean, - ) => Promise - >; - richText: Pick; - setContent: (content: string) => void; - setIsEmojiPickerOpen: React.Dispatch>; - setPendingImeta: (pendingImeta: ImetaMedia[]) => void; - hasUnsavedMedia: () => boolean; - clearQueuedAttachments: () => void; - restoreQueuedAttachments: (attachments: QueuedMediaAttachment[]) => void; - setSpoileredAttachmentUrls?: React.Dispatch< - React.SetStateAction> - >; -}; +import type { UseMentionSendFlowOptions } from "./useMentionSendFlow.types"; + export function useMentionSendFlow({ channelId, channelLinks, @@ -98,8 +53,9 @@ export function useMentionSendFlow({ mentions, onPrepareSendChannel, onAddressedAgentsSendStarted, + onAddressedAgentsComposerCleared, onAddressedAgentsSendFailed, - onInlineAgentMentionsSent, + onAddressedAgentsSendSucceeded, onSendRef, richText, setContent, @@ -406,6 +362,7 @@ export function useMentionSendFlow({ ); }; let composerCleared = false; + let optimisticComposerContent = ""; const restoreComposerAfterFailure = () => { if (!composerCleared) return; composerCleared = false; @@ -422,7 +379,7 @@ export function useMentionSendFlow({ } const canRestoreCurrentComposer = canAnimateCurrentComposer && - contentRef.current.trim().length === 0 && + contentRef.current.trim() === optimisticComposerContent.trim() && !hasUnsavedMedia(); if (!canRestoreCurrentComposer && draft.recoveryDraftKey) { saveQueuedAttachmentsForDraft( @@ -451,6 +408,12 @@ export function useMentionSendFlow({ onAddressedAgentsSendStarted?.(draft.addressedAgentPubkeys); } clearComposer(); + if (draft.addressedAgentPubkeys.length > 0) { + optimisticComposerContent = + onAddressedAgentsComposerCleared?.(draft.addressedAgentPubkeys) ?? + ""; + contentRef.current = optimisticComposerContent; + } composerCleared = true; } let uploadStarted = false; @@ -587,12 +550,23 @@ export function useMentionSendFlow({ const sentMentionPubkeys = new Set( revalidatedMentionPubkeys.map(normalizePubkey), ); - onInlineAgentMentionsSent?.({ - expectedRevision: draft.audienceRevision, - pubkeys: draft.inlineAgentMentionPubkeys.filter((pubkey) => - sentMentionPubkeys.has(normalizePubkey(pubkey)), - ), - }); + const newlyPinnedPubkeys = draft.inlineAgentMentionPubkeys.filter( + (pubkey) => sentMentionPubkeys.has(normalizePubkey(pubkey)), + ); + if ( + draft.capturedChannelId === channelIdRef.current || + channelIdRef.current === null + ) { + onAddressedAgentsSendSucceeded?.( + [ + ...new Set([ + ...draft.addressedAgentPubkeys, + ...newlyPinnedPubkeys, + ]), + ], + newlyPinnedPubkeys, + ); + } if (draft.sentDraftKey) { drafts.markDraftSent( draft.sentDraftKey, @@ -604,12 +578,18 @@ export function useMentionSendFlow({ } }; if (preparedUpload) { + let settleUpload!: () => void; + const uploadSettled = new Promise((resolve) => { + settleUpload = resolve; + }); uploadStarted = preparedUpload.start({ onComplete: async (uploaded, signal) => { try { await finishSend(uploaded, signal); } catch { restoreComposerAfterFailure(); + } finally { + settleUpload(); } }, onError: (error) => { @@ -617,14 +597,18 @@ export function useMentionSendFlow({ toast.error( `Upload failed: ${getErrorMessage(error, "Unknown error")}`, ); + settleUpload(); }, onCancel: () => { restoreComposerAfterFailure(); + settleUpload(); }, }); if (!uploadStarted) { + settleUpload(); return restoreComposerAfterFailure(); } + await uploadSettled; } if (!preparedUpload) { try { @@ -657,8 +641,9 @@ export function useMentionSendFlow({ mentions.isAgentPubkey, mentions.revalidateMentionPubkeys, onAddressedAgentsSendStarted, + onAddressedAgentsComposerCleared, onAddressedAgentsSendFailed, - onInlineAgentMentionsSent, + onAddressedAgentsSendSucceeded, onPrepareSendChannel, onSendRef, richText.setContent, @@ -674,7 +659,6 @@ export function useMentionSendFlow({ const sendMessageWithMentionFlow = React.useCallback( async ({ addressedAgentPubkeys = [], - audienceRevision = 0, capturedChannelId, capturedThreadContext = null, pendingImeta, @@ -783,7 +767,6 @@ export function useMentionSendFlow({ const savedMentionRefs = mentions.getDraftMentionRefs(trimmed); const pendingDraft: PendingNonMemberMentionSend = { addressedAgentPubkeys: uniqueNormalizedPubkeys(addressedAgentPubkeys), - audienceRevision, inlineAgentMentionPubkeys: uniqueNormalizedPubkeys( savedMentionRefs .filter((ref) => ref.isAgent) diff --git a/desktop/src/features/messages/ui/useMentionSendFlow.types.ts b/desktop/src/features/messages/ui/useMentionSendFlow.types.ts new file mode 100644 index 0000000000..496a73a94a --- /dev/null +++ b/desktop/src/features/messages/ui/useMentionSendFlow.types.ts @@ -0,0 +1,52 @@ +import type * as React from "react"; +import type { CustomEmoji } from "@/shared/lib/remarkCustomEmoji"; +import type { ChannelType } from "@/shared/api/types"; +import type { ImetaMedia } from "@/features/messages/lib/imetaMediaMarkdown"; +import type { QueuedMediaAttachment } from "@/features/messages/lib/backgroundMediaUploadStore"; +import type { UseChannelLinksResult } from "@/features/messages/lib/useChannelLinks"; +import type { UseEmojiAutocompleteResult } from "@/features/messages/lib/useEmojiAutocomplete"; +import type { UseMentionsResult } from "@/features/messages/lib/useMentions"; +import type { UseRichTextEditorResult } from "@/features/messages/lib/useRichTextEditor"; +import type { UseDraftsResult } from "@/features/messages/lib/useDrafts"; + +export type UseMentionSendFlowOptions = { + channelId: string | null; + channelLinks: Pick; + channelType: ChannelType | null; + contentRef: React.MutableRefObject; + customEmoji: CustomEmoji[]; + drafts: Pick; + emojiAutocomplete: Pick; + mentions: UseMentionsResult; + onPrepareSendChannel?: (pubkeys?: string[]) => Promise; + onAddressedAgentsSendStarted?: (pubkeys: readonly string[]) => void; + onAddressedAgentsComposerCleared?: (pubkeys: readonly string[]) => string; + onAddressedAgentsSendFailed?: (pubkeys: readonly string[]) => void; + onAddressedAgentsSendSucceeded?: ( + pubkeys: readonly string[], + newlyPinnedPubkeys: readonly string[], + ) => void; + onSendRef: React.MutableRefObject< + ( + content: string, + mentionPubkeys: string[], + mediaTags?: string[][], + channelId?: string | null, + threadContext?: { + parentEventId: string | null; + threadHeadId: string | null; + } | null, + forceRest?: boolean, + ) => Promise + >; + richText: Pick; + setContent: (content: string) => void; + setIsEmojiPickerOpen: React.Dispatch>; + setPendingImeta: (pendingImeta: ImetaMedia[]) => void; + hasUnsavedMedia: () => boolean; + clearQueuedAttachments: () => void; + restoreQueuedAttachments: (attachments: QueuedMediaAttachment[]) => void; + setSpoileredAttachmentUrls?: React.Dispatch< + React.SetStateAction> + >; +}; diff --git a/desktop/src/shared/lib/keyboard-shortcuts.ts b/desktop/src/shared/lib/keyboard-shortcuts.ts index e8b388d0dc..d8e1550549 100644 --- a/desktop/src/shared/lib/keyboard-shortcuts.ts +++ b/desktop/src/shared/lib/keyboard-shortcuts.ts @@ -166,9 +166,9 @@ export const KEYBOARD_SHORTCUTS: KeyboardShortcut[] = [ { id: "always-address-agent", label: "Always address agent", - description: "Open the agent picker, or toggle the highlighted agent", - keys: "⇧⌘↵", - keysWindows: "Ctrl+Shift+Enter", + description: "Address the default agent, or select the highlighted agent", + keys: "⇧⌘M", + keysWindows: "Ctrl+Shift+M", category: "Messages", }, { diff --git a/desktop/src/shared/ui/markdown.tsx b/desktop/src/shared/ui/markdown.tsx index 445a7c2aba..e9d4b1e8ec 100644 --- a/desktop/src/shared/ui/markdown.tsx +++ b/desktop/src/shared/ui/markdown.tsx @@ -43,6 +43,7 @@ import { markdownPropsAreEqual, } from "./markdownUtils"; import { ImageMosaic } from "./markdown/ImageMosaic"; +import { ImageGalleryStatus } from "./markdown/ImageGalleryStatus"; import { ImageLightboxZoomControls } from "./markdown/ImageLightboxZoomControls"; import { CODE_BLOCK_CLASS, @@ -145,12 +146,30 @@ type WebKitGestureLikeEvent = Event & { scale?: number; }; +function copyImageToClipboard(src: string | undefined) { + if (!src) return; + invokeTauri("copy_image_to_clipboard", { url: src }) + .then(() => { + toast.success("Copied to clipboard"); + }) + .catch((err: unknown) => { + const msg = err instanceof Error ? err.message : "Copy failed"; + toast.error(msg); + }); +} + +function downloadImage(src: string | undefined) { + if (!src) return; + invokeTauri("download_image", { url: src }).catch((err: unknown) => { + const msg = err instanceof Error ? err.message : "Download failed"; + toast.error(msg); + }); +} + function ImageZoomOverlay({ alt, galleryIndex = 0, galleryItems, - onCopy, - onDownload, onClose, resolvedSrc, sourceBox, @@ -161,8 +180,6 @@ function ImageZoomOverlay({ alt: string | undefined; galleryIndex?: number; galleryItems?: ImageGalleryItem[]; - onCopy: (src: string | undefined) => void; - onDownload: (src: string | undefined) => void; onClose: () => void; resolvedSrc: string; sourceBox: ImageLightboxBox; @@ -718,13 +735,13 @@ function ImageZoomOverlay({ const handleMenuCopy = React.useCallback(() => { setMenu(null); markControlGesture(); - onCopy(currentItem.src); - }, [currentItem.src, markControlGesture, onCopy]); + copyImageToClipboard(currentItem.src); + }, [currentItem.src, markControlGesture]); const handleMenuDownload = React.useCallback(() => { setMenu(null); markControlGesture(); - onDownload(currentItem.src); - }, [currentItem.src, markControlGesture, onDownload]); + downloadImage(currentItem.src); + }, [currentItem.src, markControlGesture]); return createPortal(
{ event.stopPropagation(); - onDownload(currentItem.src); + downloadImage(currentItem.src); }} > @@ -952,6 +969,7 @@ function ImageZoomOverlay({ updateZoom={updateZoom} zoom={zoom} /> +
{menu && canActOnCurrentImage ? ( @@ -1000,7 +1018,6 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { const triggerRef = React.useRef(null); useSmoothCorners(inlineImageRef); useSmoothCorners(thumbnailImageRef); - const [spoilerMediaSize, setSpoilerMediaSize] = React.useState<{ height: number; src: string; @@ -1078,7 +1095,6 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { return () => observer.disconnect(); }, []); - const closeMenu = React.useCallback(() => setMenu(null), []); useDismissMediaContextMenu(Boolean(menu), closeMenu); @@ -1089,7 +1105,6 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { e.nativeEvent.stopImmediatePropagation(); setMenu({ x: e.clientX, y: e.clientY }); }; - const openLightbox = React.useCallback( (image: HTMLImageElement) => { if (!resolvedSrc || isInsideHiddenSpoiler(image)) { @@ -1113,6 +1128,7 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { { alt, dim, + trigger: triggerRef.current, resolvedSrc, src, thumbnailBox: sourceBox, @@ -1140,27 +1156,13 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { const handleCopyImage = React.useCallback((copySrc: string | undefined) => { setMenu(null); - if (!copySrc) return; - invokeTauri("copy_image_to_clipboard", { url: copySrc }) - .then(() => { - toast.success("Copied to clipboard"); - }) - .catch((err: unknown) => { - const msg = err instanceof Error ? err.message : "Copy failed"; - toast.error(msg); - }); + copyImageToClipboard(copySrc); }, []); const handleDownload = React.useCallback( (downloadSrc: string | undefined) => { setMenu(null); - if (!downloadSrc) return; - invokeTauri("download_image", { url: downloadSrc }).catch( - (err: unknown) => { - const msg = err instanceof Error ? err.message : "Download failed"; - toast.error(msg); - }, - ); + downloadImage(downloadSrc); }, [], ); @@ -1215,8 +1217,6 @@ function ImageBlock({ alt, dim, resolvedSrc, src, thumbSrc }: ImageBlockProps) { alt={alt} galleryIndex={lightboxState.galleryIndex} galleryItems={lightboxState.galleryItems} - onCopy={handleCopyImage} - onDownload={handleDownload} onClose={() => setLightboxState(null)} resolvedSrc={resolvedSrc} sourceBox={lightboxState.sourceBox} diff --git a/desktop/src/shared/ui/markdown/ImageGalleryStatus.tsx b/desktop/src/shared/ui/markdown/ImageGalleryStatus.tsx new file mode 100644 index 0000000000..66e7b68b8b --- /dev/null +++ b/desktop/src/shared/ui/markdown/ImageGalleryStatus.tsx @@ -0,0 +1,31 @@ +type ImageGalleryStatusProps = { + currentIndex: number; + itemCount: number; +}; + +export function ImageGalleryStatus({ + currentIndex, + itemCount, +}: ImageGalleryStatusProps) { + if (itemCount <= 1) { + return null; + } + + const position = currentIndex + 1; + return ( + <> +