codex icon indicating copy to clipboard operation
codex copied to clipboard

Play a sound when Codex finishes a prompt / task

Open khryniewiecki opened this issue 1 year ago • 61 comments

Sound when Codex finishes

Summary Please add an optional, clearly audible completion sound that plays when Codex finishes executing a prompt/task (useful when prompts run longer and the user switches focus).

Why Helps when Codex works in background and I’m in another window/tab. Terminal bell \a is too short/quiet and easy to miss.

Use case / Motivation Most of my prompts take Codex quite a long time to execute — often more than a minute. It’s frustrating that I have to sit and stare at the screen just to know when it’s done. Since I work remotely, I could easily use that waiting time to do something else, as long as Codex informs me when it finishes.

Yes, I can (and already did) hack together my own workaround, but it would be much nicer if this were a built-in feature of the extension. For example, after finishing a prompt Codex could simply play a clear sound notification.

Environment VSC

Extras I would be cool if it plays: https://youtu.be/CduA0TULnow?list=RDCduA0TULnow&t=58

Are you interested in implementing this feature?

No response

Additional information

No response

khryniewiecki avatar Sep 20 '25 03:09 khryniewiecki

you can already do that by setting up a notification hook for it in your .codex config.toml.

just add this to your config.toml notify = ["python3", "~/.codex/notify.py"]

and setup a notify.py file

#!/usr/bin/env python3
"""
Minimal notifier for Codex "notify" hook.
Plays a short sound when an agent turn completes.

Usage: Codex runs this script with a single JSON argument.
"""

import json
import os
import subprocess
import sys


def main() -> int:
    if len(sys.argv) != 2:
        return 0

    try:
        event = json.loads(sys.argv[1])
    except Exception:
        event = {}

    if event.get("type") != "agent-turn-complete":
        return 0

    # Prefer a built-in macOS sound if available; fall back to TTS.
    sound_path = "/System/Library/Sounds/Glass.aiff"
    try:
        if os.path.exists(sound_path):
            subprocess.Popen(["afplay", sound_path])
        else:
            subprocess.Popen(["say", "Codex turn complete"])  # best-effort fallback
    except Exception:
        pass

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

robin-liquidium avatar Sep 20 '25 13:09 robin-liquidium

I had to a make a few tweaks (iterm2 on macOS):

  • Relative path didn't work for me in my ~/.codex/config.toml, I had to use absolute path to my home dir

notify = ["python3", "/Users/YOUR_USER_NAME/.codex/notify.py"]

  • Minor change to notify.py to use the terminal bell instead:
#!/usr/bin/env python3
"""
Minimal notifier for Codex "notify" hook.
Plays a short sound when an agent turn completes.

Usage: Codex runs this script with a single JSON argument.
"""

import sys
import json

def main():
    if len(sys.argv) != 2:
        return 0

    try:
        event = json.loads(sys.argv[1])
    except Exception:
        return 0

    if event.get("type") != "agent-turn-complete":
        return 0

    # Print BEL character -> terminal bell
    sys.stdout.write("\a")
    sys.stdout.flush()
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
  • To test once it's all set up run: python3 ~/.codex/notify.py '{"type":"agent-turn-complete"}'

markgrover avatar Sep 25 '25 03:09 markgrover

Love this ask. I implemented a cross-platform MVP that’s opt-in and uses system sounds (no bundled assets).

Proposal

  • notifications.sound = true|false (default false)
  • notifications.only_on_long_runs_ms = 0
  • notifications.success_tone = "default" / notifications.error_tone = "default"
    • Maps to OS-appropriate system sounds:
      • macOS → Hero (success), Basso (error)
      • Windows → SystemSounds.Asterisk (success), SystemSounds.Hand (error)
      • Linux → canberra id complete (success), dialog-error (error)
  • Fallback: terminal bell (\a) if no backend available
  • Fires only on final agent-turn-complete

