AI Coding in Practice: Building a Desktop Tool That Never Freezes the UI

    This article presents a practical, model-agnostic approach to using AI coding tools to build a desktop audio extraction utility that stays responsive, tracks errors, and produces reproducible results. It covers how to turn vague requests into verifiable requirements across functional, non-functional, and acceptance layers; how to design thread boundaries so the UI thread only renders while worker threads handle transcoding through a thread-safe event queue; how to manage external transcoder dependencies with startup and per-task checks, parameter whitelists, and argument-list subprocess calls; and five easily overlooked details such as recursive scan deduplication, same-name protection, cancellation, resume, and on-disk logging. It also shows how follow-up questions and an acceptance checklist expose real implementation gaps, and concludes that treating responsiveness as an architectural constraint and errors as first-class citizens brings generated code closer to a deliverable state.

    1. Background: Why “It Generates Code” Is Not the Same as “It Ships Software”

    As intelligent coding tools spread, the metric developers care about has shifted from “can it generate a snippet” to “can the output reach a runnable, maintainable, and acceptable engineering state.” Take a common desktop utility: batch-extracting audio from videos and exporting it to a standard audio format. The request looks simple, but it actually spans file traversal, format detection, external transcoding dependencies, task scheduling, progress feedback, error recovery, and user interaction.

    The key observation from this exercise: after stating a fairly complete requirement in one pass, the generated result not only covered the explicit asks but also filled in several implicit boundaries and passed syntax validation. What is worth reusing here is not the luck of one particular output, but the engineering method it validated: writing UI responsiveness, exception paths, and acceptance criteria into the requirements up front significantly reduces later rework.

    Note that this article is not about any specific model or platform. It abstracts the problem into a general practice: how to use intelligent coding capabilities to build a desktop audio extraction tool whose UI never freezes, whose errors are traceable, and whose results are reproducible.

    2. Requirements Modeling: Turning “Tedious” into Verifiable Items

    A vague “build me an app” cannot be accepted or verified. A high-quality requirement splits into three layers: functional requirements, non-functional requirements, and acceptance conditions.

    Functional requirements may include:

    • Recognize input from common video container and codec combinations;
    • Support output to widely used lossy and lossless audio formats;
    • Provide file import list, output format settings, start conversion, and exit;
    • Support recursive directory scanning and batch task queuing.

    Non-functional requirements should be explicit:

    • Time-consuming tasks must not occupy the UI main thread;
    • Each task needs a state, progress, and error information;
    • Same-name outputs must not be silently overwritten;
    • When the external transcoding component is missing, show an actionable hint.

    Acceptance conditions are best written as executable statements, for example: “After importing 20 files and clicking start, the UI can still scroll and cancel while tasks run” and “Deliberately feed in a corrupted file; the program must not crash and the status bar must show the failure reason.”

    A reusable prompt skeleton:

    1. Role: Senior desktop application developer
    2. Goal: Implement a batch audio/video extraction tool
    3. Constraints: General GUI framework + external transcoder CLI component
    4. Features: import, recursive scan, format selection, batch conversion, exit
    5. Non-functional: background thread execution, progress callback, error isolation, avoid overwriting
    6. Output: complete code + dependency notes + run steps + self-test checklist

    The point of this style is to turn “no freezing” from an adjective into an architectural constraint, forcing the generation process to produce a threading and callback design.

    3. Architecture Breakdown: Thread Boundaries Are the Root of a Non-Freezing UI

    The reason most generated code leaves the UI unresponsive is not mysterious: the transcoding call is written directly in the button callback, and the UI main loop is blocked by a synchronous wait. The correct approach separates three roles.

    1. UI thread: only rendering, event handling, and state display; no blocking operations.
    2. Worker thread: consumes the task queue and invokes the external transcoder one task at a time.
    3. Communication channel: the worker posts progress, success, failure, and cancellation events back through a thread-safe queue; the UI thread polls periodically and refreshes.

    A sketch of the structure:

    1. import queue
    2. import threading
    3. event_q = queue.Queue()
    4. def worker(task_queue, event_queue):
    5. while True:
    6. task = task_queue.get()
    7. if task is None:
    8. break
    9. try:
    10. # Invoke the external transcoder; parameters come from the task object
    11. event_queue.put(("progress", task.id, 0.5))
    12. event_queue.put(("done", task.id, None))
    13. except Exception as exc:
    14. event_queue.put(("error", task.id, str(exc)))
    15. finally:
    16. task_queue.task_done()

    The UI side only needs to consume events periodically and must avoid touching widgets directly across threads:

    1. def poll_events():
    2. while not event_q.empty():
    3. kind, task_id, payload = event_q.get_nowait()
    4. # Update the progress bar and status bar on the main thread
    5. root.after(100, poll_events)

    The engineering principle here: threads do the work, the main thread does the presentation, and the two are decoupled through message passing. As long as the boundary is clear, UI responsiveness and task duration no longer constrain each other.

    4. External Dependencies and Format Compatibility: Caging Uncertainty

    Audio extraction usually depends on an external transcoding component, which brings two risks: a missing environment and incompatible parameters. A mature solution probes twice, at startup and before task execution.

    • Startup probe: check whether the transcoder can be invoked; if missing, disable the start button and show installation guidance;
    • Task probe: read media info for each input file and detect whether an audio track exists, preventing track-less files from entering the queue and producing ambiguous output;
    • Parameter whitelist: output formats and sampling parameters use a controlled enumeration and do not accept arbitrary string concatenation, reducing injection and illegal-parameter risk.

    When calling the external component, prefer an argument list over a concatenated command string:

    1. cmd = [transcoder, "-y", "-i", src, "-vn", "-acodec", codec, dst]
    2. process = subprocess.run(cmd, capture_output=True, text=True)

    Also, record the full standard error stream to a log instead of only popping up “conversion failed.” Actionable error information is the lowest-cost entry point for diagnosing problems later.

    5. Completeness of Details: Five Points That Are Easy to Miss but Decide the Experience

    The maturity of generated code often shows up where the requirements said nothing.

    1. Recursive scan and deduplication: directory traversal must exclude hidden directories and the tool’s own output directory to avoid self-consumption.
    2. Same-name protection: when an output exists, automatically append a sequence number or timestamp to prevent silent overwrites.
    3. Task cancellation: the worker must periodically check a cancellation flag during long tasks and release resources promptly.
    4. Resume: record a fingerprint of completed tasks and skip them on a rerun to save time.
    5. Persist logs: write the batch ID, file paths, parameters, and error summary to a log for later review.

    These rules can be consolidated into the task object so the UI, worker threads, and logs share a single source of truth.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Task:
    4. id: str
    5. src: str
    6. dst: str
    7. fmt: str
    8. state: str = "pending" # pending/running/done/error/canceled
    9. message: str = ""

    6. Follow-Up Questions and Acceptance: Testing Real Understanding with Edge Cases

    One follow-up question often exposes more implementation holes than ten lines of requirements, for example asking “where is the default output directory?” A high-quality answer states the priority: a user-selected directory first, then the directory of the input file, and finally a fallback to the program’s working directory, along with the configurable items and how they persist. A vague answer means the source of the path was never consolidated in the implementation.

    Suggested acceptance checklist:

    • Does clicking start with an empty list give a clear hint rather than silent inaction?
    • When a single file is corrupted, do the remaining tasks continue?
    • While tasks run, does dragging the window or switching formats keep the UI smooth?
    • Are same-name output conflicts automatically numbered?
    • When the transcoder is missing, is installation guidance provided?
    • Do the logs contain enough information to locate the problem?

    7. Conclusion: Embedding Generation into the Engineering Workflow

    The value of intelligent coding is not to replace the developer’s thinking, but to land constraints the developer has already thought through at high speed. To bring generated results close to a deliverable state, requirements must include the threading model, error strategy, and acceptance criteria; after generation you still need syntax checks, dependency confirmation, and scenario-based self-tests. Treat “no UI freeze” as an architectural problem rather than a wording request, and treat exceptions as first-class citizens, and the generation and iteration efficiency of desktop utility apps will improve noticeably, moving closer to a stable, maintainable engineering artifact.