Building a Responsive Desktop Tool with AI-Generated Code: A Batch Audio Extraction Example

    This article uses a batch audio/video extraction desktop tool as a case study in building AI-generated software that keeps its interface responsive. It explains why running time-consuming tasks in the main thread makes a window show as "Not Responding," then presents a three-layer architecture that decouples the UI, scheduling, and processing layers through thread-safe queues. You'll find working Python/tkinter examples for a background worker thread, main-thread queue polling, cancellation handling, collision-safe file naming, and event throttling, along with a structured way to write prompts and a three-level acceptance checklist that turns generated code into a maintainable tool.

    1. Introduction: A modest requirement exposes the real gaps in generative coding

    Batch audio/video extraction is an ordinary desktop task: you have dozens of screen recordings, course replays, or meeting captures and want only their audio tracks, converted to formats like MP3 or WAV for listening during a commute or for transcription. A script can solve it, but you have to edit paths and parameters every time; an off-the-shelf CLI tool still requires typing commands by hand. So it’s natural to think: have an LLM generate a small tool with a graphical interface.

    This kind of requirement is a good test. Anyone can list the features: pick files, set the output format, start the conversion, exit the program. But add four words to the requirement — “don’t freeze the UI” — and the situation changes completely. If the time-consuming task runs directly in the button’s callback, the window title changes to “Not Responding” the moment conversion starts, the progress bar doesn’t move, users think the program has died, and they end up killing it in the task manager. For many beginners, this is the first real encounter with the concept of the “main thread”; for generated code, this pitfall is both hidden and one of the most likely to cause rework.

    This article doesn’t follow the “build an app in a few lines of code” approach. Instead, it answers three more practical questions:

    1. Why is “a UI that doesn’t freeze” the make-or-break factor for batch conversion tools?
    2. How should the threading and interaction architecture be designed?
    3. How do you describe the requirements clearly and verify the generated code well enough for real use?

    2. Diagnosing the problem: why the UI “freezes”

    2.1 The boundaries of the main thread’s job

    Mainstream desktop GUI frameworks use a single-threaded event loop model. Take tkinter from Python’s standard library: its logic can be summarized as follows:

    1. After the program calls the main loop, the main thread enters a loop that continuously takes tasks;
    2. Events (clicks, input, redraw requests, timed callbacks) are placed in a queue, and the main thread takes and executes them one by one;
    3. Window redraws and interaction responses all happen in this loop.

    This means the main thread is a scarce resource. If a single callback takes too long to execute, the event loop is “stuck,” and all subsequent clicks and redraws can only wait in line.

    2.2 A typical wrong pattern

    The code below is a very common shape in generated tools:

    1. def start(self):
    2. total = len(self.items)
    3. for index, item in enumerate(self.items, 1):
    4. # Wrong: the time-consuming conversion runs directly in the button callback (the main thread)
    5. subprocess.run(["transcoder", "-y", "-i", item.path, item.output], check=True)
    6. self.progress["value"] = index / total * 100
    7. self.status.set(f"Done {index}/{total}")
    8. self.root.update_idletasks() # Attempts to force a UI refresh; treats the symptom, not the cause

    This code has more than one problem:

    • Converting a single file often takes seconds to minutes, and the main thread is fully occupied during the loop;
    • Adding a forced refresh like update_idletasks() after the conversion call only makes the progress bar “jump one notch” and doesn’t let the UI truly respond to input;
    • After the UI shows “success,” the window freezes; users don’t credit the tool, they just think it’s broken.

    Think of the main thread as the only waiter in a restaurant: serving food, wiping tables, and taking payment all depend on one person. If you make him go into the kitchen and watch each dish cook, the diners in the front can only wait. The right approach isn’t to make him faster; it’s to hand the kitchen work to the cooks while the waiter only relays messages.

    3. The solution: three-layer separation plus queue decoupling

    3.1 Overall architecture

    A reliable desktop tool usually has three layers:

    • UI layer: responsible for widget layout and rendering, and collecting user input;
    • Scheduling layer: turns user actions into background tasks, tracks progress, and forwards status;
    • Processing layer: actually performs the time-consuming file processing, with no dependency on any UI code.

    The three layers communicate through thread-safe queues, which is the key to the whole approach. The processing thread only posts messages to the queue; the UI thread only takes messages from the queue. The two threads don’t call each other directly, and the only shared state is one queue and one thread-safe event object that marks cancellation.

    The reason thread safety of the queue is emphasized is that ordinary containers like lists offer no consistency guarantee when read and written concurrently in multiple threads. The standard library’s queue module was designed for exactly this: its put and get operations carry an internal lock, so concurrent access from multiple threads won’t lose or corrupt data.

    3.2 Scheduling and processing: a background thread example

    1. import os
    2. import queue
    3. import subprocess
    4. import threading
    5. from dataclasses import dataclass, field
    6. from pathlib import Path
    7. from typing import List
    8. @dataclass
    9. class ConvertItem:
    10. src: Path # Source video file
    11. dst: Path # Target audio file
    12. @dataclass
    13. class Job:
    14. items: List[ConvertItem] = field(default_factory=list)
    15. cancel: threading.Event = field(default_factory=threading.Event)
    16. @dataclass
    17. class UiEvent:
    18. kind: str # progress / file_done / failed / finished
    19. payload: dict
    20. class Worker(threading.Thread):
    21. """Background worker thread: only does the work and posts messages; never touches any UI widget directly"""
    22. def __init__(self, jobs: "queue.Queue[Job]", events: "queue.Queue[UiEvent]"):
    23. super().__init__(daemon=True) # Ends automatically when the main program exits; doesn't block the process
    24. self.jobs = jobs
    25. self.events = events
    26. def run(self):
    27. while True:
    28. job = self.jobs.get()
    29. if job is None: # Exit signal
    30. break
    31. self._run_job(job)
    32. def _run_job(self, job: Job):
    33. total = len(job.items)
    34. done, failed, completed = 0, 0, 0
    35. for index, item in enumerate(job.items, 1):
    36. if job.cancel.is_set(): # After the user cancels, don't start new conversions
    37. break
    38. try:
    39. # The external transcoder is invoked via PATH; you could instead call an in-process audio library
    40. subprocess.run(
    41. ["transcoder", "-y", "-i", str(item.src), str(item.dst)],
    42. check=True,
    43. stdout=subprocess.DEVNULL,
    44. stderr=subprocess.PIPE,
    45. )
    46. done += 1
    47. completed += 1
    48. self.events.put(UiEvent("file_done", {"index": index, "name": item.src.name}))
    49. except (subprocess.CalledProcessError, OSError) as exc:
    50. failed += 1
    51. self.events.put(UiEvent("failed", {"index": index, "name": item.src.name, "error": str(exc)}))
    52. self.events.put(UiEvent("progress", {"index": index, "total": total,
    53. "done": done, "failed": failed}))
    54. self.events.put(UiEvent("finished", {"completed": completed, "failed": failed,
    55. "total": total, "cancelled": total - completed - failed}))

    A few details in this implementation are worth noting:

    • The thread takes tasks from the queue and uses None as the exit signal, so the main thread can manage its lifecycle centrally;
    • daemon=True ensures the worker thread won’t block the process from exiting even if the UI is force-closed;
    • Each file’s outcome is recorded as success or failure; failures only increment a counter and don’t abort the whole batch;
    • The worker thread never touches any UI widget from start to finish; it only posts messages to the queue.

    3.3 UI consumption: polling the queue in the main thread

    1. POLL_INTERVAL_MS = 100
    2. MAX_EVENTS_PER_POLL = 50 # Max events handled per poll; prevents starving the main thread
    3. def poll_events(root, events: "queue.Queue[UiEvent]", bar, status_var, log, start_btn):
    4. handled = 0
    5. while handled < MAX_EVENTS_PER_POLL:
    6. try:
    7. event = events.get_nowait()
    8. except queue.Empty:
    9. break
    10. handled += 1
    11. if event.kind == "progress":
    12. p = event.payload
    13. bar["value"] = p["index"] / p["total"] * 100
    14. status_var.set(f"Progress {p['index']}/{p['total']} Done {p['done']} Failed {p['failed']}")
    15. elif event.kind == "failed":
    16. log.append(f"[Failed] {event.payload['name']}: {event.payload['error']}")
    17. elif event.kind == "finished":
    18. r = event.payload
    19. status_var.set(f"Finished: done {r['completed']}, failed {r['failed']}, skipped/cancelled {r['cancelled']}")
    20. start_btn.config(state="normal")
    21. # If there are more events, schedule the next poll; if the queue is empty, stop to avoid idle CPU usage
    22. if not events.empty():
    23. root.after(POLL_INTERVAL_MS, poll_events, root, events, bar, status_var, log, start_btn)

    Events are produced in the background thread and consumed in the main thread, so UI refresh and interaction return to the normal rhythm of the event loop. The polling approach here is the easiest to understand. In real projects, there are two other common approaches:

    • Use the thread-safe communication mechanism provided by the GUI framework, letting the framework safely deliver background-thread results to the main thread;
    • Add another state store between the conversion service and the UI, and have the UI read snapshots on a timer to refresh the display.

    Which one to choose depends on the framework and team conventions, but the principle is the same: time-consuming work runs in the background, UI operations run in the main thread.

    3.4 A few easily overlooked details

    Batch event throttling: If the progress bar refreshes once per file, then when dozens of files finish in a row, the UI thread has to handle dozens of events in a short time, and it looks like “a brief freeze.” Handling a limited number of events per poll, or adding an interval check in the progress output, avoids this.

    The two meanings of cancellation:

    • Light cancellation: stop dispatching new conversion tasks, suitable for most scenarios;
    • Hard cancellation: also terminate the currently running subprocess, which requires holding the process handle and calling its terminate method on cancellation.

    If an external tool can’t respond to a termination signal, timeouts and process reaping need to be handled more carefully.

    Log levels: Keep only a one-line summary in the status bar and write each file’s failure reason to the log, so the UI isn’t crammed with long error messages.

    Collision-safe naming: When a file with the same name already exists in the output directory, append a sequence number automatically instead of silently overwriting. For example:

    1. def unique_path(dst: Path) -> Path:
    2. if not dst.exists():
    3. return dst
    4. i = 2
    5. while True:
    6. candidate = dst.with_name(f"{dst.stem}_{i}{dst.suffix}")
    7. if not candidate.exists():
    8. return candidate
    9. i += 1

    Paths and encoding: User files often contain non-ASCII characters, spaces, and special characters. Calling external programs with an argument list rather than concatenating a command string naturally avoids parsing problems caused by special characters; keep logs and error messages in UTF-8 to avoid garbled text across different systems.

    4. Writing clear requirements: from piling up to structuring

    The original author threw out seven or eight requirements at once, and the model did catch them all — which itself shows how far code generation has come. But the vaguer the requirements, the more the results differ from one run to another. A more reliable method is to break the requirements into a few fixed dimensions, each with a verifiable standard:

    • Role and goal: a local tool for non-expert users, aimed at “one-click batch audio extraction”;
    • Tech stack: language, GUI framework version, and whether it needs to be packaged as a portable executable;
    • Input and output: supported video formats, selectable audio formats, and whether to scan subdirectories recursively;
    • Interaction elements: file list (with path and status columns), add/remove buttons, format dropdown, start/cancel buttons, progress bar, status bar, and log area;
    • Performance requirements: conversion runs in a background thread, and the UI can still be dragged, scrolled, and canceled while a task is running;
    • Robustness: give a clear message when an external tool is missing, don’t abort the whole batch when a single file fails, and auto-number same-name files;
    • Acceptance criteria: attach a set of test cases and the way to determine “pass.”

    Example prompt

    1. [Role] Senior desktop software engineer
    2. [Task] Build a local "batch audio/video extraction" desktop tool
    3. [Tech stack] Python 3.9+, standard-library tkinter, able to call an external transcoder on PATH or an audio library
    4. [Features]
    5. 1. Support multi-select of video files, and recursive scanning of an entire directory;
    6. 2. List file name, size, and status (waiting/in progress/success/failed);
    7. 3. Selectable output format, such as MP3, WAV, FLAC, etc.;
    8. 4. Start, cancel, clear list, exit;
    9. 5. Quantitative progress bar + status bar summary + failure detail log.
    10. [Performance] All time-consuming operations must run in a background thread; while a task is running, the UI can be dragged, scrolled, and canceled.
    11. [Robustness] Give an early warning when the external tool is missing or not executable; auto-number same-name outputs; a single-file failure must not affect later files.
    12. [Delivery] Complete runnable single-file code + dependency notes + no fewer than 5 test cases with expected results.

    For the generated code, you can also ask it to output a design note: for example, which logic runs on which thread, how shared state is protected, and where cancellation takes effect. These notes help you locate problems quickly when reading the code, and they force the model to treat thread safety as a question it must answer head-on rather than glossing over.

    5. Acceptance methods: from “it runs” to “worth shipping”

    Once you have the generated code, verify it in three layers.

    First layer, static checks:

    • Run a syntax check or static analysis tool to confirm there are no undefined variables or obvious type errors;
    • Check for bare exception handlers, which quietly swallow real errors;
    • Check whether time-consuming network, file, or subprocess calls appear in UI callback functions.

    Second layer, logic review: follow the main path “start → in progress → cancel → finish,” and confirm that the UI behavior in each state matches expectations. Focus on the exception path: when a single file fails, check whether the counters are correct and whether the log records the specific reason.

    Third layer, real-world testing:

    1. Use several typical kinds of material, such as different container formats, different codecs, very long videos, and filenames with special characters;
    2. In a batch of dozens of files, try dragging the window, scrolling the list, and clicking cancel, and watch whether the UI responds;
    3. Deliberately cause failures, such as removing the external tool or making the output directory read-only, and check whether the messages are clear;
    4. Run it repeatedly and watch for leftover processes.

    For branches like cancellation and exception recovery, unit tests may not cover them; walking through a real scenario by hand is often the most effective. After these three layers of acceptance, “a UI that doesn’t freeze” becomes a reproducible fact rather than a slogan.

    6. Common mistakes and how to avoid them

    Common mistake Actual consequence Avoidance strategy
    Long-running task in a UI callback Window freezes, can’t cancel Run it in a background thread; the main thread only consumes queue messages
    Background thread modifies widgets directly Unpredictable behavior, even crashes Route all UI updates back to the main thread
    Refreshing progress at high frequency for every file Brief UI freeze Control the refresh rate, or cap the number of events handled per pass
    No pre-check of runtime and dependencies The error only appears after clicking Start Before conversion, check whether the external tool exists and is executable
    Silently overwriting same-name output files Data loss, hard to notice Automatically generate a numbered filename
    Exceptions swallowed by bare handlers Nothing to trace Distinguish expected from unexpected exceptions, and log them
    Cancel only stops dispatching; the subprocess keeps running The task isn’t actually interrupted Hold the process handle and set a timeout

    A practical tip: keep a “regression requirements checklist” that matches your own usage habits, and check each item when generating a new version. The checklist doesn’t need to be long — five to ten items is enough — but it turns a subjective impression into a repeatable check.

    7. From a “runnable script” to a “maintainable tool”

    Generated code often runs within minutes, but there’s still a gap between an example and a tool, mainly in a few areas.

    Centralized configuration: Keep polling intervals, the list of supported formats, the default output directory, and so on in one place rather than scattered around.

    Testability: Once the processing logic is decoupled from the UI, the processing layer can be tested on its own without the UI — for example, feed it an input that is guaranteed to fail to verify the error-handling branch.

    Distribution experience: When packaging into an executable, pay attention to dependencies on the external tool, the location of the config file, and the log directory — these details decide whether the first use goes smoothly.

    Version control: Put generated code under version control and leave a note with each change. If you later iterate using an LLM service on a cloud platform — such as the related capabilities offered by Baidu AI Cloud — a clear change log makes each round of adjustment traceable and rollback-able.

    These tasks look trivial, but they are the real dividing line between a “demo program” and a “tool you can hand to a colleague.”

    8. Conclusion: making “no freeze” a default capability

    Generative coding is indeed improving fast: more complete instructions get you more complete implementations, and the model may proactively add details like recursive scanning, format completion, and collision-safe naming. But no matter how capable the tool itself is, it won’t define “done” for you automatically.

    For a batch conversion tool, “done” means: conversion runs in the background, the UI always responds, failures are traceable, same-name files aren’t overwritten, and there’s a clear message when an external tool is missing. Write these requirements into the spec, turn the acceptance methods into a checklist, and the efficiency of generative coding truly becomes delivery quality. Next time you just need to “extract the sound from a video,” hopefully that little tool generated in seconds can steadily see you through to the last task.