Why

  • Improves the UX for long-running tasks without requiring custom notify hook scripts
  • Only system sounds → zero new binary assets
  • Safe defaults, fully optional, and configurable via ~/.codex/config.toml
  • Increasingly relevant as model time horizons grow longer — Codex runs already take tens of minutes in some cases. An audible success/failure cue makes it possible to safely multitask while waiting.

Example Config

[notifications]
sound = true
only_on_long_runs_ms = 10000
success_tone = "default"
error_tone = "default"

Opened a PR to implement this: #4329

It adds:

  • notifications.sound (default off)
  • notifications.only_on_long_runs_ms
  • success_tone / error_tone with sensible per-OS defaults
  • Fallback to terminal bell

Cross-platform mappings:

  • macOS → Hero (success), Basso (error)
  • Windows → SystemSounds.Asterisk / Hand
  • Linux → canberra complete / dialog-error

samlouiscohen avatar Sep 27 '25 01:09 samlouiscohen

Would this proposal result in the cli playing a sound if the task pauses asking for approval?

atreeon avatar Oct 01 '25 15:10 atreeon

Hi @samlouiscohen , does your code change work for the VS Code extension as well? Or only the CLI version of Codex?

jsh9 avatar Oct 05 '25 16:10 jsh9

我尝试了很多次,都通知失败,最后,我把notify = ["python3", "/Users/wang/.codex/notify.py"] 放到disable_response_storage = true的后面一行 成功了,(我之前一直放在 trust_level = "trusted" 后面,导致一直失败,很神奇)

budingkak12 avatar Oct 18 '25 15:10 budingkak12

"I tried many times, but the notification failed every time. Finally, I moved the line notify = ["python3", "/Users/wang/.codex/notify.py"] right after disable_response_storage = true, and it worked! (It's strange because it kept failing when I had it after trust_level = "trusted".)"

budingkak12 avatar Oct 18 '25 15:10 budingkak12

For macOS users, I found a simple way to play sounds or notifications using the Shortcuts app, which has higher permissions. I configured the TOML file accordingly.

notify = ["zsh", "/Users/roger/.codex/notify.sh"]

[tui]
notifications = true
#!/bin/zsh
/usr/bin/shortcuts run "Codex Done"
Image

rijieli avatar Oct 19 '25 05:10 rijieli

The following worked for me on macOS, simple and easy to maintain, without the hassle of creating a Python script (notify.py) or a Shortcut.

In ~/.codex/config.toml, add this line:

model = "gpt-5-codex"
model_reasoning_effort = "low"
+ notify = ["bash", "-lc", "afplay /System/Library/Sounds/Bottle.aiff"]

/System/Library/Sounds has many different ringtones for you to choose. You don't have to use my choice.

/System/Library/Sounds
├── Basso.aiff
├── Blow.aiff
├── Bottle.aiff
├── Frog.aiff
├── Funk.aiff
├── Glass.aiff
├── Hero.aiff
├── Morse.aiff
├── Ping.aiff
├── Pop.aiff
├── Purr.aiff
├── Sosumi.aiff
├── Submarine.aiff
└── Tink.aiff

(Inspired by https://github.com/openai/codex/issues/4998#issuecomment-3386645329)

jsh9 avatar Oct 21 '25 03:10 jsh9

Will they add this?

Ahmet-Dedeler avatar Nov 21 '25 09:11 Ahmet-Dedeler

@Ahmet-Dedeler Just ask the Codex to do a terminal beep after a task.

antonurankar-moloco avatar Nov 24 '25 07:11 antonurankar-moloco

you can already do that by setting up a notification hook for it in your .codex config.toml.

just add this to your config.toml notify = ["python3", "~/.codex/notify.py"]

and setup a notify.py file

#!/usr/bin/env python3
"""
Minimal notifier for Codex "notify" hook.
Plays a short sound when an agent turn completes.

Usage: Codex runs this script with a single JSON argument.
"""

import json
import os
import subprocess
import sys


def main() -> int:
    if len(sys.argv) != 2:
        return 0

    try:
        event = json.loads(sys.argv[1])
    except Exception:
        event = {}

    if event.get("type") != "agent-turn-complete":
        return 0

    # Prefer a built-in macOS sound if available; fall back to TTS.
    sound_path = "/System/Library/Sounds/Glass.aiff"
    try:
        if os.path.exists(sound_path):
            subprocess.Popen(["afplay", sound_path])
        else:
            subprocess.Popen(["say", "Codex turn complete"])  # best-effort fallback
    except Exception:
        pass

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

This script helps a lot. Here is a similar script generated by gpt-5-mini. It also works in macOS.

#!/usr/bin/env python3
"""
Notifier for Codex "notify" hook (updated).

Behavior changes:
- For every event with type == "agent-turn-complete", the script will now:
    * play a sound (as before)
    * show a system notification (new: regardless of whether it's the final turn)
- If the event heuristically indicates the conversation ended, the notification title/message
  will reflect that; otherwise a shorter "Agent turn complete" notification is shown.
- Cross-platform best-effort: macOS (osascript), Linux (notify-send / DBus), Windows (PowerShell NotifyIcon).
- External calls are wrapped in try/except so the hook never crashes.
"""

import json
import os
import platform
import shutil
import subprocess
import sys
from typing import Any, Dict


def shutil_which(cmd: str) -> bool:
    """Return True if command is found in PATH (wrapper around shutil.which)."""
    try:
        return shutil.which(cmd) is not None
    except Exception:
        return False


def play_sound():
    """Play a short notification sound. Prefer macOS system sound; fallback to TTS or other utilities."""
    system = platform.system()
    try:
        if system == "Darwin":
            sound_path = "/System/Library/Sounds/Glass.aiff"
            if os.path.exists(sound_path) and shutil_which("afplay"):
                subprocess.Popen(["afplay", sound_path])
                return
            if shutil_which("say"):
                subprocess.Popen(["say", "Codex turn complete"])
                return
        elif system == "Linux":
            # Try common desktop sounds or TTS utilities
            if shutil_which("paplay") and os.path.exists("/usr/share/sounds/freedesktop/stereo/complete.oga"):
                subprocess.Popen(["paplay", "/usr/share/sounds/freedesktop/stereo/complete.oga"])
                return
            if shutil_which("aplay") and os.path.exists("/usr/share/sounds/alsa/Front_Center.wav"):
                subprocess.Popen(["aplay", "/usr/share/sounds/alsa/Front_Center.wav"])
                return
            if shutil_which("espeak"):
                subprocess.Popen(["espeak", "Codex turn complete"])
                return
            if shutil_which("spd-say"):
                subprocess.Popen(["spd-say", "Codex turn complete"])
                return
        elif system == "Windows":
            # Use PowerShell SAPI speak as a fallback
            ps = 'Add-Type –AssemblyName System.Speech; $s = New-Object System.Speech.Synthesis.SpeechSynthesizer; $s.Speak("Codex turn complete");'
            subprocess.Popen(["powershell", "-NoProfile", "-Command", ps])
            return
    except Exception:
        # ignore any failures
        pass


def show_notification(title: str, message: str, subtitle: str = ""):
    """
    Show a system notification in a cross-platform, best-effort way.
    - macOS: use osascript display notification (supports subtitle and sound)
    - Linux: try notify-send (libnotify) or gi.repository.Notify
    - Windows: use a PowerShell snippet with System.Windows.Forms.NotifyIcon (balloon)
    """
    system = platform.system()

    try:
        if system == "Darwin":
            # Escape quotes and backslashes
            esc_msg = message.replace("\\", "\\\\").replace('"', '\\"')
            esc_title = title.replace("\\", "\\\\").replace('"', '\\"')
            esc_sub = subtitle.replace("\\", "\\\\").replace('"', '\\"')
            script = f'display notification "{esc_msg}" with title "{esc_title}"'
            if esc_sub:
                script += f' subtitle "{esc_sub}"'
            script += ' sound name "Glass"'
            subprocess.Popen(["osascript", "-e", script])
            return

        elif system == "Linux":
            # Try notify-send (libnotify)
            if shutil_which("notify-send"):
                subprocess.Popen(["notify-send", title, message, "-u", "normal", "-t", "10000"])
                return
            # Try Python DBus/GObject notification (best-effort)
            try:
                from gi.repository import Notify  # type: ignore
                Notify.init("Codex")
                n = Notify.Notification.new(title, message, None)
                n.set_timeout(10000)
                n.show()
                return
            except Exception:
                pass

        elif system == "Windows":
            # Create a balloon tip via System.Windows.Forms.NotifyIcon
            esc_title = title.replace("'", "''")
            esc_message = message.replace("'", "''")
            ps_script = (
                "$title = '{t}'; $msg = '{m}'; "
                "[void][Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); "
                "[void][Reflection.Assembly]::LoadWithPartialName('System.Drawing'); "
                "$notify = New-Object System.Windows.Forms.NotifyIcon; "
                "$notify.Icon = [System.Drawing.SystemIcons]::Information; "
                "$notify.BalloonTipTitle = $title; "
                "$notify.BalloonTipText = $msg; "
                "$notify.Visible = $true; "
                "$notify.ShowBalloonTip(10000); "
                "Start-Sleep -Seconds 6; "
                "$notify.Dispose();"
            ).format(t=esc_title, m=esc_message)
            subprocess.Popen(["powershell", "-NoProfile", "-Command", ps_script])
            return

    except Exception:
        # Ignore notification errors and fall back to printing
        pass

    # Final fallback: print to stderr
    try:
        print(f"[Notification] {title}: {message}", file=sys.stderr)
    except Exception:
        pass


def event_signals_conversation_end(event: Dict[str, Any]) -> bool:
    """
    Heuristic to determine whether the event indicates the conversation ended.
    Checks many common fields to be tolerant of different event shapes.
    """
    if not isinstance(event, dict):
        return False

    # Direct boolean flags
    for key in ("is_last_turn", "conversation_end", "conversation_finished", "final", "closed"):
        if key in event and bool(event.get(key)):
            return True

    # Check nested dicts
    for container_key in ("payload", "metadata", "data", "details"):
        sub = event.get(container_key)
        if isinstance(sub, dict):
            for key in ("conversation_end", "conversation_finished", "is_last_turn", "final"):
                if key in sub and bool(sub.get(key)):
                    return True

    # State string
    state = event.get("conversation_state") or event.get("state")
    if isinstance(state, str):
        if state.lower() in ("finished", "ended", "closed", "complete"):
            return True

    # turn/total heuristics
    try:
        turn = event.get("turn")
        total = event.get("total_turns") or event.get("turns_total") or event.get("total_turns_estimate")
        if isinstance(turn, int) and isinstance(total, int) and turn >= total:
            return True
    except Exception:
        pass

    return False


def build_notification_text(event: Dict[str, Any]) -> (str, str, str):
    """
    Build (title, message, subtitle) for the notification based on the event.
    This is called for every agent-turn-complete event (so notifications always appear).
    """
    # Detect end vs non-end
    is_end = event_signals_conversation_end(event)

    if is_end:
        title = "Codex — Conversation finished"
        summary = (
            event.get("summary")
            or event.get("message")
            or (event.get("payload") or {}).get("summary")
            or (event.get("metadata") or {}).get("summary")
            or event.get("text")
            or "The conversation has ended."
        )
        msg = str(summary)
        if len(msg) > 240:
            msg = msg[:236] + "..."
        subtitle = event.get("agent") or (event.get("metadata") or {}).get("agent") or ""
        return title, msg, str(subtitle)
    else:
        # Non-final agent turn: show a short notification
        title = "Codex — Agent turn complete"
        # Prefer a short snippet if available
        snippet = (
            event.get("message")
            or event.get("text")
            or (event.get("payload") or {}).get("snippet")
            or (event.get("metadata") or {}).get("snippet")
            or event.get("summary")
            or "An agent finished a turn."
        )
        msg = str(snippet)
        if len(msg) > 200:
            msg = msg[:196] + "..."
        subtitle = event.get("agent") or ""
        return title, msg, str(subtitle)


def main() -> int:
    # Expect exactly one JSON argument (same pattern as original)
    if len(sys.argv) != 2:
        return 0

    try:
        event = json.loads(sys.argv[1])
    except Exception:
        event = {}

    # Only act on agent-turn-complete events (preserve original behavior)
    if event.get("type") != "agent-turn-complete":
        return 0

    # Always play a sound when an agent turn completes
    try:
        play_sound()
    except Exception:
        pass

    # Always show a notification for agent-turn-complete (user request)
    try:
        title, msg, subtitle = build_notification_text(event)
        show_notification(title, msg, subtitle)
    except Exception:
        pass

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

How to use this script:

Below is a brief description and testing suggestions:
- Main modification: Now, whenever event.type == "agent-turn-complete" is received, the script will simultaneously play a sound and pop up a system notification (regardless of whether it is the last turn). If the event is heuristically judged as "conversation finished," the notification title/content will show "Conversation finished"; otherwise, it will show "Agent turn complete" and display a brief excerpt.
- Testing method: Use your previous test_notifier.py (or the test script I provided before) to run the following command:
    - Assuming saved as notifier.py and test_notifier.py:
        - python3 test_notifier.py ./notify.py

- Observations:
    - agent-turn-complete-not-end (e.g., {"type":"agent-turn-complete","turn":1,"total_turns":5}) — should play sound and pop up a brief notification.
    - Events with is_last_turn or payload.conversation_finished — should play sound and pop up a "Conversation finished" notification (including summary).

- If notifications are not seen on some platforms:
    - macOS: Run osascript -e 'display notification "test" with title "Test"' in terminal to test; afplay/say/osascript are usually available by default.
    - Linux: Ensure notify-send (libnotify) or python-gi is installed.
    - Windows: Confirm running in desktop session, PowerShell available; bubbles may be blocked under remote desktop or some security policies.

Here is the test script:

#!/usr/bin/env python3
"""
Test harness for the notifier script.

This script runs several sample events against the notifier and prints the
notifier's exit code and any stdout/stderr. It pauses briefly between tests
so sounds/notifications can be seen/heard.

Usage:
    python3 test_notifier.py [path_to_notifier_script]

If path_to_notifier_script is omitted, ./notifier.py is used by default.
"""

import json
import os
import subprocess
import sys
import time


def run_test(name, event, notifier_path):
    """Run a single test: call notifier with JSON argument and print results."""
    print(f"\n--- Test: {name} ---")
    arg = json.dumps(event)
    print("Event JSON:", arg)
    try:
        completed = subprocess.run(
            [sys.executable, notifier_path, arg],
            capture_output=True,
            text=True,
            timeout=20,
        )
        print("Return code:", completed.returncode)
        if completed.stdout:
            print("Stdout:", completed.stdout.strip())
        if completed.stderr:
            print("Stderr:", completed.stderr.strip())
    except subprocess.TimeoutExpired:
        print("Error: notifier timed out")
    except FileNotFoundError:
        print(f"Error: notifier script not found at {notifier_path}")
    except Exception as e:
        print("Error running notifier:", repr(e))

    # Wait so the notification/sound has time to appear
    time.sleep(3)


def main():
    notifier_path = sys.argv[1] if len(sys.argv) > 1 else "./notifier.py"
    if not os.path.exists(notifier_path):
        print("Notifier script not found at", notifier_path)
        sys.exit(2)

    tests = [
        # 1) Non-agent event: should do nothing
        ("non-agent-event", {"type": "other-event"}),
        # 2) Agent turn complete but not end: should at least play a sound
        ("agent-turn-complete-not-end", {"type": "agent-turn-complete", "turn": 1, "total_turns": 5}),
        # 3) Agent turn complete with explicit is_last_turn boolean (should notify)
        ("agent-turn-complete-is-last", {"type": "agent-turn-complete", "is_last_turn": True, "summary": "Final summary: conversation complete."}),
        # 4) Agent turn complete with nested payload flag
        ("agent-turn-complete-payload-flag", {"type": "agent-turn-complete", "payload": {"conversation_finished": True, "summary": "Finished via payload flag"}}),
        # 5) Agent turn complete with conversation_state string
        ("agent-turn-complete-state-finished", {"type": "agent-turn-complete", "conversation_state": "finished", "text": "Conversation reached finished state"}),
    ]

    print("Using notifier at:", notifier_path)
    print("Starting tests. You should hear sounds and (for end events) see system notifications if your platform supports them.\n")

    for name, event in tests:
        run_test(name, event, notifier_path)

    print("\nAll tests completed.")


if __name__ == "__main__":
    main()

huangwb8 avatar Nov 25 '25 08:11 huangwb8

@Ahmet-Dedeler Just ask the Codex to do a terminal beep after a task.

On a Mac that would be the same as setting ~/.codex/config.toml:

notify = ["tput", "bel"]

Unfortunately it does not sound the bel(l) on permission requests though.

nialse avatar Dec 10 '25 07:12 nialse

I developed a python package to do this. For MacOS/Linux/Windows; For Claude Code/Codex. More details in huangwb8/VibeNotification

huangwb8 avatar Dec 21 '25 08:12 huangwb8

on a mac:

$ brew install terminal-notifier

In codex config.toml, add this:

notify = ["bash", "-lc", "echo 'Codex Needs Your Attention' | terminal-notifier -sound default"]

jiananlu avatar Dec 22 '25 14:12 jiananlu

@Ahmet-Dedeler Just ask the Codex to do a terminal beep after a task.

On a Mac that would be the same as setting ~/.codex/config.toml:

notify = ["tput", "bel"]

Unfortunately it does not sound the bel(l) on permission requests though.

I find that on Linux, tput bel does not accept the additional parameter that is passed down by codex and will fail silently.

A more portable solution on POSIX is:

notify = ["printf", "\\a%.0s"]

The %.0s conversion will shallow up the additional argument.

PkmX avatar Dec 22 '25 21:12 PkmX

The following worked for me on macOS, simple and easy to maintain, without the hassle of creating a Python script (notify.py) or a Shortcut.

In ~/.codex/config.toml, add this line:

model = "gpt-5-codex" model_reasoning_effort = "low"

  • notify = ["bash", "-lc", "afplay /System/Library/Sounds/Bottle.aiff"] /System/Library/Sounds has many different ringtones for you to choose. You don't have to use my choice.
/System/Library/Sounds
├── Basso.aiff
├── Blow.aiff
├── Bottle.aiff
├── Frog.aiff
├── Funk.aiff
├── Glass.aiff
├── Hero.aiff
├── Morse.aiff
├── Ping.aiff
├── Pop.aiff
├── Purr.aiff
├── Sosumi.aiff
├── Submarine.aiff
└── Tink.aiff

(Inspired by #4998 (comment))

It raises error › /Users/xx/.bash_profile: line 38: syntax error: unexpected end of file after it played the sound

wybert avatar Jan 01 '26 15:01 wybert

Hey everyone, I’ve been using Codex since last September, and I just can't understand why it requires users to write their own script for the task completion notifications feature. Is that really a good user experience? I don't think so. Even Google’s new Antigravity feature does this better than Codex.

I’m not really sure how difficult this is to implement. Can someone explain it to me? (Genuinely asking)

evan2306 avatar Jan 07 '26 21:01 evan2306

For anyone that struggles with sound integration - codex-1up comes with sound options. (Not a fork)

https://github.com/regenrek/codex-1up

regenrek avatar Jan 09 '26 10:01 regenrek

I already implemented this a while ago, but it got closed. My mistake I didn't check on these issues first. I just forked and did it for my own use but it can be an starting point.

It sounds a beep when task id done or user input is required, and has a simple menu option to enable/disable. I have been using this daily with proper behavior on ubuntu 24.04:

https://github.com/openai/codex/pull/8417#issuecomment-3680900135

fahedslx avatar Jan 13 '26 03:01 fahedslx